编辑器模块(笔记)初版
This commit is contained in:
1 parent
7e65825d3e
commit
ad987111a3
66 files changed
+17470
-283
No files matched your search
Generated
+153
-211
@@ -85,15 +85,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "alloc-no-stdlib"
|
||||
version = "2.0.4"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
|
||||
checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"
|
||||
|
||||
[[package]]
|
||||
name = "alloc-stdlib"
|
||||
version = "0.2.4"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
|
||||
checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
]
|
||||
@@ -735,9 +735,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "brotli"
|
||||
version = "8.0.4"
|
||||
version = "9.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3"
|
||||
checksum = "f8b851b75c23ca7873623d612fe49bd1989aeb03d08fb9432187eb253d3d4c6b"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
"alloc-stdlib",
|
||||
@@ -746,9 +746,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "brotli-decompressor"
|
||||
version = "5.0.3"
|
||||
version = "6.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
|
||||
checksum = "941cd9bd4ddab83cb46fa5a2d428f1c857b24ac78cb876cf7beb710840934bd7"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
"alloc-stdlib",
|
||||
@@ -885,12 +885,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cargo_toml"
|
||||
version = "0.22.3"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "374b7c592d9c00c1f4972ea58390ac6b18cbb6ab79011f3bdc90a0b82ca06b77"
|
||||
checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9"
|
||||
dependencies = [
|
||||
"semver",
|
||||
"serde",
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
"toml 1.1.2+spec-1.1.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -931,13 +932,13 @@ checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"
|
||||
|
||||
[[package]]
|
||||
name = "cfb"
|
||||
version = "0.7.3"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d38f2da7a0a2c4ccf0065be06397cc26a81f4e528be095826eee9d4adbb8c60f"
|
||||
checksum = "a347dcabdae9c31b0825fd6a8bed285ec9c2acb89c47827126d52fa4f59cece3"
|
||||
dependencies = [
|
||||
"byteorder",
|
||||
"fnv",
|
||||
"uuid",
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1366,9 +1367,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cssparser"
|
||||
version = "0.36.0"
|
||||
version = "0.37.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dae61cf9c0abb83bd659dab65b7e4e38d8236824c85f0f804f173567bda257d2"
|
||||
checksum = "8c9cdaae01d5ed7882b04d795e7f752f46ff52d2fa3b50a20d28c464510bba98"
|
||||
dependencies = [
|
||||
"cssparser-macros",
|
||||
"dtoa-short",
|
||||
@@ -1379,29 +1380,19 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cssparser-macros"
|
||||
version = "0.6.1"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331"
|
||||
checksum = "d045de693cb712d0b22c6a64be5b953f67b3ce00ab5ad3dd5d8b441886ab8e1a"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
"syn 3.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ctor"
|
||||
version = "0.8.0"
|
||||
version = "1.0.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "352d39c2f7bef1d6ad73db6f5160efcaed66d94ef8c6c573a8410c00bf909a98"
|
||||
dependencies = [
|
||||
"ctor-proc-macro",
|
||||
"dtor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ctor-proc-macro"
|
||||
version = "0.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "52560adf09603e58c9a7ee1fe1dcb95a16927b17c127f0ac02d6e768a0e25bc1"
|
||||
checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d"
|
||||
|
||||
[[package]]
|
||||
name = "ctr"
|
||||
@@ -1664,9 +1655,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "dirs"
|
||||
version = "6.0.0"
|
||||
version = "7.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"
|
||||
checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f"
|
||||
dependencies = [
|
||||
"dirs-sys 0.5.0",
|
||||
]
|
||||
@@ -1754,9 +1745,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "dom_query"
|
||||
version = "0.27.0"
|
||||
version = "0.28.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "521e380c0c8afb8d9a1e83a1822ee03556fc3e3e7dbc1fd30be14e37f9cb3f89"
|
||||
checksum = "fac5fca71e65e94cc718a6e2af65d6e0f9c6027751c2aa562fbb5087fda639bc"
|
||||
dependencies = [
|
||||
"bit-set",
|
||||
"cssparser",
|
||||
@@ -1803,21 +1794,6 @@ dependencies = [
|
||||
"dtoa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dtor"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1057d6c64987086ff8ed0fd3fbf377a6b7d205cc7715868cd401705f715cbe4"
|
||||
dependencies = [
|
||||
"dtor-proc-macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dtor-proc-macro"
|
||||
version = "0.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f678cf4a922c215c63e0de95eb1ff08a958a81d47e485cf9da1e27bf6305cfa5"
|
||||
|
||||
[[package]]
|
||||
name = "dunce"
|
||||
version = "1.0.5"
|
||||
@@ -2573,7 +2549,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8c386b0a4a70cb2d39fffd74480f985b6f0bfbcb934b6a6b6b7e630e448f242e"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"keyboard-types",
|
||||
"keyboard-types 0.7.0",
|
||||
"objc2",
|
||||
"objc2-app-kit",
|
||||
"once_cell",
|
||||
@@ -2830,9 +2806,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "html5ever"
|
||||
version = "0.38.0"
|
||||
version = "0.39.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1054432bae2f14e0061e33d23402fbaa67a921d319d56adc6bcf887ddad1cbc2"
|
||||
checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8"
|
||||
dependencies = [
|
||||
"log",
|
||||
"markup5ever",
|
||||
@@ -2985,7 +2961,7 @@ dependencies = [
|
||||
"js-sys",
|
||||
"log",
|
||||
"wasm-bindgen",
|
||||
"windows-core 0.62.2",
|
||||
"windows-core 0.57.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3167,9 +3143,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "infer"
|
||||
version = "0.19.0"
|
||||
version = "0.22.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a588916bfdfd92e71cacef98a63d9b1f0d74d6599980d11894290e7ddefffcf7"
|
||||
checksum = "f4200d433cbd5178df7797c9c2e75b348b728e39631cf14520d1e2fc424201f4"
|
||||
dependencies = [
|
||||
"cfb",
|
||||
]
|
||||
@@ -3383,21 +3359,21 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "json-patch"
|
||||
version = "3.0.1"
|
||||
version = "4.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "863726d7afb6bc2590eeff7135d923545e5e964f004c2ccf8716c25e70a86f08"
|
||||
checksum = "7421438de105a0827e44fadd05377727847d717c80ce29a229f85fd04c427b72"
|
||||
dependencies = [
|
||||
"jsonptr",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 1.0.69",
|
||||
"thiserror 2.0.20",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jsonptr"
|
||||
version = "0.6.3"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5dea2b27dd239b2556ed7a25ba842fe47fd602e7fc7433c2a8d6106d4d9edd70"
|
||||
checksum = "a5a3cc660ba5d72bce0b3bb295bf20847ccbb40fd423f3f05b61273672e561fe"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -3434,6 +3410,16 @@ dependencies = [
|
||||
"unicode-segmentation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "keyboard-types"
|
||||
version = "0.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "keyring"
|
||||
version = "3.6.3"
|
||||
@@ -3822,7 +3808,7 @@ dependencies = [
|
||||
"httparse",
|
||||
"librqbit-dualstack-sockets",
|
||||
"network-interface",
|
||||
"quick-xml",
|
||||
"quick-xml 0.41.0",
|
||||
"reqwest 0.13.4",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
@@ -3968,9 +3954,9 @@ checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b"
|
||||
|
||||
[[package]]
|
||||
name = "markup5ever"
|
||||
version = "0.38.0"
|
||||
version = "0.39.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8983d30f2915feeaaab2d6babdd6bc7e9ed1a00b66b5e6d74df19aa9c0e91862"
|
||||
checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de"
|
||||
dependencies = [
|
||||
"log",
|
||||
"tendril",
|
||||
@@ -4125,14 +4111,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "muda"
|
||||
version = "0.19.3"
|
||||
version = "0.20.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1dd04e60bc0b07438a6771710ee1698f98f6ebbc7f89b61264af1563b8aeb878"
|
||||
checksum = "cca139e57da4383727f189e43e66e84fa372347027fc996f9f1a007ec0a37996"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"dpi",
|
||||
"gtk",
|
||||
"keyboard-types",
|
||||
"keyboard-types 0.8.3",
|
||||
"objc2",
|
||||
"objc2-app-kit",
|
||||
"objc2-core-foundation",
|
||||
@@ -4441,6 +4427,7 @@ dependencies = [
|
||||
"objc2",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation",
|
||||
"objc2-quartz-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5080,7 +5067,7 @@ checksum = "7da1d65da6dd5d1e44199ac0f58712d241c0f439f80adea8924d832384087f85"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"indexmap 2.14.0",
|
||||
"quick-xml",
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
"time",
|
||||
]
|
||||
@@ -5328,6 +5315,15 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quick-xml"
|
||||
version = "0.42.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quinn"
|
||||
version = "0.11.11"
|
||||
@@ -6213,9 +6209,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "selectors"
|
||||
version = "0.36.1"
|
||||
version = "0.38.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c5d9c0c92a92d33f08817311cf3f2c29a3538a8240e94a6a3c622ce652d7e00c"
|
||||
checksum = "8adfa1c298912827b8a28b223b3b874357397ae706e6190acd9bf28cee99114d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"cssparser",
|
||||
@@ -6878,9 +6874,9 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
||||
|
||||
[[package]]
|
||||
name = "swift-rs"
|
||||
version = "1.0.7"
|
||||
version = "1.0.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4057c98e2e852d51fdcfca832aac7b571f6b351ad159f9eda5db1655f8d0c4d7"
|
||||
checksum = "e45c444e496845d3f2a351146bff59aae4975b2280238df1dfaa0c7d1846f38e"
|
||||
dependencies = [
|
||||
"base64 0.21.7",
|
||||
"serde",
|
||||
@@ -7175,9 +7171,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tao"
|
||||
version = "0.35.3"
|
||||
version = "0.37.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d1c93047acf68669466a34690ac58cca7010bd1b201e1ec86f1fd0a75d3dd4a9"
|
||||
checksum = "f37f381f4e048e6cdf038b5705f8cf14ad108279d46eb968140a7b291aba9400"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"block2",
|
||||
@@ -7195,29 +7191,29 @@ dependencies = [
|
||||
"libc",
|
||||
"log",
|
||||
"ndk",
|
||||
"ndk-context",
|
||||
"ndk-sys",
|
||||
"objc2",
|
||||
"objc2-app-kit",
|
||||
"objc2-foundation",
|
||||
"objc2-ui-kit",
|
||||
"once_cell",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"raw-window-handle",
|
||||
"tao-macros",
|
||||
"unicode-segmentation",
|
||||
"url",
|
||||
"windows 0.61.3",
|
||||
"windows-core 0.61.2",
|
||||
"windows 0.62.2",
|
||||
"windows-core 0.62.2",
|
||||
"windows-version",
|
||||
"x11-dl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tao-macros"
|
||||
version = "0.1.3"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f4e16beb8b2ac17db28eab8bca40e62dbfbb34c0fcdc6d9826b11b7b5d047dfd"
|
||||
checksum = "5f7eeb6d99155545da6150a1795945f16ac9c178deb2a5f2e74d776107bd5849"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -7238,14 +7234,14 @@ checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
|
||||
|
||||
[[package]]
|
||||
name = "tauri"
|
||||
version = "2.11.5"
|
||||
version = "2.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "667b20e2726d572dea2de7370da16e188eb06008faf9a92fab7cdc46791190b5"
|
||||
checksum = "cb20ef8e6f97d6fe03039666cd82861f09a38b56291fa2f0f9fe140023f61c1a"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bytes",
|
||||
"cookie",
|
||||
"dirs 6.0.0",
|
||||
"dirs 7.0.0",
|
||||
"dunce",
|
||||
"embed_plist",
|
||||
"getrandom 0.3.4",
|
||||
@@ -7285,18 +7281,18 @@ dependencies = [
|
||||
"webkit2gtk",
|
||||
"webview2-com",
|
||||
"window-vibrancy",
|
||||
"windows 0.61.3",
|
||||
"windows 0.62.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-build"
|
||||
version = "2.6.3"
|
||||
version = "2.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bc9ce40b16101cb6ea63d3e221567affd1c3a9205f95d7bc574941a10636b632"
|
||||
checksum = "5b5ae674f48836f5dd2eeaf9e221c095bd3e78a8d0439c77ca93b48740a1b644"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"cargo_toml",
|
||||
"dirs 6.0.0",
|
||||
"dirs 7.0.0",
|
||||
"glob",
|
||||
"heck 0.5.0",
|
||||
"json-patch",
|
||||
@@ -7311,16 +7307,16 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-codegen"
|
||||
version = "2.6.3"
|
||||
version = "2.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08279169ff42f8fc45a1dbc9dcae888893ba95288142e5880c59b93a26d2cfc5"
|
||||
checksum = "3926b73ac01df7c14f19ff872cd56e67213a87acc0000ea37ddb300f3d11a3e3"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"brotli",
|
||||
"ico",
|
||||
"json-patch",
|
||||
"plist",
|
||||
"png 0.17.16",
|
||||
"png 0.18.1",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"semver",
|
||||
@@ -7338,9 +7334,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-macros"
|
||||
version = "2.6.3"
|
||||
version = "2.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e8b394794f399a421811d06966343e7933fcae92d59f5180b9388d1174497a45"
|
||||
checksum = "d21d0fa2c0529972ea6ecaf7404fcf40efac098eda0beb06ca682f41e33a6aa5"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@@ -7352,9 +7348,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin"
|
||||
version = "2.6.3"
|
||||
version = "2.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "74be5dd4bed9afbd145e5716b5fa2ec28cbc29c34ffa61c258c9273d896c8020"
|
||||
checksum = "c9ff3ebb9fda56ceb93d46f6cbb126bae82951bf43498543a5163dde5def49a1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"glob",
|
||||
@@ -7368,9 +7364,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-autostart"
|
||||
version = "2.5.1"
|
||||
version = "2.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "459383cebc193cdd03d1ba4acc40f2c408a7abce419d64bdcd2d745bc2886f70"
|
||||
checksum = "d464b4c2a5742cdeaf89d739f0681a8770c380053919dcd3ab9bc65fdb9f7c5f"
|
||||
dependencies = [
|
||||
"auto-launch",
|
||||
"serde",
|
||||
@@ -7382,9 +7378,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-dialog"
|
||||
version = "2.7.2"
|
||||
version = "2.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b2d3c1dbe38037e7f590cdf2492594d5ceebe031e7bc7e827509b22a999d2940"
|
||||
checksum = "7527c5fd1678032d116c1a82e5d609c67370e56f858ae6cfd376bbca37fe0490"
|
||||
dependencies = [
|
||||
"log",
|
||||
"raw-window-handle",
|
||||
@@ -7400,9 +7396,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-fs"
|
||||
version = "2.5.1"
|
||||
version = "2.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b7ecc274121aca0c036a2b42d1cbe83d368d348f54e0bb8a735c2b1548e8f371"
|
||||
checksum = "466eb32466fe5021b6728b06862f9ff14a9f7e1af890047654e03a96d7c0e1bb"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"dunce",
|
||||
@@ -7424,9 +7420,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-global-shortcut"
|
||||
version = "2.3.2"
|
||||
version = "2.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4dd9f4c5136c09cd962da0c86dc4accd4666db2ea591cf16e6597435843bd2b"
|
||||
checksum = "0bd2e1f725891a1613af8f25bf918ba3357654b0fd3f2d794c0ce76cbdd92ed2"
|
||||
dependencies = [
|
||||
"global-hotkey",
|
||||
"log",
|
||||
@@ -7439,9 +7435,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-notification"
|
||||
version = "2.3.3"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "01fc2c5ff41105bd1f7242d8201fdf3efd70749b82fa013a17f2126357d194cc"
|
||||
checksum = "9237e5cc1458bf1b31ad3c8c2c8480e86b6ecf133d00648fe6c36f25821f2f79"
|
||||
dependencies = [
|
||||
"log",
|
||||
"notify-rust",
|
||||
@@ -7458,9 +7454,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-opener"
|
||||
version = "2.5.4"
|
||||
version = "2.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "17e1bea14edce6b793a04e2417e3fd924b9bc4faae83cdee7d714156cceeed29"
|
||||
checksum = "d39404b2572927e0d3ed30a7ca226037f7508d22e79c96ee6ef0d42b6a4b3345"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"glob",
|
||||
@@ -7474,7 +7470,23 @@ dependencies = [
|
||||
"tauri-plugin",
|
||||
"thiserror 2.0.20",
|
||||
"url",
|
||||
"windows 0.61.3",
|
||||
"windows 0.62.2",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-single-instance"
|
||||
version = "2.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "91baf4f5db4b008fc2bcada0f7d3a49b45d911f94575ac236f225ed67554f5c0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
"thiserror 2.0.20",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
@@ -7496,9 +7508,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-runtime"
|
||||
version = "2.11.3"
|
||||
version = "2.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b0b4bc95aed361b0019067d189a1174a603d460d0f6c72606512d59fc9c12ec8"
|
||||
checksum = "c9e6d5ef76985b32ff012a43b58df205d25a285e400ca878afcacddc5d5f3238"
|
||||
dependencies = [
|
||||
"cookie",
|
||||
"dpi",
|
||||
@@ -7516,14 +7528,14 @@ dependencies = [
|
||||
"url",
|
||||
"webkit2gtk",
|
||||
"webview2-com",
|
||||
"windows 0.61.3",
|
||||
"windows 0.62.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-runtime-wry"
|
||||
version = "2.11.4"
|
||||
version = "2.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e6fac707727b7a2f48e4ded90976324267371073edbb415ffb73bb0458d203f"
|
||||
checksum = "fa829eb69860cf1fb0bedb21d2d5f1effce3527d054a68ca1cd7355c654400a3"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"http",
|
||||
@@ -7541,7 +7553,7 @@ dependencies = [
|
||||
"url",
|
||||
"webkit2gtk",
|
||||
"webview2-com",
|
||||
"windows 0.61.3",
|
||||
"windows 0.62.2",
|
||||
"wry",
|
||||
]
|
||||
|
||||
@@ -7564,9 +7576,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-utils"
|
||||
version = "2.9.3"
|
||||
version = "2.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3e176a18e67764923c4f1ce66f25ae4abe5f688384d5eb1a0fa6c77f3d90f887"
|
||||
checksum = "4dd257082deff79550de3409ed146104aeaf86fe38649615b04a304144939677"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"brotli",
|
||||
@@ -7646,7 +7658,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "thing"
|
||||
version = "26.9.4"
|
||||
version = "26.9.5"
|
||||
dependencies = [
|
||||
"aes 0.8.4",
|
||||
"async-trait",
|
||||
@@ -7668,6 +7680,7 @@ dependencies = [
|
||||
"lofty",
|
||||
"md-5",
|
||||
"notify",
|
||||
"quick-xml 0.42.0",
|
||||
"rand 0.8.8",
|
||||
"raw-window-handle",
|
||||
"regex",
|
||||
@@ -7692,6 +7705,7 @@ dependencies = [
|
||||
"tauri-plugin-global-shortcut",
|
||||
"tauri-plugin-notification",
|
||||
"tauri-plugin-opener",
|
||||
"tauri-plugin-single-instance",
|
||||
"tauri-plugin-snap-layout",
|
||||
"tauri-specta",
|
||||
"tokio",
|
||||
@@ -7909,21 +7923,6 @@ dependencies = [
|
||||
"toml_edit 0.20.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml"
|
||||
version = "0.9.12+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863"
|
||||
dependencies = [
|
||||
"indexmap 2.14.0",
|
||||
"serde_core",
|
||||
"serde_spanned 1.1.1",
|
||||
"toml_datetime 0.7.5+spec-1.1.0",
|
||||
"toml_parser",
|
||||
"toml_writer",
|
||||
"winnow 0.7.15",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml"
|
||||
version = "1.1.2+spec-1.1.0"
|
||||
@@ -7948,15 +7947,6 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "0.7.5+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "1.1.1+spec-1.1.0"
|
||||
@@ -8107,12 +8097,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tray-icon"
|
||||
version = "0.24.1"
|
||||
version = "0.25.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65ba1e5f6b9ef9fd87e21b9c6f351554dbd717960089168fcfdef854686961dc"
|
||||
checksum = "b2b9c52859a94554803ccd4a24b98f74148ebc73b90676d783f3490b1bff9d72"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"dirs 6.0.0",
|
||||
"dirs 7.0.0",
|
||||
"libappindicator",
|
||||
"muda",
|
||||
"objc2",
|
||||
@@ -8180,47 +8170,6 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unic-char-property"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221"
|
||||
dependencies = [
|
||||
"unic-char-range",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unic-char-range"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc"
|
||||
|
||||
[[package]]
|
||||
name = "unic-common"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc"
|
||||
|
||||
[[package]]
|
||||
name = "unic-ucd-ident"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e230a37c0381caa9219d67cf063aa3a375ffed5bf541a452db16e744bdab6987"
|
||||
dependencies = [
|
||||
"unic-char-property",
|
||||
"unic-char-range",
|
||||
"unic-ucd-version",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unic-ucd-version"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4"
|
||||
dependencies = [
|
||||
"unic-common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicase"
|
||||
version = "2.9.0"
|
||||
@@ -8288,13 +8237,13 @@ checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"
|
||||
|
||||
[[package]]
|
||||
name = "urlpattern"
|
||||
version = "0.3.0"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "70acd30e3aa1450bc2eece896ce2ad0d178e9c079493819301573dae3c37ba6d"
|
||||
checksum = "df16f50ef4cc145211879a3867ba757076b25dfee812040dcb0658bd9ae7904b"
|
||||
dependencies = [
|
||||
"icu_properties",
|
||||
"regex",
|
||||
"serde",
|
||||
"unic-ucd-ident",
|
||||
"url",
|
||||
]
|
||||
|
||||
@@ -8562,16 +8511,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "webview2-com"
|
||||
version = "0.38.2"
|
||||
version = "0.39.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7130243a7a5b33c54a444e54842e6a9e133de08b5ad7b5861cd8ed9a6a5bc96a"
|
||||
checksum = "3f89fca7a704cee10dcb3654c1dbb8941d1783132f1917358af75bec37a7d7e6"
|
||||
dependencies = [
|
||||
"webview2-com-macros",
|
||||
"webview2-com-sys",
|
||||
"windows 0.61.3",
|
||||
"windows-core 0.61.2",
|
||||
"windows-implement 0.60.2",
|
||||
"windows-interface 0.59.3",
|
||||
"windows 0.62.2",
|
||||
"windows-core 0.62.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8587,13 +8534,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "webview2-com-sys"
|
||||
version = "0.38.2"
|
||||
version = "0.39.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c"
|
||||
checksum = "b3a07132775117d6065853d9d1178157b8c90e228de47129d6bce2c7edebedfb"
|
||||
dependencies = [
|
||||
"thiserror 2.0.20",
|
||||
"windows 0.61.3",
|
||||
"windows-core 0.61.2",
|
||||
"windows 0.62.2",
|
||||
"windows-core 0.62.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8618,7 +8565,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.48.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8629,16 +8576,17 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
|
||||
|
||||
[[package]]
|
||||
name = "window-vibrancy"
|
||||
version = "0.6.0"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d9bec5a31f3f9362f2258fd0e9c9dd61a9ca432e7306cc78c444258f0dce9a9c"
|
||||
checksum = "111e51caca442cafd9bab396628ac4d814880eaea4e63dfd76a12e9f342b5580"
|
||||
dependencies = [
|
||||
"objc2",
|
||||
"objc2-app-kit",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation",
|
||||
"objc2-quartz-core",
|
||||
"raw-window-handle",
|
||||
"windows-sys 0.59.0",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-version",
|
||||
]
|
||||
|
||||
@@ -9252,12 +9200,6 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winnow"
|
||||
version = "0.7.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
|
||||
|
||||
[[package]]
|
||||
name = "winnow"
|
||||
version = "1.0.4"
|
||||
@@ -9322,15 +9264,15 @@ checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"
|
||||
|
||||
[[package]]
|
||||
name = "wry"
|
||||
version = "0.55.1"
|
||||
version = "0.57.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "186f9871daa55fd9c016578b810d149de58367113db7fb72b462d2323ce19514"
|
||||
checksum = "a819957a01b3119af85e638a38d242af76dbc87d130dca67bfd0441072e21ff0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"block2",
|
||||
"cookie",
|
||||
"crossbeam-channel",
|
||||
"dirs 6.0.0",
|
||||
"dirs 7.0.0",
|
||||
"dom_query",
|
||||
"dpi",
|
||||
"dunce",
|
||||
@@ -9358,8 +9300,8 @@ dependencies = [
|
||||
"webkit2gtk",
|
||||
"webkit2gtk-sys",
|
||||
"webview2-com",
|
||||
"windows 0.61.3",
|
||||
"windows-core 0.61.2",
|
||||
"windows 0.62.2",
|
||||
"windows-core 0.62.2",
|
||||
"windows-version",
|
||||
"x11-dl",
|
||||
]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "thing"
|
||||
version = "26.9.4"
|
||||
version = "26.9.5"
|
||||
description = "A Tauri App"
|
||||
authors = ["you"]
|
||||
edition = "2021"
|
||||
@@ -117,6 +117,11 @@ symphonia = { version = "0.6", features = ["mp3", "aac", "alac", "isomp4"] }
|
||||
# AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | SRC_DEFAULT_QUALITY,因此**可以用源采样率
|
||||
# 直接建流**,由 Windows 自己转换到设备混音格式 —— 不需要额外引入重采样库。
|
||||
cpal = "0.18"
|
||||
# WebDAV 的 PROPFIND 响应是 XML,且命名空间前缀由服务端随意指定(D: / d: / lp1: /
|
||||
# 无前缀),因此只能按 local name 做宽容的事件流解析。quick-xml 是纯 Rust、无 C 依赖,
|
||||
# 且比 serde 反序列化更能吃下各家 NAS 不一致的字段集合(见 notes/webdav/client.rs)。
|
||||
quick-xml = "0.42.0"
|
||||
tauri-plugin-single-instance = "2.5.1"
|
||||
# HDR 截图说明:windows-capture 的 Windows Graphics Capture 后端在 HDR 显示器上
|
||||
# 可能输出 scRGB / rgba16F 或 HDR10(PQ) 格式的帧,与项目其余截图路径
|
||||
# (GDI BitBlt,sRGB 8bit)色彩空间不一致。capture 层统一转成 sRGB 8bit
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "notes-window",
|
||||
"description": "Capability for the notes/editor windows (multi-open, label = notes-window-<n>). Needs the CM6 editor's window controls, events (settings/library sync) and opener.",
|
||||
"windows": ["notes-window-*"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-show",
|
||||
"core:window:allow-hide",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-minimize",
|
||||
"core:window:allow-maximize",
|
||||
"core:window:allow-toggle-maximize",
|
||||
"core:window:allow-set-focus",
|
||||
"core:window:allow-set-title",
|
||||
"core:window:allow-start-dragging",
|
||||
"core:window:allow-set-theme",
|
||||
"core:window:allow-set-effects",
|
||||
"core:window:allow-set-background-color",
|
||||
"core:event:allow-listen",
|
||||
"core:event:allow-emit",
|
||||
"dialog:default",
|
||||
"opener:default",
|
||||
"opener:allow-open-path",
|
||||
"opener:allow-reveal-item-in-dir",
|
||||
"snap-layout:default"
|
||||
]
|
||||
}
|
||||
@@ -26,6 +26,9 @@ pub mod windows {
|
||||
/// 因此**不登记 capability**:远端页面不应获得任何 Tauri 权限)。
|
||||
#[allow(dead_code)]
|
||||
pub const DSH_WEB: &str = "dsh-web";
|
||||
/// 笔记 / 编辑器独立窗口前缀,实际 label = `${NOTES_WINDOW}-<n>`(可多开)
|
||||
#[allow(dead_code)]
|
||||
pub const NOTES_WINDOW: &str = "notes-window";
|
||||
}
|
||||
|
||||
/// Tauri 事件名(与前端 constants::EVENTS 对应)
|
||||
@@ -134,4 +137,24 @@ pub mod events {
|
||||
/// dsh 模块:全局快捷键触发「打开独立窗口」(无负载)。
|
||||
/// 窗口由前端创建(它持有带令牌的地址与 label 判重),Rust 侧只负责注册快捷键。
|
||||
pub const DSH_OPEN_WINDOW: &str = "dsh-open-window";
|
||||
// 笔记模块:设置已保存(无负载)。各窗口据以重读设置,实现跨窗口同步(同 terminal-settings)
|
||||
pub const NOTES_SETTINGS: &str = "notes-settings";
|
||||
// 笔记模块:库内容已变更(新建/保存/重命名/删除/切换库根,无负载)
|
||||
pub const NOTES_LIBRARY_CHANGED: &str = "notes-library-changed";
|
||||
// 笔记模块:库内某个文件在**应用外**被改动了(负载见 notes::index_service::NoteFileEvent)。
|
||||
// 与 NOTES_LIBRARY_CHANGED 的区别:那个是「本应用改了,重读即可」,这个是
|
||||
// 「别人改了,当前打开的文档可能已经过时」——前端据此提示而不是静默覆盖。
|
||||
pub const NOTES_FILE_CHANGED: &str = "notes-file-changed";
|
||||
// 笔记模块:WebDAV 同步进度(负载见 notes::types::SyncProgress)。
|
||||
// 进度事件是高频的,前端按「每 X% 或每 N 条」节流显示即可;Rust 侧逐条发,
|
||||
// 因为节流放在发送端会让「最后一条」容易被丢掉(进度条停在 98%)。
|
||||
pub const NOTES_SYNC_PROGRESS: &str = "notes-sync-progress";
|
||||
// 笔记模块:全局快捷键按下「新建笔记」(无负载,窗口由前端创建)
|
||||
pub const NOTES_NEW_NOTE: &str = "notes-new-note";
|
||||
// 笔记模块:全局快捷键按下「打开编辑器窗口」(无负载)
|
||||
pub const NOTES_OPEN_EDITOR: &str = "notes-open-editor";
|
||||
// 笔记模块:需要打开一个磁盘文件(负载 `{ path }`)。
|
||||
// 来源有三:① 双击关联的 .md(单实例回调把参数转交过来);② 启动命令行参数;
|
||||
// ③ 系统「打开方式」。三种都只发事件,窗口由前端创建。
|
||||
pub const NOTES_OPEN_FILE: &str = "notes-open-file";
|
||||
}
|
||||
+91
-1
@@ -10,6 +10,7 @@ mod mihomo_manager;
|
||||
mod monitor_kernel;
|
||||
pub mod music;
|
||||
mod network_monitor;
|
||||
mod notes;
|
||||
mod osd_window;
|
||||
mod process_manager;
|
||||
mod quickpanel;
|
||||
@@ -37,6 +38,18 @@ use download_engine::{
|
||||
use logger::{
|
||||
log_clear, log_info_state, log_list, log_message,
|
||||
};
|
||||
use notes::{
|
||||
notes_add_template, notes_authorize_file, notes_backlinks, notes_backup_now,
|
||||
notes_create_folder, notes_create_note, notes_daily_note, notes_delete_entry,
|
||||
notes_export_note, notes_export_snapshot_local, notes_export_zip, notes_get_settings,
|
||||
notes_import, notes_index_stats, notes_library_info, notes_link_graph, notes_list_backups,
|
||||
notes_list_notes, notes_list_templates, notes_open_file, notes_read_asset, notes_read_note,
|
||||
notes_read_template, notes_rebuild_index, notes_rename_entry, notes_restore_backup,
|
||||
notes_save_note, notes_save_settings, notes_scan_library, notes_search_notes,
|
||||
notes_set_library_root, notes_set_webdav_password, notes_sync_index, notes_sync_now,
|
||||
notes_tags, notes_take_pending_file, notes_test_webdav, notes_webdav_status,
|
||||
notes_write_asset, notes_write_file,
|
||||
};
|
||||
use mihomo_manager::{
|
||||
proxy_activate_profile, proxy_apply_kernel_update, proxy_cancel_kernel_install, proxy_check_kernel_update, proxy_clear_system_proxy,
|
||||
proxy_close_connection, proxy_confirm_install, proxy_delete_profile, proxy_get_connections, proxy_get_proxies, proxy_get_settings, proxy_get_system_proxy,
|
||||
@@ -324,6 +337,18 @@ fn export_bindings() {
|
||||
dsh_unregister_shortcut, dsh_start, dsh_stop, dsh_restart,
|
||||
dsh_ai_preview, dsh_ai_sync, dsh_log_tail, dsh_install_log, dsh_log_clear,
|
||||
dsh_open_dir,
|
||||
// notes(39)——与 `run()` 里那份保持一致,否则 bindings.ts 缺类型
|
||||
notes_get_settings, notes_save_settings, notes_library_info, notes_set_library_root,
|
||||
notes_scan_library, notes_read_note, notes_save_note, notes_create_note,
|
||||
notes_create_folder, notes_rename_entry, notes_delete_entry,
|
||||
notes_rebuild_index, notes_sync_index, notes_search_notes, notes_list_notes,
|
||||
notes_tags, notes_index_stats, notes_open_file, notes_write_file,
|
||||
notes_write_asset, notes_authorize_file,
|
||||
notes_list_templates, notes_add_template, notes_read_template, notes_daily_note,
|
||||
notes_import, notes_export_note, notes_export_zip, notes_export_snapshot_local,
|
||||
notes_webdav_status, notes_set_webdav_password, notes_test_webdav,
|
||||
notes_sync_now, notes_backup_now, notes_list_backups, notes_restore_backup,
|
||||
notes_backlinks, notes_link_graph, notes_take_pending_file, notes_read_asset,
|
||||
])
|
||||
.export(Typescript::default(), "../src/lib/bindings.ts")
|
||||
.expect("failed to export bindings");
|
||||
@@ -343,6 +368,30 @@ pub fn run() {
|
||||
win32_util::set_app_user_model_id("thing.lfeng.me");
|
||||
|
||||
tauri::Builder::default()
|
||||
// 单实例必须是**第一个**注册的插件:它决定「第二个进程是退出还是把参数转交过来」,
|
||||
// 排在别的插件后面会让后面的插件在第二个进程里先跑一遍初始化(起两个托盘图标之类)。
|
||||
//
|
||||
// # 为什么需要它
|
||||
//
|
||||
// 「用 Thing 打开」的文件关联会让 Windows 用 `thing.exe <文件路径>` 启动本应用;
|
||||
// 应用已在运行时就会冒出第二个进程 —— 没有这个插件,用户双击一个 .md 只会得到
|
||||
// 一个(或两个)空窗口,而且第二个实例会和第一个抢同一个 sqlite 索引文件。
|
||||
// 有了它,第二个进程立即退出,命令行参数被转交给第一个实例的下面这个回调。
|
||||
.plugin(tauri_plugin_single_instance::init(|app, argv, _cwd| {
|
||||
// 主窗口可能藏在托盘里:先把已有窗口叫出来,再决定开哪个
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
let _ = window.show();
|
||||
let _ = window.unminimize();
|
||||
let _ = window.set_focus();
|
||||
}
|
||||
match crate::notes::note_path_from_args(argv.clone()) {
|
||||
Some(path) => crate::notes::emit_open_file(app, &path),
|
||||
None => {
|
||||
// 没有文件参数(用户又点了一次快捷方式):只把主窗口叫到前面,别开新窗口
|
||||
crate::logger::log_info("notes", "第二个实例无文件参数,仅聚焦主窗口");
|
||||
}
|
||||
}
|
||||
}))
|
||||
.plugin(tauri_plugin_autostart::Builder::new().build())
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
@@ -762,7 +811,48 @@ pub fn run() {
|
||||
dsh_log_tail,
|
||||
dsh_install_log,
|
||||
dsh_log_clear,
|
||||
dsh_open_dir
|
||||
dsh_open_dir,
|
||||
// notes(39)
|
||||
notes_get_settings,
|
||||
notes_save_settings,
|
||||
notes_library_info,
|
||||
notes_set_library_root,
|
||||
notes_scan_library,
|
||||
notes_read_note,
|
||||
notes_save_note,
|
||||
notes_create_note,
|
||||
notes_create_folder,
|
||||
notes_rename_entry,
|
||||
notes_delete_entry,
|
||||
notes_rebuild_index,
|
||||
notes_sync_index,
|
||||
notes_search_notes,
|
||||
notes_list_notes,
|
||||
notes_tags,
|
||||
notes_index_stats,
|
||||
notes_open_file,
|
||||
notes_write_file,
|
||||
notes_write_asset,
|
||||
notes_authorize_file,
|
||||
notes_list_templates,
|
||||
notes_add_template,
|
||||
notes_read_template,
|
||||
notes_daily_note,
|
||||
notes_import,
|
||||
notes_export_note,
|
||||
notes_export_zip,
|
||||
notes_export_snapshot_local,
|
||||
notes_webdav_status,
|
||||
notes_set_webdav_password,
|
||||
notes_test_webdav,
|
||||
notes_sync_now,
|
||||
notes_backup_now,
|
||||
notes_list_backups,
|
||||
notes_restore_backup,
|
||||
notes_backlinks,
|
||||
notes_link_graph,
|
||||
notes_take_pending_file,
|
||||
notes_read_asset
|
||||
])
|
||||
.setup(setup::init)
|
||||
.on_window_event(|window, event| {
|
||||
|
||||
@@ -32,6 +32,9 @@ pub use fnconnect::{extract_fn_id, resolve_base_url};
|
||||
use conn::{generate_device_id, sha256_hex};
|
||||
use proxy::{ProxyCfg, ProxyShared};
|
||||
|
||||
/// 登录接口路径(同时用于失败留痕)。
|
||||
const LOGIN_PATH: &str = "/music/api/v1/user/password-login";
|
||||
|
||||
/// 一条飞牛音乐连接(持久化在 `MusicSettings`)。
|
||||
#[derive(Serialize, Deserialize, Clone, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -151,6 +154,33 @@ fn slot_client(slot: &Mutex<Option<ClientSlot>>, insecure: bool, streaming: bool
|
||||
g.as_ref().unwrap().client.clone()
|
||||
}
|
||||
|
||||
/// 服务端错误 → 画面上要展示的提示。
|
||||
///
|
||||
/// 飞牛音乐失败时常常只回一句笼统的 `msg`(如 `unknown error`),单看它判断不出
|
||||
/// 该重试、该重新登录,还是该去 NAS 上修服务;这里按官方错误码表补上结论与处理动作,
|
||||
/// 让提示本身就能指导操作。HTTP 状态码与错误码附在括号里,便于对日志。
|
||||
///
|
||||
/// 只有取不到 `data` 的失败才会走到这里,因此不需要区分调用方。
|
||||
fn error_text(status: StatusCode, code: i64, msg: &str) -> String {
|
||||
let head = match code {
|
||||
100001 => "飞牛 NAS 的音乐服务内部异常,可在 NAS 上重启「飞牛音乐」应用后重试",
|
||||
100002 => "请求与 NAS 端音乐服务版本不匹配",
|
||||
100003 | 100004 => "当前账号没有权限",
|
||||
100005 => "目标不存在(可能已被删除)",
|
||||
110002 => "NAS 端音乐应用尚未初始化",
|
||||
140001 => "NAS 正在重建搜索索引,请稍后再试",
|
||||
_ => {
|
||||
let m = msg.trim();
|
||||
if m.is_empty() {
|
||||
"飞牛音乐请求失败"
|
||||
} else {
|
||||
m
|
||||
}
|
||||
}
|
||||
};
|
||||
format!("{head}(HTTP {} / code {code})", status.as_u16())
|
||||
}
|
||||
|
||||
impl Feiniu {
|
||||
/// 设置缓存根目录({app_data}/music/cache),应用启动时调用一次。
|
||||
pub fn set_cache_root(&mut self, app_data_dir: &Path) {
|
||||
@@ -310,7 +340,7 @@ impl Feiniu {
|
||||
.relay;
|
||||
let mut rb = self
|
||||
.client(insecure)
|
||||
.post(format!("{base}/music/api/v1/user/password-login"))
|
||||
.post(format!("{base}{LOGIN_PATH}"))
|
||||
.json(&body);
|
||||
// 中继链路:登录请求也需带 mode=relay,否则网关 302 回登录页
|
||||
if let Some(cookie) = Self::auth_cookie("", relay) {
|
||||
@@ -328,20 +358,24 @@ impl Feiniu {
|
||||
format!("{kind}: {e}")
|
||||
})?;
|
||||
let status = resp.status();
|
||||
let b: Value = resp
|
||||
.json()
|
||||
.await
|
||||
.unwrap_or_else(|_| json!({ "code": status.as_u16() }));
|
||||
let raw = resp.text().await.unwrap_or_default();
|
||||
let b: Value = serde_json::from_str(&raw).unwrap_or_else(|_| json!({ "code": status.as_u16() }));
|
||||
let code = b["code"].as_i64().unwrap_or(i64::from(status.as_u16()));
|
||||
if code != 0 {
|
||||
let msg = b["msg"].as_str().unwrap_or("");
|
||||
// 服务端对部分失败只给一句笼统的 msg(如 `unknown error`),
|
||||
// 不带状态码/错误码/原始响应就无从定位,这里一次性留全。
|
||||
crate::logger::log_error(
|
||||
"feiniu",
|
||||
&format!(
|
||||
"POST {LOGIN_PATH} 失败: HTTP {status} code={code} body={}",
|
||||
raw.chars().take(400).collect::<String>()
|
||||
),
|
||||
);
|
||||
if code == 120001 {
|
||||
return Err("用户名或密码错误".into());
|
||||
}
|
||||
let msg = b["msg"]
|
||||
.as_str()
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| format!("HTTP {status}"));
|
||||
return Err(msg);
|
||||
return Err(error_text(status, code, msg));
|
||||
}
|
||||
let token = b["data"]["userToken"]
|
||||
.as_str()
|
||||
@@ -515,20 +549,30 @@ impl Feiniu {
|
||||
}
|
||||
let resp = rb.send().await.map_err(|e| format!("请求失败: {e}"))?;
|
||||
let status = resp.status();
|
||||
let body: Value = resp
|
||||
.json()
|
||||
.await
|
||||
.unwrap_or_else(|_| json!({ "code": status.as_u16() }));
|
||||
let raw = resp.text().await.unwrap_or_default();
|
||||
let body: Value =
|
||||
serde_json::from_str(&raw).unwrap_or_else(|_| json!({ "code": status.as_u16() }));
|
||||
let code = body["code"].as_i64().unwrap_or(i64::from(status.as_u16()));
|
||||
if code != 0 {
|
||||
if status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN {
|
||||
let msg = body["msg"].as_str().unwrap_or("");
|
||||
// 服务端对部分失败只给一句笼统的 msg(如 `unknown error`),
|
||||
// 不带状态码/错误码/原始响应就无从定位,这里一次性留全。
|
||||
crate::logger::log_error(
|
||||
"feiniu",
|
||||
&format!(
|
||||
"GET {path} 失败: HTTP {status} code={code} body={}",
|
||||
raw.chars().take(400).collect::<String>()
|
||||
),
|
||||
);
|
||||
// HTTP 401/403 与 120001(Unauthorized)都表示「这把会话不能用了」,
|
||||
// 需重新登录——不该混进「NAS 服务异常」的提示里。
|
||||
if status == StatusCode::UNAUTHORIZED
|
||||
|| status == StatusCode::FORBIDDEN
|
||||
|| code == 120001
|
||||
{
|
||||
return Err("登录已过期,请重新登录".into());
|
||||
}
|
||||
let msg = body["msg"]
|
||||
.as_str()
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| format!("请求失败(HTTP {status})"));
|
||||
return Err(msg);
|
||||
return Err(error_text(status, code, msg));
|
||||
}
|
||||
Ok(body["data"].clone())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
//! 「用 Thing 打开」的参数解析与事件投递。
|
||||
//!
|
||||
//! # 两条入口,同一份逻辑
|
||||
//!
|
||||
//! 1. **冷启动**:安装器注册的文件关联让 Windows 用 `thing.exe <文件路径>` 启动本应用;
|
||||
//! 2. **热启动**:应用已在运行时双击 `.md`,会起第二个进程,由
|
||||
//! `tauri-plugin-single-instance` 把它的命令行参数转交给第一个实例。
|
||||
//!
|
||||
//! 两条路径的输入形态完全一样(都是命令行参数),因此共用 [`note_path_from_args`]。
|
||||
//! 解析成功后统一发 [`crate::constants::events::NOTES_OPEN_FILE`],**窗口由前端创建** ——
|
||||
//! Rust 侧不持有窗口 label 策略,也不该知道「用户是不是想让它在已有窗口里打开」。
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// 「启动时命令行指定的文件」缓存。
|
||||
///
|
||||
/// # 为什么需要缓存而不是启动时直接 `emit`
|
||||
///
|
||||
/// 冷启动的顺序是:`setup` 跑完 → 创建主窗口 → WebView 加载前端 → 前端注册监听。
|
||||
/// 在 `setup` 里 `emit` 时前端还没开始监听,事件**直接丢掉**了 —— 表现是
|
||||
/// 「双击 .md 打开了应用,但笔记没打开」。
|
||||
///
|
||||
/// 因此这里把路径存下来,由前端在注册完监听后**主动取一次**
|
||||
/// (`notes_take_pending_file`)。取走即清空,避免下次打开窗口时又被翻出来。
|
||||
static PENDING: std::sync::OnceLock<Mutex<Option<PathBuf>>> = std::sync::OnceLock::new();
|
||||
|
||||
fn pending_slot() -> &'static Mutex<Option<PathBuf>> {
|
||||
PENDING.get_or_init(|| Mutex::new(None))
|
||||
}
|
||||
|
||||
/// 记下「启动时想打开的文件」(由 `setup` 调用)。
|
||||
pub fn remember_pending_file(path: PathBuf) {
|
||||
if let Ok(mut slot) = pending_slot().lock() {
|
||||
*slot = Some(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// 取出并清空待打开文件(由 `notes_take_pending_file` 命令调用)。
|
||||
pub fn take_pending_file() -> Option<PathBuf> {
|
||||
pending_slot()
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|mut slot| slot.take())
|
||||
}
|
||||
|
||||
/// 从一组命令行参数里挑出「看起来是笔记文件」的那个路径。
|
||||
///
|
||||
/// # 为什么需要挑而不是直接用 `args[1]`
|
||||
///
|
||||
/// 关联启动时命令行长这样:`thing.exe D:\笔记\会议.md`;
|
||||
/// 但从「开始菜单 → 打开」启动时可能有别的开关参数;开发模式下还有 `cargo run --`。
|
||||
/// 这里只认「**存在**的文件 + 笔记类扩展名」,其余一律忽略 ——
|
||||
/// 宁可漏开一个窗口,也不要因为一个参数把主窗口的启动逻辑搞乱。
|
||||
///
|
||||
/// 认的扩展名比「只有 .md」宽一点:`.markdown` / `.mdx` 也常见,且编辑器都能处理
|
||||
/// (打开后走「库外文件」路径,不影响库内笔记的 `.md` 约定)。
|
||||
///
|
||||
/// # 为什么要 `.is_file()`
|
||||
///
|
||||
/// 参数里出现 `foo.md` 但那个文件其实不存在(用户删了、路径编码错了)时,
|
||||
/// 让前端去报「文件不存在」不如在这里就静默忽略 —— 前端那条路径会开一个空窗口。
|
||||
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_file(app: &tauri::AppHandle, path: &Path) {
|
||||
use tauri::Emitter;
|
||||
let payload = serde_json::json!({ "path": path.to_string_lossy() });
|
||||
if let Err(e) = app.emit(crate::constants::events::NOTES_OPEN_FILE, payload) {
|
||||
crate::logger::log_warn("notes", &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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
//! zip 快照备份:整库打包上传 + 远端轮转 + 恢复。
|
||||
//!
|
||||
//! # 为什么「快照」比「双向同步」更该先做
|
||||
//!
|
||||
//! 规划 §3.6 的判断:对「只是要个备份」的用户,一次上传一个完整 zip 比双向同步
|
||||
//! **可靠得多** —— 同步要考虑冲突、删除传播、时钟偏差;快照只有一个动作(上传),
|
||||
//! 失败就是失败,不会在半途产生「一半新一半旧」的库。
|
||||
//!
|
||||
//! 因此本模块与 `webdav/sync.rs` 是两条独立路径,用的是同一个客户端。
|
||||
//!
|
||||
//! # 打包内容
|
||||
//!
|
||||
//! 库内全部 `.md` 与 `assets/` 下的附件,外加一份 `thing-notes-manifest.json`
|
||||
//! (记录快照时间、文件数、格式版本)。**不打包 `.notes/`**:里面是索引与同步基线,
|
||||
//! 属于本机私有数据,跟着快照跑到另一台机器上只会误导那边的基线判断。
|
||||
//!
|
||||
//! # 轮转
|
||||
//!
|
||||
//! 上传后列出远端 `backups/` 下的快照,按**文件名里的时间戳**倒序保留
|
||||
//! [`WebdavSettings::backup_keep`] 份,其余删除。用文件名排序而不是远端 mtime:
|
||||
//! 各家服务端的 mtime 精度与时钟都不一致,而文件名是我们自己写的、单调递增。
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use super::webdav::client::WebdavClient;
|
||||
use crate::notes::library;
|
||||
use crate::notes::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;
|
||||
}
|
||||
// `.notes/` 是本机私有数据(索引 + 同步基线),不进快照
|
||||
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("notes", &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("notes", &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("notes", "快照里有越界路径,已跳过");
|
||||
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("notes", &format!("保存同步基线失败: {e}"));
|
||||
}
|
||||
} else {
|
||||
crate::logger::log_warn(
|
||||
"notes",
|
||||
&format!("本轮有 {} 条失败,不推进同步基线", report.failed),
|
||||
);
|
||||
// 仍然保存「成功的那些」:SyncState 是按条更新的,未处理的条目保持旧基线,
|
||||
// 于是下一轮会把它们重新算作差异并重试
|
||||
if let Err(e) = state.save(root) {
|
||||
crate::logger::log_warn("notes", &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_contains_notes_and_assets_but_not_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(".notes")).unwrap();
|
||||
std::fs::write(root.join(".notes/notes.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(".notes")),
|
||||
"私有目录不该进快照: {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,916 @@
|
||||
//! 笔记模块 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, NoteSettings,
|
||||
SyncProgress,
|
||||
};
|
||||
use super::webdav::{self, WebdavTestResult};
|
||||
use super::NotesManager;
|
||||
use crate::constants::events;
|
||||
|
||||
/// 通知各窗口「库内容已变更」(新建/保存/重命名/删除/切换库根后)。
|
||||
fn emit_library_changed(app: &AppHandle) {
|
||||
if let Err(e) = app.emit(events::NOTES_LIBRARY_CHANGED, ()) {
|
||||
crate::logger::log_warn("notes", &format!("发出库变更事件失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// 通知各窗口「设置已变更」(跨窗口同步,范式同 terminal-settings)。
|
||||
fn emit_settings_changed(app: &AppHandle) {
|
||||
if let Err(e) = app.emit(events::NOTES_SETTINGS, ()) {
|
||||
crate::logger::log_warn("notes", &format!("发出设置变更事件失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// 当前库根(按设置解析),并确保目录存在。
|
||||
fn current_root(state: &NotesManager) -> PathBuf {
|
||||
let settings = state.load_settings();
|
||||
library::resolve_library_root(state.module_dir(), &settings)
|
||||
}
|
||||
|
||||
/// 取索引服务并把它的库根对齐到当前设置。
|
||||
fn indexed<'a>(app: &AppHandle, state: &NotesManager) -> Result<&'a IndexService, String> {
|
||||
let root = current_root(state);
|
||||
let service = index_service::service(app);
|
||||
service.retarget(root)?;
|
||||
Ok(service)
|
||||
}
|
||||
|
||||
/// 组装库状态概览。
|
||||
fn library_info(state: &NotesManager) -> 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),
|
||||
})
|
||||
}
|
||||
|
||||
/// 标记「本应用刚写过」,随后把库同步进索引。
|
||||
///
|
||||
/// 顺序重要:先标记(抑制窗口从写入那一刻算起),再同步。这里走全库增量同步而不是
|
||||
/// 「只索引这一篇」的快路径:单文件快路径要额外拼一份 wikilink 的 `stems` 映射,
|
||||
/// 而不完整的映射会让 `[[某笔记]]` 解析到错误位置;全量同步靠 (mtime,size) 跳过
|
||||
/// 未变文件,万篇规模也是毫秒级,用一点开销换「索引永远自洽」。
|
||||
fn mark_written_then_index(app: &AppHandle, state: &NotesManager) {
|
||||
match indexed(app, state) {
|
||||
Ok(service) => {
|
||||
service.mark_write();
|
||||
if let Err(e) = service.sync() {
|
||||
crate::logger::log_warn("notes", &format!("保存后同步索引失败: {e}"));
|
||||
}
|
||||
}
|
||||
Err(e) => crate::logger::log_warn("notes", &format!("索引服务不可用: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 设置与库 =====
|
||||
|
||||
/// 读取笔记模块设置。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_get_settings(state: State<'_, NotesManager>) -> Result<NoteSettings, String> {
|
||||
Ok(state.load_settings())
|
||||
}
|
||||
|
||||
/// 保存笔记模块设置(自愈后落盘,并广播给各窗口)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_save_settings(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
settings: NoteSettings,
|
||||
) -> Result<NoteSettings, 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 notes_library_info(state: State<'_, NotesManager>) -> Result<LibraryInfo, String> {
|
||||
library_info(&state)
|
||||
}
|
||||
|
||||
/// 设置库根(`None` 或空串 = 恢复默认库根)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_set_library_root(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
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 notes_scan_library(state: State<'_, NotesManager>) -> Result<Vec<LibraryEntry>, String> {
|
||||
let root = current_root(&state);
|
||||
library::ensure_library(&root)?;
|
||||
library::scan(&root)
|
||||
}
|
||||
|
||||
/// 读取一篇笔记。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_read_note(state: State<'_, NotesManager>, rel_path: String) -> Result<NoteDoc, String> {
|
||||
let root = current_root(&state);
|
||||
library::read_note(&root, &rel_path)
|
||||
}
|
||||
|
||||
/// 保存一篇笔记(写完立即更新索引,使搜索无需等下一轮全量同步)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_save_note(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
rel_path: String,
|
||||
content: String,
|
||||
) -> Result<NoteDoc, String> {
|
||||
let root = current_root(&state);
|
||||
let doc = library::write_note(&root, &rel_path, &content)?;
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// 新建笔记(自动补 `.md`、重名加序号),返回新文档。
|
||||
///
|
||||
/// `template_id` 为空时用默认模板;找不到该模板时同样回退默认模板(不报错 ——
|
||||
/// 模板文件被删掉不该让「新建笔记」这个核心动作失败)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_create_note(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
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 notes_daily_note(app: AppHandle, state: State<'_, NotesManager>) -> 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 notes_create_folder(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
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 notes_rename_entry(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
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("notes", &format!("改名后同步索引失败: {e}"));
|
||||
}
|
||||
}
|
||||
emit_library_changed(&app);
|
||||
Ok(next)
|
||||
}
|
||||
|
||||
/// 删除条目(目录递归删除)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_delete_entry(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
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("notes", &format!("删除后同步索引失败: {e}"));
|
||||
}
|
||||
}
|
||||
emit_library_changed(&app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ===== 索引与检索 =====
|
||||
|
||||
/// 全量重建索引(设置页「重建索引」)。文件不受影响。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_rebuild_index(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
) -> Result<NoteIndexReport, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
let report = service.rebuild()?;
|
||||
Ok(finish_report(service, report))
|
||||
}
|
||||
|
||||
/// 增量同步索引(打开编辑器 / 手动刷新时调用)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_sync_index(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
) -> 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 notes_search_notes(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
query: NoteSearchQuery,
|
||||
) -> Result<NoteSearchPage, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.search(query)
|
||||
}
|
||||
|
||||
/// 快速打开清单(`Ctrl+P`;只取路径/标题,带全文片段反而会拖慢输入响应)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_list_notes(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
limit: Option<i64>,
|
||||
) -> Result<Vec<NoteSearchHit>, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.list(limit.unwrap_or(500))
|
||||
}
|
||||
|
||||
/// 标签及计数。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_tags(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
) -> Result<Vec<super::index::NoteTagCount>, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.tags()
|
||||
}
|
||||
|
||||
/// 一篇笔记的链接关系(出链 + 入链)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_backlinks(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
rel_path: String,
|
||||
) -> Result<NoteBacklinks, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.backlinks(&rel_path)
|
||||
}
|
||||
|
||||
/// 全库链接图(已解析的内部链接边)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_link_graph(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
) -> 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 notes_index_stats(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
) -> 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 notes_read_asset(
|
||||
state: State<'_, NotesManager>,
|
||||
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(
|
||||
"notes",
|
||||
&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 还没加载完,
|
||||
/// 事件会直接丢掉(见 `notes/args.rs` 的 `PENDING` 注释)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_take_pending_file() -> Result<Option<String>, String> {
|
||||
Ok(super::args::take_pending_file().map(|path| super::files::display_path(&path)))
|
||||
}
|
||||
|
||||
/// 打开(读取)库外任意文件。
|
||||
///
|
||||
/// 读取本身不要求预先授权(用户可能刚通过系统对话框选完,也可能带命令行参数),
|
||||
/// 但**读取会顺带登记授权** —— 于是「打开过就能保存」这条最符合直觉的规则成立。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_open_file(
|
||||
state: State<'_, NotesManager>,
|
||||
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 notes_write_file(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
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) {
|
||||
service.mark_write();
|
||||
}
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// 显式登记一个路径为「可写」。
|
||||
///
|
||||
/// 前端在拿到系统对话框返回的路径后调用(那种路径不经过 `notes_open_file`,
|
||||
/// 但用户确实是用系统对话框选的,属于「用户显式选择」)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_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 notes_write_asset(
|
||||
state: State<'_, NotesManager>,
|
||||
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 notes_list_templates(state: State<'_, NotesManager>) -> 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 notes_add_template(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
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 notes_read_template(
|
||||
state: State<'_, NotesManager>,
|
||||
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 notes_import(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
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 notes_export_note(
|
||||
state: State<'_, NotesManager>,
|
||||
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(
|
||||
"notes",
|
||||
&format!("导出 {} → {}({} 字节)", rel_path, target.display(), bytes.len()),
|
||||
);
|
||||
Ok(target.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
/// 把整库(或某个目录)打包成 zip,返回落盘路径。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_export_zip(
|
||||
state: State<'_, NotesManager>,
|
||||
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(
|
||||
"notes",
|
||||
&format!("导出 zip:{files} 个文件 → {}", dest_path.display()),
|
||||
);
|
||||
Ok(dest_path.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
/// 把整库打包成一份本地快照 zip(与上传到远端的快照是同一份内容)。
|
||||
///
|
||||
/// 与 [`notes_export_zip`] 的区别只在**目的**:导出是「我要把笔记拿走/分享」,
|
||||
/// 快照是「我要一份可整体恢复的备份」。两者目前内容一致,但保留两个入口是因为
|
||||
/// 将来它们的排除规则可能分化(比如快照要带同步基线,导出不该带)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_export_snapshot_local(
|
||||
state: State<'_, NotesManager>,
|
||||
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 notes_webdav_status(state: State<'_, NotesManager>) -> 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 notes_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 notes_test_webdav(
|
||||
state: State<'_, NotesManager>,
|
||||
) -> Result<WebdavTestResult, String> {
|
||||
let settings = state.load_settings().webdav;
|
||||
run_blocking(move || webdav::test_connection(&settings)).await
|
||||
}
|
||||
|
||||
/// 立即同步(并按设置决定是否追加一次快照备份)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn notes_sync_now(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
) -> 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::NOTES_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 notes_backup_now(
|
||||
state: State<'_, NotesManager>,
|
||||
) -> 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 notes_list_backups(
|
||||
state: State<'_, NotesManager>,
|
||||
) -> 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 notes_restore_backup(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
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,168 @@
|
||||
//! 整库 / 目录导出为 zip。
|
||||
//!
|
||||
//! # 与快照备份的区别
|
||||
//!
|
||||
//! `backup.rs` 的 zip 是**给同步服务用的**(固定文件名前缀、上传到远端、轮转),
|
||||
//! 本模块的 zip 是**给用户拿走的**(用户选保存位置、可以只导出某个目录)。
|
||||
//! 两者都打包 `.md` 与 `assets/`,但排除规则不同:用户导出时**包含**点号开头的
|
||||
//! 普通目录(除了 `.notes/`)—— 因为「我库里有 `.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 == ".notes" || rel.starts_with(".notes/") {
|
||||
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("notes", &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(".notes")).unwrap();
|
||||
std::fs::create_dir_all(root.join(".custom")).unwrap();
|
||||
std::fs::write(root.join("a.md"), "A").unwrap();
|
||||
std::fs::write(root.join(".notes/notes.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(".notes")),
|
||||
"私有目录不该导出: {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,375 @@
|
||||
//! 任意文本 / 代码文件的读写:编码探测、换行探测、授权路径白名单。
|
||||
//!
|
||||
//! # 与笔记库的分工
|
||||
//!
|
||||
//! 库内笔记走 `library.rs`(相对路径 + 树形结构 + front-matter);本模块服务的是
|
||||
//! **库外的任意文件**:用户用 `Ctrl+O` 或拖拽打开的一个 `.py`、`.json`、`.log`。
|
||||
//! 两者的安全模型完全不同 —— 库是「一个根目录内的沙箱」,而任意文件是「用户显式
|
||||
//! 点过的那个路径」。因此这里的守卫不是路径前缀,而是**授权集合**(见下)。
|
||||
//!
|
||||
//! # 为什么要有授权白名单
|
||||
//!
|
||||
//! 前端传来的路径一律不可信:一个被污染的 WebView(XSS、恶意依赖)如果能调
|
||||
//! `notes_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 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` / …)。
|
||||
///
|
||||
/// # 判定顺序(每一步都有理由)
|
||||
///
|
||||
/// 1. **BOM**:UTF-8 BOM / UTF-16 的 BOM 是无歧义的事实,直接采信;
|
||||
/// 2. **严格 UTF-8 校验**:能完整解成 UTF-8 就是 UTF-8。这一步的优先级高于任何
|
||||
/// 统计猜测 —— 中文 GBK 字节序列几乎不可能恰好是合法 UTF-8,反向的误判同样罕见;
|
||||
/// 3. **GB18030 试解**:GB18030 是 GBK 的超集,用它解 GBK 内容总能成功,
|
||||
/// 因此作为「非 UTF-8 中文」的兜底(比 GBK 更宽,能覆盖 4 字节生僻字);
|
||||
/// 4. 都失败则按 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:交给 GB18030 兜底(GBK 的每个序列在 GB18030 下都合法)
|
||||
if crate::terminal::encoding::is_supported("gb18030") {
|
||||
return "gb18030".to_string();
|
||||
}
|
||||
"utf-8".to_string()
|
||||
}
|
||||
|
||||
/// 按编码把字节解成字符串(BOM 已剥离)。
|
||||
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)。
|
||||
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}"));
|
||||
}
|
||||
Ok(crate::terminal::encoding::encode(text, &normalized))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 探测换行风格(`\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> {
|
||||
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 = 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,
|
||||
})
|
||||
}
|
||||
|
||||
/// 写入任意文件。
|
||||
///
|
||||
/// `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());
|
||||
}
|
||||
|
||||
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_as_gb18030() {
|
||||
// 「测试」的 GBK 字节:合法 UTF-8 校验必然失败
|
||||
let gbk = crate::terminal::encoding::encode("测试", "gbk");
|
||||
assert_eq!(detect_encoding(&gbk), "gb18030");
|
||||
assert_eq!(decode_bytes(&gbk, "gb18030"), "测试");
|
||||
}
|
||||
|
||||
#[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,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,506 @@
|
||||
//! 索引服务:单线程 worker + notify 文件监听。
|
||||
//!
|
||||
//! # 为什么索引必须由一个线程独占
|
||||
//!
|
||||
//! `rusqlite::Connection` 不是 `Sync` 的共享对象,而本模块有三个**并发**入口:
|
||||
//! ① 前端的搜索/统计命令(Tauri 命令线程池,可能同时进来好几个);
|
||||
//! ② 保存笔记后的增量更新;③ 文件监听器(notify 自己的回调线程)。
|
||||
//!
|
||||
//! 三种做法各有代价:给连接套 `Mutex` 会让「全库重建索引」这类慢操作**堵住搜索**
|
||||
//! (UI 直接卡住);每次操作现开一个连接则丢失 prepared statement 缓存,还会在
|
||||
//! WAL 上堆出一串写锁竞争。这里选第三条:**一个专职线程独占连接**,所有操作通过
|
||||
//! 消息通道排队进来。慢操作只排队、不阻塞调用方(命令层是异步等待回复),
|
||||
//! 连接始终只有一个,顺序天然可预期。
|
||||
//!
|
||||
//! # 监听器为什么也挂在这个线程上
|
||||
//!
|
||||
//! `notify` 的事件要落到索引上(外部新增/改动文件后立刻可搜),而**只有这个线程
|
||||
//! 能写索引**。让监听回调投递一条 `SyncPath` 消息给 worker,就地把那一个文件同步掉,
|
||||
//! 比「回调里发前端事件 → 前端再调一次同步命令」少一次往返,也不会因为前端窗口
|
||||
//! 关着而漏掉索引更新。
|
||||
//!
|
||||
//! 自我保存抑制([`SUPPRESS_MS`])是必须的:编辑器每次自动保存都会触发
|
||||
//! `Modify(Data)`,若不抑制,前端就会在用户自己打字时反复弹出「文件已被外部修改」。
|
||||
|
||||
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, NotesIndex};
|
||||
use super::library;
|
||||
use crate::constants::events;
|
||||
|
||||
/// 自我保存抑制窗口:`notes_write_*` 之后这段时间内的文件事件不当作「外部修改」。
|
||||
///
|
||||
/// 取 1200ms:前端自动保存默认 800ms 防抖,加上写盘与 notify 自身的派发延迟,
|
||||
/// 这个窗口足够覆盖「自己写的」这一类事件,又短到不会吞掉用户紧接着在外部编辑器
|
||||
/// 里的另一次保存(那种情况用户本来就刚切过窗口,多等一秒无妨)。
|
||||
const SUPPRESS_MS: u64 = 1200;
|
||||
|
||||
/// 单个文件事件的去抖说明。
|
||||
///
|
||||
/// worker 是「来一条处理一条」,去抖由三层共同承担:notify 自身的派发合并、
|
||||
/// 前端 `notes-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, bool),
|
||||
/// 全文检索
|
||||
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>>),
|
||||
}
|
||||
|
||||
/// 索引服务的句柄(命令层只拿到这个)。
|
||||
pub struct IndexService {
|
||||
tx: Sender<Request>,
|
||||
/// 自我保存抑制的时间点(`notes_write_*` 写入)
|
||||
last_write: Mutex<Option<Instant>>,
|
||||
}
|
||||
|
||||
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("notes-index".to_string())
|
||||
.spawn(move || worker_loop(app, rx, handle_tx))
|
||||
.expect("启动笔记索引线程失败");
|
||||
Self {
|
||||
tx,
|
||||
last_write: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// 标记「刚刚由本应用写入了文件」,用于抑制自我触发的「外部修改」提示。
|
||||
pub fn mark_write(&self) {
|
||||
if let Ok(mut slot) = self.last_write.lock() {
|
||||
*slot = Some(Instant::now());
|
||||
}
|
||||
}
|
||||
|
||||
fn recently_written(&self) -> bool {
|
||||
self.last_write
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|slot| *slot)
|
||||
.map(|at| at.elapsed() < Duration::from_millis(SUPPRESS_MS))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// 增量同步整个库。
|
||||
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 主循环:独占 [`NotesIndex`],串行处理所有请求。
|
||||
fn worker_loop(app: AppHandle, rx: Receiver<Request>, handle_tx: Sender<Request>) {
|
||||
let mut index: Option<NotesIndex> = 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;
|
||||
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, from_app) => {
|
||||
if let Some(current) = root.clone() {
|
||||
// 索引尚未建立时先建(首次操作前就被外部改动的情况)
|
||||
if index.is_none() {
|
||||
if let Err(e) = ensure_index(&app, &mut index, ¤t) {
|
||||
crate::logger::log_warn("notes", &format!("索引不可用: {e}"));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
ensure_watcher(&mut watcher, &mut watched_root, ¤t, &handle_tx);
|
||||
sync_one(&app, index.as_mut(), ¤t, &path, from_app);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 借出索引(必要时按 `root` 打开),并把结果映射成 `Result<_, String>`。
|
||||
fn with_index<T>(
|
||||
app: &AppHandle,
|
||||
index: &mut Option<NotesIndex>,
|
||||
root: &mut Option<PathBuf>,
|
||||
run: impl FnOnce(&mut NotesIndex) -> 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<NotesIndex>, 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("notes", &e);
|
||||
}
|
||||
let opened = NotesIndex::open(root)?;
|
||||
crate::logger::log_info(
|
||||
"notes",
|
||||
&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("notes", &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, true));
|
||||
}
|
||||
})
|
||||
.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("notes", &format!("库监听已启动: {}", root.display()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 从 notify 事件里取出「值得同步」的路径(只关心 .md,且忽略 `.notes/` 自身)。
|
||||
///
|
||||
/// 重命名会给出两个路径(旧、新),这里都收下:旧路径在同步时会发现「文件不存在」
|
||||
/// 而被当作删除处理,新路径自然成为新增 —— 无需专门分辨 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()
|
||||
}
|
||||
|
||||
/// 就地同步单个文件(含自我保存抑制与前端事件广播)。
|
||||
fn sync_one(
|
||||
app: &AppHandle,
|
||||
index: Option<&mut NotesIndex>,
|
||||
root: &Path,
|
||||
path: &Path,
|
||||
from_app: bool,
|
||||
) {
|
||||
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 service = SERVICE.get();
|
||||
let self_write = from_app && service.map(|s| s.recently_written()).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("notes", &format!("增量索引 {rel} 失败: {e}"));
|
||||
}
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
// 无法分辨「新建」与「修改」时统一报 modified:前端对两者的处理相同
|
||||
// (重载树)。真正需要区分时以库扫描结果为准。
|
||||
CHANGE_MODIFIED
|
||||
} else {
|
||||
if let Err(e) = index.remove_note(&rel) {
|
||||
crate::logger::log_warn("notes", &format!("移除索引 {rel} 失败: {e}"));
|
||||
}
|
||||
CHANGE_REMOVED
|
||||
};
|
||||
|
||||
if self_write {
|
||||
// 自己写的:索引已更新,前端无需提示(它的编辑器里本来就是最新内容)
|
||||
return;
|
||||
}
|
||||
|
||||
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::NOTES_FILE_CHANGED, payload) {
|
||||
crate::logger::log_warn("notes", &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,333 @@
|
||||
//! 笔记库的文件系统层:路径安全解析、扫描、读写、增删改移。
|
||||
//!
|
||||
//! # 真相在文件,不在数据库
|
||||
//!
|
||||
//! 笔记就是库根下的 `.md` 文件树。本文件的每个函数都以「相对库根的路径」为
|
||||
//! 输入/输出,**所有路径都先过 [`safe_join`]**:拒绝绝对路径、盘符与 `..`,
|
||||
//! 保证任何操作都无法越出库根(前端传来的路径一律不可信)。
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
use super::types::{LibraryEntry, NoteDoc, NoteSettings};
|
||||
|
||||
/// 默认库根相对模块目录的名字:`{app_data_dir}/notes/library`
|
||||
pub const DEFAULT_LIBRARY_DIR: &str = "library";
|
||||
/// 附件(粘贴图片等)目录名,位于库根下
|
||||
pub const ASSETS_DIR: &str = "assets";
|
||||
/// 扫描深度上限(防御性:软链接成环时不会无限递归)。
|
||||
/// 对 `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: &NoteSettings) -> PathBuf {
|
||||
match &settings.library_root {
|
||||
Some(root) if !root.trim().is_empty() => PathBuf::from(root.trim()),
|
||||
_ => default_library_root(module_dir),
|
||||
}
|
||||
}
|
||||
|
||||
/// 确保库根与其 `assets/` 子目录存在。
|
||||
pub fn ensure_library(root: &Path) -> Result<(), String> {
|
||||
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();
|
||||
// 隐藏项(含 `.notes` 之类的私有目录)一律不进库树
|
||||
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,170 @@
|
||||
//! 笔记 / 编辑器模块。
|
||||
//!
|
||||
//! 架构位置:
|
||||
//!
|
||||
//! ```text
|
||||
//! 主模块页(设置 / 库管理) 独立窗口(CM6 编辑器)
|
||||
//! ↓ Tauri IPC ↓
|
||||
//! commands.rs 命令层
|
||||
//! ↓
|
||||
//! NotesManager(本文件):设置读写 / 库根解析
|
||||
//! ↓
|
||||
//! library.rs 文件系统(路径安全 / 扫描 / 读写 / 增删改移)
|
||||
//! ```
|
||||
//!
|
||||
//! # 真相在文件
|
||||
//!
|
||||
//! 笔记 = 库根下的 `.md` 文件树。Rust 侧只做文件 IO 与设置持久化,
|
||||
//! **不引入私有格式**;SQLite 索引(`index.rs`)只是可重建的加速层。
|
||||
//!
|
||||
//! # 三个入口的职责边界
|
||||
//!
|
||||
//! ```text
|
||||
//! library.rs 库内笔记:相对路径 + 树 + front-matter(安全模型 = 根目录沙箱)
|
||||
//! files.rs 库外任意文件:绝对路径 + 编码/换行(安全模型 = 授权白名单)
|
||||
//! index_service.rs 索引与监听:独占 SQLite 连接的单线程 worker + notify
|
||||
//! ```
|
||||
//!
|
||||
//! 设置持久化:`{app_data_dir}/notes/settings.json`(范式同 ai / translate)。
|
||||
//! 默认库根:`{app_data_dir}/notes/library`;用户可在设置里改。
|
||||
|
||||
mod args;
|
||||
mod backup;
|
||||
mod commands;
|
||||
mod export;
|
||||
mod files;
|
||||
mod import;
|
||||
mod index;
|
||||
mod index_service;
|
||||
mod library;
|
||||
mod templates;
|
||||
mod types;
|
||||
mod webdav;
|
||||
|
||||
pub use commands::{
|
||||
notes_add_template, notes_authorize_file, notes_backlinks, notes_backup_now,
|
||||
notes_create_folder, notes_create_note, notes_daily_note, notes_delete_entry,
|
||||
notes_export_note, notes_export_snapshot_local, notes_export_zip, notes_get_settings,
|
||||
notes_import, notes_index_stats, notes_library_info, notes_link_graph, notes_list_backups,
|
||||
notes_list_notes, notes_list_templates, notes_open_file, notes_read_asset, notes_read_note,
|
||||
notes_read_template, notes_rebuild_index, notes_rename_entry, notes_restore_backup,
|
||||
notes_save_note, notes_save_settings, notes_scan_library, notes_search_notes,
|
||||
notes_set_library_root, notes_set_webdav_password, notes_sync_index, notes_sync_now,
|
||||
notes_tags, notes_take_pending_file, notes_test_webdav, notes_webdav_status,
|
||||
notes_write_asset, notes_write_file,
|
||||
};
|
||||
pub use args::{emit_open_file, note_path_from_args, remember_pending_file};
|
||||
use types::NoteSettings;
|
||||
|
||||
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: NoteSettings,
|
||||
}
|
||||
|
||||
/// 笔记模块管理器(Tauri State)。
|
||||
pub struct NotesManager {
|
||||
/// 模块自身目录:`{app_data_dir}/notes`
|
||||
module_dir: PathBuf,
|
||||
cache: Mutex<Option<SettingsCache>>,
|
||||
}
|
||||
|
||||
impl NotesManager {
|
||||
pub fn new(app_data_dir: PathBuf) -> Self {
|
||||
let module_dir = app_data_dir.join("notes");
|
||||
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, "notes-new-note", &new_note, |app| {
|
||||
if let Err(e) = app.emit(crate::constants::events::NOTES_NEW_NOTE, ()) {
|
||||
crate::logger::log_warn("notes", &format!("发出新建笔记事件失败: {e}"));
|
||||
}
|
||||
}) {
|
||||
crate::logger::log_warn("notes", &format!("注册「新建笔记」快捷键失败: {e}"));
|
||||
}
|
||||
|
||||
let open_editor = settings.open_editor_shortcut.clone();
|
||||
if let Err(e) =
|
||||
crate::shortcut::register_shortcut(app, "notes-open-editor", &open_editor, |app| {
|
||||
if let Err(e) = app.emit(crate::constants::events::NOTES_OPEN_EDITOR, ()) {
|
||||
crate::logger::log_warn("notes", &format!("发出打开编辑器事件失败: {e}"));
|
||||
}
|
||||
})
|
||||
{
|
||||
crate::logger::log_warn("notes", &format!("注册「打开编辑器」快捷键失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
fn settings_path(&self) -> PathBuf {
|
||||
self.module_dir.join("settings.json")
|
||||
}
|
||||
|
||||
/// 读取设置(带短时缓存;文件缺失回退默认值;自愈结果落盘)。
|
||||
pub fn load_settings(&self) -> NoteSettings {
|
||||
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::<NoteSettings>(&s).ok())
|
||||
.unwrap_or_default();
|
||||
let healed = settings.heal();
|
||||
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("notes", &format!("设置自愈落盘失败: {e}"));
|
||||
}
|
||||
}
|
||||
settings
|
||||
}
|
||||
|
||||
/// 保存设置并刷新缓存。
|
||||
pub fn save_settings(&self, settings: &NoteSettings) -> 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,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,344 @@
|
||||
//! 笔记模块的数据模型。
|
||||
//!
|
||||
//! 持久化位置:`{app_data_dir}/notes/settings.json`(与 ai / translate / terminal 同一范式)。
|
||||
//! 容器级 `#[serde(default)]`:新增字段对旧配置文件向后兼容(缺字段取
|
||||
//! `Default::default()` 的对应值,而不是让整份设置反序列化失败)。
|
||||
//!
|
||||
//! 笔记正文**不在这里**:它以 `.md` 文件为准(见 `library.rs`),
|
||||
//! 本结构只保存「库根 + 编辑器偏好」这类模块级设置。
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
/// 结构版本号。字段增减时递增,由 [`NoteSettings::heal`] 推进。
|
||||
pub const NOTES_SETTINGS_VERSION: u32 = 2;
|
||||
|
||||
/// 同步方向。
|
||||
#[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(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 同步进度(事件 `notes-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>,
|
||||
}
|
||||
|
||||
/// 笔记 / 编辑器设置根结构。
|
||||
///
|
||||
/// 字段取值必须与前端 `src/modules/notes/editor/themes.ts` 的 key 保持一致,
|
||||
/// 否则用户选了主题却回落默认(静默失效,终端模块踩过这个坑)。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct NoteSettings {
|
||||
/// 结构版本号
|
||||
pub version: u32,
|
||||
/// 自定义库根(`None` = 用默认 `{app_data_dir}/notes/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` 的原子注册 + 冲突检测(与终端 / 翻译同一套),
|
||||
/// 触发时只发 `notes-new-note` 事件,窗口由前端创建 —— Rust 侧不持窗口 label 策略。
|
||||
pub new_note_shortcut: String,
|
||||
/// 全局快捷键:打开编辑器窗口(空串 = 不注册)
|
||||
pub open_editor_shortcut: String,
|
||||
}
|
||||
|
||||
impl Default for NoteSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
version: NOTES_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,
|
||||
autosave_ms: 800,
|
||||
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: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NoteSettings {
|
||||
/// 自愈:把越界/非法取值夹回合法区间,推进版本号。
|
||||
/// 返回是否发生了变更(由调用方决定是否落盘)。
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
if self.version < NOTES_SETTINGS_VERSION {
|
||||
self.version = NOTES_SETTINGS_VERSION;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
changed
|
||||
}
|
||||
}
|
||||
|
||||
/// 库内一个条目(文件或目录)的扁平描述。
|
||||
///
|
||||
/// **刻意用扁平列表而不是树**:递归类型在 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}/notes/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(
|
||||
"notes",
|
||||
&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(
|
||||
"notes",
|
||||
&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("notes", "远端目录过多,提前结束遍历");
|
||||
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)
|
||||
}
|
||||
|
||||
/// 该远端路径是否应当排除在同步之外。
|
||||
///
|
||||
/// `.notes/` 是本模块的私有目录(索引 + 同步状态),**必须排除**:把索引同步到
|
||||
/// 远端毫无意义,且它随每次搜索变化,会让每一次同步都变成全量传输。
|
||||
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(".notes/notes.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::notes::types::WebdavSettings;
|
||||
use client::WebdavClient;
|
||||
|
||||
/// keyring 里的服务名(与 `secrets.rs` 的约定一致,服务名固定 `"Thing"`)。
|
||||
pub const KEYRING_PASSWORD: &str = "notes.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
@@ -21,6 +21,7 @@ use crate::mihomo_manager::MihomoManager;
|
||||
use crate::monitor_kernel::{MonitorKernel, check_and_relaunch_if_needed};
|
||||
use crate::music::MusicManager;
|
||||
use crate::network_monitor::NetworkMonitor;
|
||||
use crate::notes::NotesManager;
|
||||
use crate::process_manager::{ProcessManager, start_monitoring_thread};
|
||||
use crate::terminal::TerminalManager;
|
||||
use crate::translate::TranslateManager;
|
||||
@@ -83,6 +84,21 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let dsh = crate::dsh::DshManager::new(app_data_dir.clone());
|
||||
app.manage(dsh);
|
||||
|
||||
// ===== 笔记模块:NotesManager =====
|
||||
// 仅注册状态:库扫描与读写都在命令调用时按需触发,启动阶段只创建目录结构。
|
||||
let notes = NotesManager::new(app_data_dir.clone());
|
||||
let _ = notes.load_settings();
|
||||
// 按设置注册「新建笔记 / 打开编辑器」两个全局快捷键(失败只记日志,不阻断启动)
|
||||
notes.init_on_launch(app.handle());
|
||||
app.manage(notes);
|
||||
// 「用 Thing 打开」的**冷启动**路径:命令行里带了 .md 就记下来。
|
||||
// 不在这里 `emit` —— 此时 WebView 还没加载、前端还没注册监听,事件会丢掉。
|
||||
// 前端注册完监听后会主动调 `notes_take_pending_file` 取走(见 notes/args.rs)。
|
||||
if let Some(path) = crate::notes::note_path_from_args(std::env::args().skip(1)) {
|
||||
crate::logger::log_info("notes", &format!("命令行指定打开: {}", path.display()));
|
||||
crate::notes::remember_pending_file(path);
|
||||
}
|
||||
|
||||
// ===== 翻译模块:TranslateManager =====
|
||||
// 仅注册状态:设置与密钥都在命令调用时按需读取,启动阶段不发任何网络请求
|
||||
// (模型可用性校验因此改为懒校验:首次翻译失败时解释原因 + 设置页手动拉取模型列表)。
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "thing",
|
||||
"version": "26.9.4",
|
||||
"version": "26.9.5",
|
||||
"identifier": "thing.lfeng.me",
|
||||
"build": {
|
||||
"beforeDevCommand": "bun run dev",
|
||||
@@ -38,6 +38,14 @@
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"resources": ["binaries/*", "resources/thing-extension/**/*"],
|
||||
"fileAssociations": [
|
||||
{
|
||||
"ext": ["md", "markdown", "mdx"],
|
||||
"name": "Markdown 笔记",
|
||||
"description": "用 Thing 打开 Markdown 笔记",
|
||||
"role": "Editor"
|
||||
}
|
||||
],
|
||||
"windows": {
|
||||
"nsis": {
|
||||
"compression": "lzma"
|
||||
|
||||
Reference in new issue
Block a user