调整,音乐模块
This commit is contained in:
@@ -10,6 +10,9 @@ lerna-debug.log*
|
|||||||
# 发布暂存目录
|
# 发布暂存目录
|
||||||
release_stage/
|
release_stage/
|
||||||
|
|
||||||
|
# musicdl 手动测试产物(search_results.pkl 等)
|
||||||
|
musicdl_outputs/
|
||||||
|
|
||||||
node_modules
|
node_modules
|
||||||
dist
|
dist
|
||||||
dist-ssr
|
dist-ssr
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "thing",
|
"name": "thing",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "26.8.5",
|
"version": "26.9.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
import sys, importlib.util
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8")
|
||||||
|
from musicdl.modules.sources.qq import QQMusicClient
|
||||||
|
from musicdl.modules.sources.netease import NeteaseMusicClient
|
||||||
|
from musicdl.modules.sources.kugou import KugouMusicClient
|
||||||
|
from musicdl.modules.utils.qqutils import SongFileType
|
||||||
|
# find MUSIC_QUALITIES in source modules
|
||||||
|
for mod in (QQMusicClient, NeteaseMusicClient, KugouMusicClient):
|
||||||
|
src = mod.__module__
|
||||||
|
m = getattr(mod, 'source', '?')
|
||||||
|
names = [x for x in mod.__init__.__globals__.keys() if 'QUALIT' in x.upper()]
|
||||||
|
print("SRC", m, "quality-names-in-globals:", names)
|
||||||
|
for n in names:
|
||||||
|
v = mod.__init__.__globals__[n]
|
||||||
|
print(" ", n, "=", v)
|
||||||
|
print("QQ SORTED_QUALITIES:", SongFileType.SORTED_QUALITIES.value)
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import sys, json, importlib.util
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8")
|
||||||
|
spec = importlib.util.spec_from_file_location("bridge", r"d:\Atie\Gitea\Thing\src-tauri\src\music\bridge.py")
|
||||||
|
b = importlib.util.module_from_spec(spec); spec.loader.exec_module(b)
|
||||||
|
client = b.get_client(["QQMusicClient"])
|
||||||
|
res = client.search("海阔天空")
|
||||||
|
s = res["QQMusicClient"][0]
|
||||||
|
rs = (s.raw_data or {}).get("search")
|
||||||
|
src = b._get_resolve_client("QQMusicClient")
|
||||||
|
print("raw song:", s.song_name, "| id", s.identifier)
|
||||||
|
# official alone, lossless_quality_is_sufficient=False, no cap
|
||||||
|
from musicdl.modules.utils.data import SongInfo
|
||||||
|
official = src._parsewithofficialapiv1
|
||||||
|
r2 = official(search_result=rs, song_info_flac=SongInfo(source="QQMusicClient"), lossless_quality_is_sufficient=False)
|
||||||
|
print("official-only uncapped -> ext=", getattr(r2,"ext",None), "valid=", getattr(r2,"with_valid_download_url",None))
|
||||||
|
for target in ("", "最高", "无损", "320K", "128K"):
|
||||||
|
r = b._resolve_song(src, rs, target)
|
||||||
|
print("target=%r ->" % target, "ext=", getattr(r,"ext",None), "bitrate=", getattr(r,"bitrate",None), "valid=", getattr(r,"with_valid_download_url",None))
|
||||||
|
# verify constant restored
|
||||||
|
import musicdl.modules.utils.qqutils as qq
|
||||||
|
print("restored SORTED len:", len(qq.SongFileType.SORTED_QUALITIES.value))
|
||||||
Generated
+232
-2
@@ -515,6 +515,12 @@ version = "0.23.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
|
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "base64ct"
|
||||||
|
version = "1.8.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bit-set"
|
name = "bit-set"
|
||||||
version = "0.8.0"
|
version = "0.8.0"
|
||||||
@@ -566,6 +572,15 @@ dependencies = [
|
|||||||
"generic-array 0.14.7",
|
"generic-array 0.14.7",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "block-padding"
|
||||||
|
version = "0.3.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"
|
||||||
|
dependencies = [
|
||||||
|
"generic-array 0.14.7",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "block2"
|
name = "block2"
|
||||||
version = "0.6.2"
|
version = "0.6.2"
|
||||||
@@ -748,6 +763,15 @@ dependencies = [
|
|||||||
"toml 0.9.12+spec-1.1.0",
|
"toml 0.9.12+spec-1.1.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cbc"
|
||||||
|
version = "0.1.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"
|
||||||
|
dependencies = [
|
||||||
|
"cipher",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cc"
|
name = "cc"
|
||||||
version = "1.2.67"
|
version = "1.2.67"
|
||||||
@@ -908,6 +932,12 @@ dependencies = [
|
|||||||
"crossbeam-utils",
|
"crossbeam-utils",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "const-oid"
|
||||||
|
version = "0.9.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "const_panic"
|
name = "const_panic"
|
||||||
version = "0.2.17"
|
version = "0.2.17"
|
||||||
@@ -1192,6 +1222,17 @@ version = "0.1.12"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2"
|
checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "der"
|
||||||
|
version = "0.7.10"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
|
||||||
|
dependencies = [
|
||||||
|
"const-oid",
|
||||||
|
"pem-rfc7468",
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "deranged"
|
name = "deranged"
|
||||||
version = "0.5.8"
|
version = "0.5.8"
|
||||||
@@ -1240,6 +1281,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"block-buffer",
|
"block-buffer",
|
||||||
|
"const-oid",
|
||||||
"crypto-common",
|
"crypto-common",
|
||||||
"subtle",
|
"subtle",
|
||||||
]
|
]
|
||||||
@@ -2619,6 +2661,7 @@ version = "0.1.4"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
|
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"block-padding",
|
||||||
"generic-array 0.14.7",
|
"generic-array 0.14.7",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -2847,6 +2890,9 @@ name = "lazy_static"
|
|||||||
version = "1.5.0"
|
version = "1.5.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
|
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
|
||||||
|
dependencies = [
|
||||||
|
"spin",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "leaky-bucket"
|
name = "leaky-bucket"
|
||||||
@@ -2908,6 +2954,12 @@ dependencies = [
|
|||||||
"winapi",
|
"winapi",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "libm"
|
||||||
|
version = "0.2.16"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "libredox"
|
name = "libredox"
|
||||||
version = "0.1.18"
|
version = "0.1.18"
|
||||||
@@ -3324,6 +3376,16 @@ version = "0.8.4"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
|
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "md-5"
|
||||||
|
version = "0.10.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"digest",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "memchr"
|
name = "memchr"
|
||||||
version = "2.8.3"
|
version = "2.8.3"
|
||||||
@@ -3570,6 +3632,22 @@ dependencies = [
|
|||||||
"num-traits",
|
"num-traits",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "num-bigint-dig"
|
||||||
|
version = "0.8.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7"
|
||||||
|
dependencies = [
|
||||||
|
"lazy_static",
|
||||||
|
"libm",
|
||||||
|
"num-integer",
|
||||||
|
"num-iter",
|
||||||
|
"num-traits",
|
||||||
|
"rand 0.8.8",
|
||||||
|
"smallvec",
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "num-complex"
|
name = "num-complex"
|
||||||
version = "0.2.4"
|
version = "0.2.4"
|
||||||
@@ -3623,6 +3701,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"autocfg",
|
"autocfg",
|
||||||
|
"libm",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -3989,6 +4068,15 @@ dependencies = [
|
|||||||
"hmac",
|
"hmac",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pem-rfc7468"
|
||||||
|
version = "0.7.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412"
|
||||||
|
dependencies = [
|
||||||
|
"base64ct",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "percent-encoding"
|
name = "percent-encoding"
|
||||||
version = "2.3.2"
|
version = "2.3.2"
|
||||||
@@ -4065,6 +4153,27 @@ dependencies = [
|
|||||||
"futures-io",
|
"futures-io",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pkcs1"
|
||||||
|
version = "0.7.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"
|
||||||
|
dependencies = [
|
||||||
|
"der",
|
||||||
|
"pkcs8",
|
||||||
|
"spki",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pkcs8"
|
||||||
|
version = "0.10.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
|
||||||
|
dependencies = [
|
||||||
|
"der",
|
||||||
|
"spki",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pkg-config"
|
name = "pkg-config"
|
||||||
version = "0.3.33"
|
version = "0.3.33"
|
||||||
@@ -4346,13 +4455,24 @@ version = "0.7.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09"
|
checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rand"
|
||||||
|
version = "0.8.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"rand_chacha 0.3.1",
|
||||||
|
"rand_core 0.6.4",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rand"
|
name = "rand"
|
||||||
version = "0.9.5"
|
version = "0.9.5"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
|
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"rand_chacha",
|
"rand_chacha 0.9.0",
|
||||||
"rand_core 0.9.5",
|
"rand_core 0.9.5",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -4367,6 +4487,16 @@ dependencies = [
|
|||||||
"rand_core 0.10.1",
|
"rand_core 0.10.1",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rand_chacha"
|
||||||
|
version = "0.3.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
|
||||||
|
dependencies = [
|
||||||
|
"ppv-lite86",
|
||||||
|
"rand_core 0.6.4",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rand_chacha"
|
name = "rand_chacha"
|
||||||
version = "0.9.0"
|
version = "0.9.0"
|
||||||
@@ -4377,6 +4507,15 @@ dependencies = [
|
|||||||
"rand_core 0.9.5",
|
"rand_core 0.9.5",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rand_core"
|
||||||
|
version = "0.6.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
|
||||||
|
dependencies = [
|
||||||
|
"getrandom 0.2.17",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rand_core"
|
name = "rand_core"
|
||||||
version = "0.9.5"
|
version = "0.9.5"
|
||||||
@@ -4547,6 +4686,7 @@ dependencies = [
|
|||||||
"js-sys",
|
"js-sys",
|
||||||
"log",
|
"log",
|
||||||
"mime",
|
"mime",
|
||||||
|
"mime_guess",
|
||||||
"native-tls",
|
"native-tls",
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
@@ -4666,6 +4806,26 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rsa"
|
||||||
|
version = "0.9.10"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d"
|
||||||
|
dependencies = [
|
||||||
|
"const-oid",
|
||||||
|
"digest",
|
||||||
|
"num-bigint-dig",
|
||||||
|
"num-integer",
|
||||||
|
"num-traits",
|
||||||
|
"pkcs1",
|
||||||
|
"pkcs8",
|
||||||
|
"rand_core 0.6.4",
|
||||||
|
"signature",
|
||||||
|
"spki",
|
||||||
|
"subtle",
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rusqlite"
|
name = "rusqlite"
|
||||||
version = "0.32.1"
|
version = "0.32.1"
|
||||||
@@ -5167,6 +5327,16 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "signature"
|
||||||
|
version = "2.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
|
||||||
|
dependencies = [
|
||||||
|
"digest",
|
||||||
|
"rand_core 0.6.4",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "simd-adler32"
|
name = "simd-adler32"
|
||||||
version = "0.3.9"
|
version = "0.3.9"
|
||||||
@@ -5327,6 +5497,12 @@ dependencies = [
|
|||||||
"specta",
|
"specta",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "spin"
|
||||||
|
version = "0.9.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "spinning_top"
|
name = "spinning_top"
|
||||||
version = "0.3.0"
|
version = "0.3.0"
|
||||||
@@ -5336,6 +5512,16 @@ dependencies = [
|
|||||||
"lock_api",
|
"lock_api",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "spki"
|
||||||
|
version = "0.7.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
|
||||||
|
dependencies = [
|
||||||
|
"base64ct",
|
||||||
|
"der",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "stable_deref_trait"
|
name = "stable_deref_trait"
|
||||||
version = "1.2.1"
|
version = "1.2.1"
|
||||||
@@ -5951,24 +6137,31 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "thing"
|
name = "thing"
|
||||||
version = "26.8.5"
|
version = "26.9.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"aes",
|
||||||
"axum 0.7.9",
|
"axum 0.7.9",
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
"bytes",
|
"bytes",
|
||||||
|
"cbc",
|
||||||
"chrono",
|
"chrono",
|
||||||
"dirs 5.0.1",
|
"dirs 5.0.1",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
|
"hmac",
|
||||||
"image",
|
"image",
|
||||||
"librqbit",
|
"librqbit",
|
||||||
|
"md-5",
|
||||||
"notify",
|
"notify",
|
||||||
|
"rand 0.8.8",
|
||||||
"raw-window-handle",
|
"raw-window-handle",
|
||||||
"regex",
|
"regex",
|
||||||
"reqwest 0.12.28",
|
"reqwest 0.12.28",
|
||||||
|
"rsa",
|
||||||
"rusqlite",
|
"rusqlite",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"serde_yaml",
|
"serde_yaml",
|
||||||
|
"sha2",
|
||||||
"specta",
|
"specta",
|
||||||
"specta-typescript",
|
"specta-typescript",
|
||||||
"sysinfo",
|
"sysinfo",
|
||||||
@@ -5982,6 +6175,7 @@ dependencies = [
|
|||||||
"tauri-plugin-snap-layout",
|
"tauri-plugin-snap-layout",
|
||||||
"tauri-specta",
|
"tauri-specta",
|
||||||
"tokio",
|
"tokio",
|
||||||
|
"tokio-tungstenite",
|
||||||
"url",
|
"url",
|
||||||
"walkdir",
|
"walkdir",
|
||||||
"windows 0.52.0",
|
"windows 0.52.0",
|
||||||
@@ -6156,6 +6350,18 @@ dependencies = [
|
|||||||
"tokio-util",
|
"tokio-util",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tokio-tungstenite"
|
||||||
|
version = "0.24.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "edc5f74e248dc973e0dbb7b74c7e0d6fcc301c694ff50049504004ef4d0cdcd9"
|
||||||
|
dependencies = [
|
||||||
|
"futures-util",
|
||||||
|
"log",
|
||||||
|
"tokio",
|
||||||
|
"tungstenite",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tokio-util"
|
name = "tokio-util"
|
||||||
version = "0.7.18"
|
version = "0.7.18"
|
||||||
@@ -6395,6 +6601,24 @@ version = "0.2.5"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tungstenite"
|
||||||
|
version = "0.24.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "18e5b8366ee7a95b16d32197d0b2604b43a0be89dc5fac9f8e96ccafbaedda8a"
|
||||||
|
dependencies = [
|
||||||
|
"byteorder",
|
||||||
|
"bytes",
|
||||||
|
"data-encoding",
|
||||||
|
"http",
|
||||||
|
"httparse",
|
||||||
|
"log",
|
||||||
|
"rand 0.8.8",
|
||||||
|
"sha1",
|
||||||
|
"thiserror 1.0.69",
|
||||||
|
"utf-8",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "typeid"
|
name = "typeid"
|
||||||
version = "1.0.3"
|
version = "1.0.3"
|
||||||
@@ -6526,6 +6750,12 @@ dependencies = [
|
|||||||
"url",
|
"url",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "utf-8"
|
||||||
|
version = "0.7.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "utf8_iter"
|
name = "utf8_iter"
|
||||||
version = "1.0.4"
|
version = "1.0.4"
|
||||||
|
|||||||
+17
-10
File diff suppressed because one or more lines are too long
@@ -63,6 +63,10 @@ pub mod events {
|
|||||||
pub const SCROLL_CANCELLED: &str = "screenshot-scroll-cancelled";
|
pub const SCROLL_CANCELLED: &str = "screenshot-scroll-cancelled";
|
||||||
// 内核安装进度
|
// 内核安装进度
|
||||||
pub const KERNEL_INSTALL_PROGRESS: &str = "kernel-install-progress";
|
pub const KERNEL_INSTALL_PROGRESS: &str = "kernel-install-progress";
|
||||||
|
// 音乐模块:Python 便携运行时安装进度
|
||||||
|
pub const MUSIC_RUNTIME_INSTALL_PROGRESS: &str = "music-runtime-install-progress";
|
||||||
|
// 音乐模块:下载任务事件(桥接事件行 → 前端,负载见 bridge.py _emit_event)
|
||||||
|
pub const MUSIC_DOWNLOAD_EVENT: &str = "music-download-event";
|
||||||
// 后端自动切换节点完成(前端据以刷新节点列表并提示)
|
// 后端自动切换节点完成(前端据以刷新节点列表并提示)
|
||||||
pub const PROXY_AUTO_SWITCH: &str = "proxy-auto-switch";
|
pub const PROXY_AUTO_SWITCH: &str = "proxy-auto-switch";
|
||||||
// 应用更新进度
|
// 应用更新进度
|
||||||
|
|||||||
+58
-2
@@ -6,6 +6,7 @@ mod download_engine;
|
|||||||
mod logger;
|
mod logger;
|
||||||
mod mihomo_manager;
|
mod mihomo_manager;
|
||||||
mod monitor_kernel;
|
mod monitor_kernel;
|
||||||
|
mod music;
|
||||||
mod network_monitor;
|
mod network_monitor;
|
||||||
mod osd_window;
|
mod osd_window;
|
||||||
mod process_manager;
|
mod process_manager;
|
||||||
@@ -41,6 +42,17 @@ use monitor_kernel::{
|
|||||||
monitor_set_hardware_config, monitor_start, monitor_start_elevated, monitor_status, monitor_stop,
|
monitor_set_hardware_config, monitor_start, monitor_start_elevated, monitor_status, monitor_stop,
|
||||||
MonitorKernel,
|
MonitorKernel,
|
||||||
};
|
};
|
||||||
|
use music::{
|
||||||
|
feiniu_activate_connection, feiniu_cache_clear, feiniu_cache_fetch, feiniu_cache_status,
|
||||||
|
feiniu_delete_connection, feiniu_fnconnect_resolve, feiniu_fnos_delete, feiniu_fnos_list,
|
||||||
|
feiniu_fnos_login, feiniu_fnos_logout, feiniu_fnos_status, feiniu_fnos_upload,
|
||||||
|
feiniu_get_config, feiniu_list_connections, feiniu_list_tracks, feiniu_login, feiniu_logout,
|
||||||
|
feiniu_lyric, feiniu_media_prefix, feiniu_save_connection, feiniu_scan_local,
|
||||||
|
feiniu_test_connection, music_cancel_runtime_install, music_download, music_download_cancel,
|
||||||
|
music_env_status, music_get_settings, music_get_sources, music_install_runtime,
|
||||||
|
music_parse_playlist, music_ping, music_resolve, music_save_settings, music_search,
|
||||||
|
music_stop_bridge, MusicManager,
|
||||||
|
};
|
||||||
use network_monitor::network_status;
|
use network_monitor::network_status;
|
||||||
use osd_window::{
|
use osd_window::{
|
||||||
osd_apply_overlay_style, osd_begin_drag, osd_set_bounds, osd_set_click_through,
|
osd_apply_overlay_style, osd_begin_drag, osd_set_bounds, osd_set_click_through,
|
||||||
@@ -61,7 +73,7 @@ use screenshot::commands::{
|
|||||||
screenshot_register_shortcut,
|
screenshot_register_shortcut,
|
||||||
screenshot_save_cache, screenshot_save_png, screenshot_scroll_capture,
|
screenshot_save_cache, screenshot_save_png, screenshot_scroll_capture,
|
||||||
screenshot_scroll_cancel, screenshot_scroll_finish, screenshot_scroll_start,
|
screenshot_scroll_cancel, screenshot_scroll_finish, screenshot_scroll_start,
|
||||||
screenshot_show_overlay, screenshot_take_editor_image_raw,
|
screenshot_set_scroll_hole, screenshot_show_overlay, screenshot_take_editor_image_raw,
|
||||||
screenshot_unregister_pin_shortcut, screenshot_unregister_shortcut,
|
screenshot_unregister_pin_shortcut, screenshot_unregister_shortcut,
|
||||||
};
|
};
|
||||||
use clipboard::{
|
use clipboard::{
|
||||||
@@ -149,7 +161,10 @@ fn export_bindings() {
|
|||||||
downloader_get_tasks, downloader_check_url, downloader_add_task, downloader_pause_task,
|
downloader_get_tasks, downloader_check_url, downloader_add_task, downloader_pause_task,
|
||||||
downloader_resume_task, downloader_cancel_task, downloader_redownload, downloader_remove_task, downloader_get_settings,
|
downloader_resume_task, downloader_cancel_task, downloader_redownload, downloader_remove_task, downloader_get_settings,
|
||||||
downloader_save_settings, downloader_open_dir, downloader_open_url, downloader_focus_window, downloader_inspect, downloader_select_bt_files,
|
downloader_save_settings, downloader_open_dir, downloader_open_url, downloader_focus_window, downloader_inspect, downloader_select_bt_files,
|
||||||
// screenshot(22,豁免 3:get_fullscreen_bmp / take_editor_image_raw 返回 ipc::Response、
|
// music(6,豁免 3:music_ping / music_get_sources / music_search 返回 serde_json::Value)
|
||||||
|
music_env_status, music_install_runtime, music_cancel_runtime_install,
|
||||||
|
music_stop_bridge, music_get_settings, music_save_settings,
|
||||||
|
// screenshot(23,豁免 3:get_fullscreen_bmp / take_editor_image_raw 返回 ipc::Response、
|
||||||
// compose_copy / compose_png 接收 ipc::Request)
|
// compose_copy / compose_png 接收 ipc::Request)
|
||||||
screenshot_disable_transitions, screenshot_show_overlay, screenshot_register_shortcut,
|
screenshot_disable_transitions, screenshot_show_overlay, screenshot_register_shortcut,
|
||||||
screenshot_unregister_shortcut, screenshot_register_pin_shortcut,
|
screenshot_unregister_shortcut, screenshot_register_pin_shortcut,
|
||||||
@@ -158,6 +173,7 @@ fn export_bindings() {
|
|||||||
screenshot_crop_copy_stored, screenshot_pick_list, screenshot_cursor_pos,
|
screenshot_crop_copy_stored, screenshot_pick_list, screenshot_cursor_pos,
|
||||||
screenshot_enum_windows, screenshot_capture_window, screenshot_scroll_capture,
|
screenshot_enum_windows, screenshot_capture_window, screenshot_scroll_capture,
|
||||||
screenshot_scroll_cancel, screenshot_scroll_finish, screenshot_scroll_start,
|
screenshot_scroll_cancel, screenshot_scroll_finish, screenshot_scroll_start,
|
||||||
|
screenshot_set_scroll_hole,
|
||||||
screenshot_copy_image, screenshot_save_png,
|
screenshot_copy_image, screenshot_save_png,
|
||||||
screenshot_save_cache, screenshot_load_cache, screenshot_delete_cache,
|
screenshot_save_cache, screenshot_load_cache, screenshot_delete_cache,
|
||||||
])
|
])
|
||||||
@@ -243,6 +259,41 @@ pub fn run() {
|
|||||||
monitor_set_auto_start,
|
monitor_set_auto_start,
|
||||||
monitor_get_hardware_config,
|
monitor_get_hardware_config,
|
||||||
monitor_set_hardware_config,
|
monitor_set_hardware_config,
|
||||||
|
music_env_status,
|
||||||
|
music_install_runtime,
|
||||||
|
music_cancel_runtime_install,
|
||||||
|
music_ping,
|
||||||
|
music_stop_bridge,
|
||||||
|
music_get_sources,
|
||||||
|
music_search,
|
||||||
|
music_parse_playlist,
|
||||||
|
music_resolve,
|
||||||
|
music_get_settings,
|
||||||
|
music_save_settings,
|
||||||
|
music_download,
|
||||||
|
music_download_cancel,
|
||||||
|
feiniu_list_connections,
|
||||||
|
feiniu_save_connection,
|
||||||
|
feiniu_delete_connection,
|
||||||
|
feiniu_activate_connection,
|
||||||
|
feiniu_test_connection,
|
||||||
|
feiniu_login,
|
||||||
|
feiniu_logout,
|
||||||
|
feiniu_get_config,
|
||||||
|
feiniu_list_tracks,
|
||||||
|
feiniu_lyric,
|
||||||
|
feiniu_media_prefix,
|
||||||
|
feiniu_scan_local,
|
||||||
|
feiniu_cache_status,
|
||||||
|
feiniu_cache_clear,
|
||||||
|
feiniu_cache_fetch,
|
||||||
|
feiniu_fnos_login,
|
||||||
|
feiniu_fnos_logout,
|
||||||
|
feiniu_fnos_status,
|
||||||
|
feiniu_fnos_upload,
|
||||||
|
feiniu_fnos_delete,
|
||||||
|
feiniu_fnos_list,
|
||||||
|
feiniu_fnconnect_resolve,
|
||||||
network_status,
|
network_status,
|
||||||
osd_apply_overlay_style,
|
osd_apply_overlay_style,
|
||||||
osd_begin_drag,
|
osd_begin_drag,
|
||||||
@@ -344,6 +395,7 @@ pub fn run() {
|
|||||||
screenshot_scroll_cancel,
|
screenshot_scroll_cancel,
|
||||||
screenshot_scroll_finish,
|
screenshot_scroll_finish,
|
||||||
screenshot_scroll_start,
|
screenshot_scroll_start,
|
||||||
|
screenshot_set_scroll_hole,
|
||||||
screenshot_take_editor_image_raw,
|
screenshot_take_editor_image_raw,
|
||||||
screenshot_copy_image,
|
screenshot_copy_image,
|
||||||
screenshot_save_png,
|
screenshot_save_png,
|
||||||
@@ -395,6 +447,10 @@ pub fn run() {
|
|||||||
});
|
});
|
||||||
let _ = rx.recv_timeout(std::time::Duration::from_secs(3));
|
let _ = rx.recv_timeout(std::time::Duration::from_secs(3));
|
||||||
}
|
}
|
||||||
|
if let Some(music) = app.try_state::<MusicManager>() {
|
||||||
|
// 停止音乐桥接进程(kill 快速返回,wait 在后台线程完成)
|
||||||
|
music.cleanup_on_exit();
|
||||||
|
}
|
||||||
if let Some(clip) = app.try_state::<ClipboardManager>() {
|
if let Some(clip) = app.try_state::<ClipboardManager>() {
|
||||||
clip.stop();
|
clip.stop();
|
||||||
}
|
}
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,262 @@
|
|||||||
|
//! 桥接进程生命周期:spawn(stdio JSON-Lines 协议)→ 请求分发 → 事件转发 → 停止。
|
||||||
|
//! 子模块通过 `impl super::MusicManager` 追加方法。
|
||||||
|
//!
|
||||||
|
//! 协议(与 bridge.py 对应):
|
||||||
|
//! 请求 `{"id":1,"method":"ping","params":{}}`
|
||||||
|
//! 响应 `{"id":1,"ok":true,"result":{...}}` 或 `{"id":1,"ok":false,"error":"..."}`
|
||||||
|
//! 无 id 的事件行 `{"event":"download","type":"progress",...}` 由 reader 线程
|
||||||
|
//! 原样转发为 Tauri 事件 `music-download-event`(见 constants::events)。
|
||||||
|
|
||||||
|
use std::io::{BufRead, BufReader, Write};
|
||||||
|
use std::process::{Command, Stdio};
|
||||||
|
use tauri::Emitter;
|
||||||
|
|
||||||
|
use super::{BridgeEntry, MusicManager, PythonEnv};
|
||||||
|
|
||||||
|
/// 桥接脚本源码(内置,运行时写出到 {root}/bridge.py,避免资源目录配置)
|
||||||
|
const BRIDGE_SCRIPT: &str = include_str!("bridge.py");
|
||||||
|
|
||||||
|
/// 桥接请求错误分类:决定是否允许重启桥接进程重试。
|
||||||
|
/// 应用层错误与超时绝不能触发重启——重启会杀掉正在进行的下载任务。
|
||||||
|
pub(crate) enum BridgeError {
|
||||||
|
/// 传输层错误(进程退出/管道损坏/写入失败/通道关闭)→ 可重启重试
|
||||||
|
Transport(String),
|
||||||
|
/// 应用层错误(桥接正常响应 ok:false)→ 不重启
|
||||||
|
App(String),
|
||||||
|
/// 响应超时 → 不重启(进程可能只是忙,如正在执行长耗时搜索)
|
||||||
|
Timeout(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BridgeError {
|
||||||
|
fn into_message(self) -> String {
|
||||||
|
match self {
|
||||||
|
BridgeError::Transport(m) | BridgeError::App(m) | BridgeError::Timeout(m) => m,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MusicManager {
|
||||||
|
/// 桥接进程是否在运行(存在且未退出)
|
||||||
|
pub fn bridge_running(&self) -> bool {
|
||||||
|
let mut guard = match self.bridge.lock() {
|
||||||
|
Ok(g) => g,
|
||||||
|
Err(_) => return false,
|
||||||
|
};
|
||||||
|
match guard.as_mut() {
|
||||||
|
Some(entry) => entry.child.try_wait().ok().map(|w| w.is_none()).unwrap_or(false),
|
||||||
|
None => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 确保桥接进程已启动(已启动则直接返回;并发调用由 start_lock 串行化)
|
||||||
|
pub fn ensure_bridge(&self) -> Result<(), String> {
|
||||||
|
if self.bridge_running() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let _guard = self.start_lock().lock().map_err(|e| e.to_string())?;
|
||||||
|
// 二次检查(等待锁期间可能已被其他调用方启动)
|
||||||
|
if self.bridge_running() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
// 清理可能残留的旧条目
|
||||||
|
self.bridge.lock().map_err(|e| e.to_string())?.take();
|
||||||
|
let python = self.resolve_python()?;
|
||||||
|
self.spawn_bridge(&python)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 启动桥接进程:stdin/stdout 管道直连,stderr 写入 runtime/bridge_stderr.log
|
||||||
|
fn spawn_bridge(&self, python: &PythonEnv) -> Result<(), String> {
|
||||||
|
let script = self.bridge_script_path();
|
||||||
|
// 每次启动前重写脚本,保证与当前版本一致(内容固定,成本极低)
|
||||||
|
std::fs::write(&script, BRIDGE_SCRIPT).map_err(|e| format!("写出桥接脚本失败: {}", e))?;
|
||||||
|
|
||||||
|
let stderr_log = self.runtime_dir().join("bridge_stderr.log");
|
||||||
|
let stderr_file = std::fs::File::create(&stderr_log).map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
let mut cmd = Command::new(&python.exe);
|
||||||
|
cmd.arg(&script);
|
||||||
|
cmd.stdin(Stdio::piped())
|
||||||
|
.stdout(Stdio::piped())
|
||||||
|
.stderr(Stdio::from(stderr_file));
|
||||||
|
crate::process_manager::setup_creation_flags(&mut cmd);
|
||||||
|
// cwd 统一设为模块根目录:musicdl 会在 cwd 落 search_results.pkl 等缓存文件,
|
||||||
|
// 不设置时(系统 Python)会污染应用工作目录(开发期为仓库根目录)
|
||||||
|
if let Some(parent) = script.parent() {
|
||||||
|
cmd.current_dir(parent);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut child = cmd
|
||||||
|
.spawn()
|
||||||
|
.map_err(|e| format!("启动桥接进程失败 (python: {}): {}", python.exe.display(), e))?;
|
||||||
|
crate::process_manager::assign_to_job(&child);
|
||||||
|
|
||||||
|
let stdin = child.stdin.take().ok_or_else(|| "无法获取桥接 stdin".to_string())?;
|
||||||
|
let stdout = child.stdout.take().ok_or_else(|| "无法获取桥接 stdout".to_string())?;
|
||||||
|
|
||||||
|
*self.bridge.lock().map_err(|e| e.to_string())? = Some(BridgeEntry { child, stdin });
|
||||||
|
|
||||||
|
// 启动 stdout reader 线程:按行读取,按 id 分发到 pending;无 id 的事件行转发到前端
|
||||||
|
let pending = self.pending.clone();
|
||||||
|
let app = self.app_handle();
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
let reader = BufReader::new(stdout);
|
||||||
|
for line in reader.lines() {
|
||||||
|
let Ok(line) = line else { break };
|
||||||
|
let Ok(v) = serde_json::from_str::<serde_json::Value>(&line) else {
|
||||||
|
crate::logger::log_warn("music-bridge", &format!("无法解析 stdout: {}", line));
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if let Some(id) = v.get("id").and_then(|i| i.as_u64()) {
|
||||||
|
if let Some(tx) = pending.lock().ok().and_then(|mut m| m.remove(&id)) {
|
||||||
|
let _ = tx.send(v);
|
||||||
|
}
|
||||||
|
} else if v.get("event").is_some() {
|
||||||
|
// 事件行(下载进度等):原样转发给前端
|
||||||
|
if let Some(app) = app.as_ref() {
|
||||||
|
let _ = app.emit(crate::constants::events::MUSIC_DOWNLOAD_EVENT, &v);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 其他无 id 行仅记日志
|
||||||
|
crate::logger::log_info("music-bridge", &line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
crate::logger::log_info("music-bridge", "stdout 已关闭,reader 线程退出");
|
||||||
|
});
|
||||||
|
|
||||||
|
crate::logger::log_info(
|
||||||
|
"music-bridge",
|
||||||
|
&format!("桥接进程已启动 (python: {})", python.exe.display()),
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 停止桥接进程:kill 快速返回,wait 移到后台线程;所有 pending 请求置为失败
|
||||||
|
pub fn stop_bridge(&self) {
|
||||||
|
let entry = self.bridge.lock().ok().and_then(|mut b| b.take());
|
||||||
|
if let Some(mut entry) = entry {
|
||||||
|
let _ = entry.child.kill();
|
||||||
|
// drop stdin/stdout 关闭管道端,reader 线程读到 EOF 退出
|
||||||
|
drop(entry.stdin);
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
let _ = entry.child.wait();
|
||||||
|
});
|
||||||
|
crate::logger::log_info("music-bridge", "桥接进程已停止");
|
||||||
|
}
|
||||||
|
// 通知前端:活动中的下载任务应标记为中断
|
||||||
|
if let Some(app) = self.app_handle() {
|
||||||
|
let _ = app.emit(
|
||||||
|
crate::constants::events::MUSIC_DOWNLOAD_EVENT,
|
||||||
|
serde_json::json!({ "event": "download", "type": "bridge-stopped" }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// 唤醒所有等待中的请求(以 Null 表示已中止)
|
||||||
|
if let Ok(mut map) = self.pending.lock() {
|
||||||
|
for (_, tx) in map.drain() {
|
||||||
|
let _ = tx.send(serde_json::Value::Null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 发送一条请求并等待响应(默认 5s 超时)。传输层错误时自动重启重试一次。
|
||||||
|
pub async fn request(
|
||||||
|
&self,
|
||||||
|
method: &str,
|
||||||
|
params: serde_json::Value,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
self.request_with_timeout(method, params, std::time::Duration::from_secs(5))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 发送一条请求并等待响应(自定义超时,供 search 等长耗时操作使用)。
|
||||||
|
/// 仅传输层错误(进程退出/管道损坏)会重启桥接并重试一次;
|
||||||
|
/// 应用层错误(桥接返回 ok:false)与超时不重启——重启会误杀正在下载的任务。
|
||||||
|
pub async fn request_with_timeout(
|
||||||
|
&self,
|
||||||
|
method: &str,
|
||||||
|
params: serde_json::Value,
|
||||||
|
timeout: std::time::Duration,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
self.ensure_bridge()?;
|
||||||
|
match self.request_inner(method, params.clone(), timeout).await {
|
||||||
|
Ok(v) => Ok(v),
|
||||||
|
Err(BridgeError::Transport(_)) => {
|
||||||
|
// 一次重启机会(进程可能已退出/管道损坏)
|
||||||
|
self.stop_bridge();
|
||||||
|
self.ensure_bridge()?;
|
||||||
|
self.request_inner(method, params, timeout)
|
||||||
|
.await
|
||||||
|
.map_err(BridgeError::into_message)
|
||||||
|
}
|
||||||
|
Err(e) => Err(e.into_message()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn request_inner(
|
||||||
|
&self,
|
||||||
|
method: &str,
|
||||||
|
params: serde_json::Value,
|
||||||
|
timeout: std::time::Duration,
|
||||||
|
) -> Result<serde_json::Value, BridgeError> {
|
||||||
|
let id = self.next_id.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||||
|
let (tx, rx) = tokio::sync::oneshot::channel::<serde_json::Value>();
|
||||||
|
self.pending
|
||||||
|
.lock()
|
||||||
|
.map_err(|e| BridgeError::Transport(e.to_string()))?
|
||||||
|
.insert(id, tx);
|
||||||
|
|
||||||
|
// 写入 stdin(同步函数,MutexGuard 在返回时释放,避免跨 await 持有非 Send 值)
|
||||||
|
self.write_request(id, method, ¶ms)
|
||||||
|
.map_err(BridgeError::Transport)?;
|
||||||
|
|
||||||
|
let v = tokio::time::timeout(timeout, rx)
|
||||||
|
.await
|
||||||
|
.map_err(|_| BridgeError::Timeout("桥接响应超时".to_string()))?
|
||||||
|
.map_err(|_| BridgeError::Transport("桥接响应通道已关闭".to_string()))?;
|
||||||
|
|
||||||
|
// 停止桥接时发送 Null 表示中止
|
||||||
|
if v.is_null() {
|
||||||
|
return Err(BridgeError::Transport("桥接进程已停止".into()));
|
||||||
|
}
|
||||||
|
if v.get("ok").and_then(|o| o.as_bool()).unwrap_or(false) {
|
||||||
|
Ok(v.get("result").cloned().unwrap_or(serde_json::Value::Null))
|
||||||
|
} else {
|
||||||
|
Err(BridgeError::App(
|
||||||
|
v.get("error")
|
||||||
|
.and_then(|e| e.as_str())
|
||||||
|
.unwrap_or("桥接返回未知错误")
|
||||||
|
.to_string(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 写入一条请求到桥接 stdin(同步;进程已退出 / 管道损坏时返回错误)
|
||||||
|
fn write_request(&self, id: u64, method: &str, params: &serde_json::Value) -> Result<(), String> {
|
||||||
|
let line = format!(
|
||||||
|
"{{\"id\":{},\"method\":{},\"params\":{}}}\n",
|
||||||
|
id,
|
||||||
|
serde_json::to_string(method).map_err(|e| e.to_string())?,
|
||||||
|
params
|
||||||
|
);
|
||||||
|
let mut guard = self.bridge.lock().map_err(|e| e.to_string())?;
|
||||||
|
let Some(entry) = guard.as_mut() else {
|
||||||
|
return Err("桥接进程未启动".into());
|
||||||
|
};
|
||||||
|
// 进程已退出 → 立即失败,交给外层重启
|
||||||
|
if entry.child.try_wait().map_err(|e| e.to_string())?.is_some() {
|
||||||
|
return Err("桥接进程已退出".into());
|
||||||
|
}
|
||||||
|
entry
|
||||||
|
.stdin
|
||||||
|
.write_all(line.as_bytes())
|
||||||
|
.map_err(|e| format!("写入桥接 stdin 失败: {}", e))?;
|
||||||
|
entry.stdin.flush().map_err(|e| format!("刷新桥接 stdin 失败: {}", e))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// ping 桥接进程(P0 环境层连通性验证)
|
||||||
|
pub async fn ping(&self) -> Result<serde_json::Value, String> {
|
||||||
|
let v = self.request("ping", serde_json::Value::Null).await?;
|
||||||
|
crate::logger::log_info("music-bridge", &format!("ping 成功: {}", v));
|
||||||
|
Ok(v)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,550 @@
|
|||||||
|
//! 音乐模块 Tauri 命令层。
|
||||||
|
|
||||||
|
use serde_json::json;
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
use tauri::{AppHandle, State};
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
normalize_base_url, resolve_base_url, extract_fn_id, FeiniuConnection, MusicEnvStatus,
|
||||||
|
MusicManager, MusicSettings,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// 查询环境状态(Python / musicdl / FFmpeg / 桥接进程),设置页「环境检查」面板调用。
|
||||||
|
/// 异步命令:子进程探测在阻塞线程池执行,避免冻结主线程/UI。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn music_env_status(state: State<'_, MusicManager>) -> Result<MusicEnvStatus, String> {
|
||||||
|
state.env_status().await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 安装便携 Python + musicdl(幂等),全程推送 music-runtime-install-progress 事件
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn music_install_runtime(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
app: AppHandle,
|
||||||
|
) -> Result<MusicEnvStatus, String> {
|
||||||
|
state.install_runtime(&app).await?;
|
||||||
|
Ok(state.env_status().await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 取消便携运行时安装/下载
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub fn music_cancel_runtime_install(state: State<'_, MusicManager>) -> Result<(), String> {
|
||||||
|
state.cancel();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// ping 桥接进程(未启动则自动拉起),返回 {"version","python"};
|
||||||
|
/// 返回 Value 且未标注 specta:前端直接按 JSON 使用
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn music_ping(state: State<'_, MusicManager>) -> Result<serde_json::Value, String> {
|
||||||
|
state.ping().await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 停止桥接进程
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub fn music_stop_bridge(state: State<'_, MusicManager>) -> Result<(), String> {
|
||||||
|
state.stop_bridge();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 列出 musicdl 已注册的全部搜索源(客户端名);返回 Value,未标注 specta
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn music_get_sources(state: State<'_, MusicManager>) -> Result<serde_json::Value, String> {
|
||||||
|
state.request("get_sources", serde_json::Value::Null).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 多源搜索(最长 90s)。sources 为空时桥接使用默认 3 个大陆源;返回 Value,未标注 specta
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn music_search(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
keyword: String,
|
||||||
|
sources: Option<Vec<String>>,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
let params = serde_json::json!({ "keyword": keyword, "sources": sources.unwrap_or_default() });
|
||||||
|
state
|
||||||
|
.request_with_timeout("search", params, std::time::Duration::from_secs(90))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 解析歌单链接(网易云/QQ 等),返回歌曲列表;返回 Value,未标注 specta
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn music_parse_playlist(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
url: String,
|
||||||
|
sources: Option<Vec<String>>,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
let params = serde_json::json!({ "url": url, "sources": sources.unwrap_or_default() });
|
||||||
|
state
|
||||||
|
.request_with_timeout("parse_playlist", params, std::time::Duration::from_secs(90))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 读取音乐模块设置
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub fn music_get_settings(state: State<'_, MusicManager>) -> MusicSettings {
|
||||||
|
state.load_settings()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 保存音乐模块设置(立即生效)
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub fn music_save_settings(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
settings: MusicSettings,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
state.save_settings(&settings)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 解析歌曲真实下载链接(懒解析:搜索只取元数据,试听/下载前调用)。
|
||||||
|
/// song(单曲)或 songs(批量)二选一;返回 Value,未标注 specta。
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn music_resolve(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
song: Option<serde_json::Value>,
|
||||||
|
songs: Option<Vec<serde_json::Value>>,
|
||||||
|
quality: Option<String>,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
let mut list: Vec<serde_json::Value> = songs.unwrap_or_default();
|
||||||
|
if let Some(s) = song {
|
||||||
|
list.insert(0, s);
|
||||||
|
}
|
||||||
|
if list.is_empty() {
|
||||||
|
return Err("未提供歌曲".into());
|
||||||
|
}
|
||||||
|
let params = serde_json::json!({ "songs": list, "quality": quality.unwrap_or_default() });
|
||||||
|
state
|
||||||
|
.request_with_timeout("resolve", params, std::time::Duration::from_secs(180))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 启动下载任务(桥接后台工作池执行,立即返回 taskId;进度经 music-download-event 推送)。
|
||||||
|
/// songs 为搜索结果的歌曲 dict(桥接端用 SongInfo.fromdict 重建)。
|
||||||
|
/// 返回 Value,未标注 specta。
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn music_download(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
task_id: String,
|
||||||
|
songs: Vec<serde_json::Value>,
|
||||||
|
savedir: String,
|
||||||
|
lyric: Option<bool>,
|
||||||
|
cover: Option<bool>,
|
||||||
|
proxy_url: Option<String>,
|
||||||
|
max_concurrent: Option<u32>,
|
||||||
|
quality: Option<String>,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
if songs.is_empty() {
|
||||||
|
return Err("未选择任何歌曲".into());
|
||||||
|
}
|
||||||
|
let params = serde_json::json!({
|
||||||
|
"taskId": task_id,
|
||||||
|
"songs": songs,
|
||||||
|
"savedir": savedir,
|
||||||
|
"lyric": lyric.unwrap_or(true),
|
||||||
|
"cover": cover.unwrap_or(true),
|
||||||
|
"proxy": proxy_url.unwrap_or_default(),
|
||||||
|
"maxConcurrent": max_concurrent.unwrap_or(1).clamp(1, 16),
|
||||||
|
"quality": quality.unwrap_or_default(),
|
||||||
|
});
|
||||||
|
state
|
||||||
|
.request_with_timeout("download", params, std::time::Duration::from_secs(15))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 取消下载任务(队列级:正在下载的歌曲会完成,其余标记取消)
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn music_download_cancel(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
task_id: String,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
state
|
||||||
|
.request("cancel", serde_json::json!({ "taskId": task_id }))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ 飞牛音乐(NAS)客户端(多连接) ============
|
||||||
|
// 全部命令返回 serde_json::Value、不加 specta:前端用裸 invoke,映射在 feiniuStore。
|
||||||
|
|
||||||
|
/// 连接列表 + 激活 id。返回 `{ activeId, list: [{id,name,kind,baseUrl,username,loggedIn,accessCode,insecure}] }`。
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn feiniu_list_connections(state: State<'_, MusicManager>) -> Result<serde_json::Value, String> {
|
||||||
|
let s = state.load_settings();
|
||||||
|
let list: Vec<_> = s
|
||||||
|
.feiniu_connections
|
||||||
|
.iter()
|
||||||
|
.map(|c| {
|
||||||
|
json!({
|
||||||
|
"id": c.id,
|
||||||
|
"name": c.name,
|
||||||
|
"kind": c.kind,
|
||||||
|
"baseUrl": c.base_url,
|
||||||
|
"username": c.username,
|
||||||
|
"loggedIn": !c.token.is_empty(),
|
||||||
|
"accessCode": c.access_code,
|
||||||
|
"insecure": c.insecure,
|
||||||
|
"fnId": c.fn_id,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
Ok(json!({ "activeId": s.feiniu_active_id, "list": list }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 新增/更新一条连接(不触碰已登录的 token;改地址后需重新登录)。
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn feiniu_save_connection(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
connection: FeiniuConnection,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
let mut settings = state.load_settings();
|
||||||
|
let mut conn = connection;
|
||||||
|
conn.base_url = normalize_base_url(&conn.base_url);
|
||||||
|
if conn.id.is_empty() {
|
||||||
|
conn.id = new_conn_id();
|
||||||
|
}
|
||||||
|
if let Some(existing) = settings.feiniu_connections.iter_mut().find(|c| c.id == conn.id) {
|
||||||
|
conn.token = existing.token.clone(); // 保留既有 token
|
||||||
|
*existing = conn;
|
||||||
|
} else {
|
||||||
|
settings.feiniu_connections.push(conn);
|
||||||
|
}
|
||||||
|
state.save_settings(&settings)?;
|
||||||
|
Ok(json!({ "ok": true }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 删除一条连接;若删的是激活连接,自动切换激活到第一条。
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn feiniu_delete_connection(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
id: String,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
let mut settings = state.load_settings();
|
||||||
|
settings.feiniu_connections.retain(|c| c.id != id);
|
||||||
|
if settings.feiniu_active_id == id {
|
||||||
|
settings.feiniu_active_id = settings
|
||||||
|
.feiniu_connections
|
||||||
|
.first()
|
||||||
|
.map(|c| c.id.clone())
|
||||||
|
.unwrap_or_default();
|
||||||
|
}
|
||||||
|
state.save_settings(&settings)?;
|
||||||
|
state.feiniu.sync_with_settings(&settings);
|
||||||
|
Ok(json!({ "ok": true }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 设某连接为激活连接。
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn feiniu_activate_connection(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
id: String,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
let mut settings = state.load_settings();
|
||||||
|
if !settings.feiniu_connections.iter().any(|c| c.id == id) {
|
||||||
|
return Err("连接不存在".into());
|
||||||
|
}
|
||||||
|
settings.feiniu_active_id = id;
|
||||||
|
state.save_settings(&settings)?;
|
||||||
|
state.feiniu.sync_with_settings(&settings);
|
||||||
|
Ok(json!({ "ok": true }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 登录激活/某连接:校验通过后写回该连接的 token/device_id 并启动本地流代理。
|
||||||
|
/// fnconnect 连接会先用 fnId 解析出可达 base_url 再登录。
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn feiniu_login(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
connection_id: String,
|
||||||
|
username: String,
|
||||||
|
password: String,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
let mut settings = state.load_settings();
|
||||||
|
let mut conn = settings
|
||||||
|
.feiniu_connections
|
||||||
|
.iter()
|
||||||
|
.find(|c| c.id == connection_id)
|
||||||
|
.cloned()
|
||||||
|
.ok_or_else(|| "连接不存在,请先保存连接".to_string())?;
|
||||||
|
// fnconnect:用 fnId 解析 base_url
|
||||||
|
if conn.kind == "fnconnect" {
|
||||||
|
let fid = extract_fn_id(&conn.fn_id).ok_or_else(|| "FnConnect 连接缺少有效 fnId".to_string())?;
|
||||||
|
let (url, _relay) = resolve_base_url(&fid).await?;
|
||||||
|
conn.base_url = url;
|
||||||
|
if let Some(c) = settings.feiniu_connections.iter_mut().find(|c| c.id == connection_id) {
|
||||||
|
c.base_url = conn.base_url.clone();
|
||||||
|
}
|
||||||
|
state.save_settings(&settings)?;
|
||||||
|
}
|
||||||
|
// 用该连接配置装备运行期
|
||||||
|
let mut tmp = settings.clone();
|
||||||
|
tmp.feiniu_active_id = conn.id.clone();
|
||||||
|
state.feiniu.sync_with_settings(&tmp);
|
||||||
|
|
||||||
|
let (token, device_id) = state.feiniu.login(&conn.base_url, &username, &password).await?;
|
||||||
|
|
||||||
|
if let Some(existing) = settings.feiniu_connections.iter_mut().find(|c| c.id == connection_id) {
|
||||||
|
existing.token = token.clone();
|
||||||
|
existing.device_id = device_id;
|
||||||
|
existing.username = username;
|
||||||
|
}
|
||||||
|
settings.feiniu_active_id = connection_id.clone();
|
||||||
|
state.save_settings(&settings)?;
|
||||||
|
state.feiniu.sync_with_settings(&settings);
|
||||||
|
let prefix = state.feiniu.media_prefix().await?;
|
||||||
|
Ok(json!({ "ok": true, "userToken": token, "mediaPrefix": prefix }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 登出某连接(清 token,保留地址/账号),代理 Cookie 同步失效。
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn feiniu_logout(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
connection_id: String,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
let mut settings = state.load_settings();
|
||||||
|
if let Some(c) = settings.feiniu_connections.iter_mut().find(|c| c.id == connection_id) {
|
||||||
|
c.token.clear();
|
||||||
|
}
|
||||||
|
state.save_settings(&settings)?;
|
||||||
|
state.feiniu.sync_with_settings(&settings);
|
||||||
|
state.feiniu.logout();
|
||||||
|
Ok(json!({ "ok": true }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 测试某连接是否能登录(不持久化 token),探测后恢复原激活连接的运行期状态。
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn feiniu_test_connection(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
connection_id: String,
|
||||||
|
username: String,
|
||||||
|
password: String,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
let settings = state.load_settings();
|
||||||
|
let conn = settings
|
||||||
|
.feiniu_connections
|
||||||
|
.iter()
|
||||||
|
.find(|c| c.id == connection_id)
|
||||||
|
.cloned()
|
||||||
|
.ok_or_else(|| "连接不存在".to_string())?;
|
||||||
|
let mut tmp = settings.clone();
|
||||||
|
tmp.feiniu_active_id = conn.id.clone();
|
||||||
|
state.feiniu.sync_with_settings(&tmp);
|
||||||
|
let r = state.feiniu.login(&conn.base_url, &username, &password).await;
|
||||||
|
// 探测可能污染运行期:恢复为持久化的激活连接
|
||||||
|
state.feiniu.sync_with_settings(&state.load_settings());
|
||||||
|
match r {
|
||||||
|
Ok(_) => Ok(json!({ "ok": true })),
|
||||||
|
Err(e) => Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 查询当前激活连接配置:{ activeId, baseUrl, username, loggedIn }。
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn feiniu_get_config(state: State<'_, MusicManager>) -> Result<serde_json::Value, String> {
|
||||||
|
let settings = state.load_settings();
|
||||||
|
state.feiniu.sync_with_settings(&settings);
|
||||||
|
let active_id = settings.feiniu_active_id;
|
||||||
|
let mut cfg = state.feiniu.config();
|
||||||
|
cfg["activeId"] = json!(active_id);
|
||||||
|
Ok(cfg)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 分页拉取激活连接曲目列表:{ page, size, keyword? } → NAS 原始 data。
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn feiniu_list_tracks(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
page: Option<u32>,
|
||||||
|
size: Option<u32>,
|
||||||
|
keyword: Option<String>,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
state.feiniu.sync_with_settings(&state.load_settings());
|
||||||
|
state
|
||||||
|
.feiniu
|
||||||
|
.list_tracks(
|
||||||
|
page.unwrap_or(1).max(1),
|
||||||
|
size.unwrap_or(50).clamp(1, 100),
|
||||||
|
keyword.as_deref(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 获取某曲目歌词:{ lyric }(无则空字符串)。
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn feiniu_lyric(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
guid: String,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
state.feiniu.sync_with_settings(&state.load_settings());
|
||||||
|
let text = state.feiniu.lyric(&guid).await?;
|
||||||
|
Ok(json!({ "lyric": text }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 本地媒体地址前缀:{ mediaPrefix }(首次调用惰性启动本地流代理)。
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn feiniu_media_prefix(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
state.feiniu.sync_with_settings(&state.load_settings());
|
||||||
|
let prefix = state.feiniu.media_prefix().await?;
|
||||||
|
Ok(json!({ "mediaPrefix": prefix }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 扫描本地曲库目录中的音频文件:{ items }(目录 = 下载 savedir + 用户自定义 dirs)。
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn feiniu_scan_local(state: State<'_, MusicManager>) -> Result<serde_json::Value, String> {
|
||||||
|
let s = state.load_settings();
|
||||||
|
let mut dirs: Vec<String> = vec![s.savedir.clone()];
|
||||||
|
for d in &s.feiniu_local_dirs {
|
||||||
|
if !dirs.iter().any(|x| x == d) {
|
||||||
|
dirs.push(d.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(state.feiniu.scan_local(&dirs))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 播放缓存状态:{ count, usedBytes, usedMb }。
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn feiniu_cache_status(state: State<'_, MusicManager>) -> Result<serde_json::Value, String> {
|
||||||
|
Ok(state.feiniu.cache_status())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 清空播放缓存。
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn feiniu_cache_clear(state: State<'_, MusicManager>) -> Result<serde_json::Value, String> {
|
||||||
|
state.feiniu.cache_clear();
|
||||||
|
Ok(json!({ "ok": true }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 缓存一首歌(命中则直接返回):{ path } 或 { cached }。
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn feiniu_cache_fetch(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
guid: String,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
state.feiniu.sync_with_settings(&state.load_settings());
|
||||||
|
let max_gb = state.load_settings().feiniu_cache_max_gb;
|
||||||
|
let hit = state.feiniu.cache_fetch(&guid, max_gb).await?;
|
||||||
|
Ok(json!({ "path": hit, "cached": hit.is_some() }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 生成一条新连接的 id(时间戳 + 进程号,避免引 rand)。
|
||||||
|
fn new_conn_id() -> String {
|
||||||
|
let n = SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.map(|d| d.as_nanos())
|
||||||
|
.unwrap_or(0);
|
||||||
|
format!("c{n:x}")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ P6:下载到飞牛 + 曲库增删(fnOS 文件服务) ============
|
||||||
|
|
||||||
|
/// fnOS 登录:为某连接建立 NAS 文件服务会话(WS + RSA/AES)。成功后不持久化凭据。
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn feiniu_fnos_login(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
connection_id: String,
|
||||||
|
username: String,
|
||||||
|
password: String,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
let settings = state.load_settings();
|
||||||
|
let conn = settings
|
||||||
|
.feiniu_connections
|
||||||
|
.iter()
|
||||||
|
.find(|c| c.id == connection_id)
|
||||||
|
.cloned()
|
||||||
|
.ok_or_else(|| "连接不存在".to_string())?;
|
||||||
|
state
|
||||||
|
.feiniu
|
||||||
|
.fnos_login(&connection_id, &conn.base_url, &username, &password)
|
||||||
|
.await?;
|
||||||
|
Ok(json!({ "ok": true }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 登出 fnOS 文件服务会话。
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn feiniu_fnos_logout(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
connection_id: String,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
state.feiniu.fnos_logout(&connection_id);
|
||||||
|
Ok(json!({ "ok": true }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// fnOS 文件服务登录状态:{ loggedIn }(按连接)。
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn feiniu_fnos_status(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
connection_id: String,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
Ok(json!({ "loggedIn": state.feiniu.fnos_logged_in(&connection_id) }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 上传本地文件到 NAS(激活连接的 fnOS 会话)。返回上传文件名。
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn feiniu_fnos_upload(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
local_path: String,
|
||||||
|
nas_path: String,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
let settings = state.load_settings();
|
||||||
|
let conn = settings
|
||||||
|
.feiniu_connections
|
||||||
|
.iter()
|
||||||
|
.find(|c| c.id == settings.feiniu_active_id)
|
||||||
|
.cloned()
|
||||||
|
.ok_or_else(|| "没有激活连接".to_string())?;
|
||||||
|
let name = state
|
||||||
|
.feiniu
|
||||||
|
.fnos_upload(&conn.id, std::path::Path::new(&local_path), &nas_path)
|
||||||
|
.await?;
|
||||||
|
Ok(json!({ "ok": true, "name": name }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 删除 NAS 文件(激活连接的 fnOS 会话)。
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn feiniu_fnos_delete(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
nas_path: String,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
let settings = state.load_settings();
|
||||||
|
let conn = settings
|
||||||
|
.feiniu_connections
|
||||||
|
.iter()
|
||||||
|
.find(|c| c.id == settings.feiniu_active_id)
|
||||||
|
.cloned()
|
||||||
|
.ok_or_else(|| "没有激活连接".to_string())?;
|
||||||
|
state.feiniu.fnos_delete(&conn.id, &nas_path).await?;
|
||||||
|
Ok(json!({ "ok": true }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 列出 NAS 目录(激活连接的 fnOS 会话)。
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn feiniu_fnos_list(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
path: String,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
let settings = state.load_settings();
|
||||||
|
let conn = settings
|
||||||
|
.feiniu_connections
|
||||||
|
.iter()
|
||||||
|
.find(|c| c.id == settings.feiniu_active_id)
|
||||||
|
.cloned()
|
||||||
|
.ok_or_else(|| "没有激活连接".to_string())?;
|
||||||
|
let v = state.feiniu.fnos_list(&conn.id, &path).await?;
|
||||||
|
Ok(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ P7:FnConnect 远程连接解析 ============
|
||||||
|
|
||||||
|
/// 解析 fnId → 可达 base_url(探测后返回)。命令层在 fnconnect 连接登录前调用。
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn feiniu_fnconnect_resolve(
|
||||||
|
state: State<'_, MusicManager>,
|
||||||
|
fn_id: String,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
let _ = &state;
|
||||||
|
let (url, relay) = resolve_base_url(&fn_id).await?;
|
||||||
|
Ok(json!({ "baseUrl": url, "relay": relay }))
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
//! 飞牛音乐播放缓存(容量限制 + LRU 逐出)。
|
||||||
|
//!
|
||||||
|
//! 缓存目录:`{app_data}/music/cache`,文件 `guid.<ext>`(ext 缺省记 `bin`)。
|
||||||
|
//! 元数据:`index.json` → `{ "guid": { "size", "lastUsed", "file" } }`。
|
||||||
|
//! 超上限按 lastUsed 升序逐出,直到总占用低于上限。
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::fs;
|
||||||
|
use std::io::Write;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
/// 单条缓存元数据
|
||||||
|
#[derive(Serialize, Deserialize, Clone)]
|
||||||
|
pub struct CacheEntry {
|
||||||
|
pub size: u64,
|
||||||
|
pub last_used: u64,
|
||||||
|
pub file: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct CacheManager {
|
||||||
|
root: PathBuf,
|
||||||
|
index_path: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CacheManager {
|
||||||
|
pub fn new(app_data_dir: &Path) -> Self {
|
||||||
|
let root = app_data_dir.join("music").join("cache");
|
||||||
|
fs::create_dir_all(&root).ok();
|
||||||
|
let index_path = root.join("index.json");
|
||||||
|
Self { root, index_path }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_index(&self) -> HashMap<String, CacheEntry> {
|
||||||
|
fs::read_to_string(&self.index_path)
|
||||||
|
.ok()
|
||||||
|
.and_then(|s| serde_json::from_str(&s).ok())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save_index(&self, idx: &HashMap<String, CacheEntry>) {
|
||||||
|
if let Ok(s) = serde_json::to_string(idx) {
|
||||||
|
fs::write(&self.index_path, s).ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn now_ms(&self) -> u64 {
|
||||||
|
SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.map(|d| d.as_millis() as u64)
|
||||||
|
.unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 命中缓存:更新 lastUsed 并返回文件路径。
|
||||||
|
pub fn hit(&self, guid: &str) -> Option<String> {
|
||||||
|
let mut idx = self.load_index();
|
||||||
|
if let Some(e) = idx.get_mut(guid) {
|
||||||
|
let path = self.root.join(&e.file);
|
||||||
|
if path.exists() {
|
||||||
|
e.last_used = self.now_ms();
|
||||||
|
self.save_index(&idx);
|
||||||
|
return Some(path.to_string_lossy().to_string());
|
||||||
|
}
|
||||||
|
idx.remove(guid);
|
||||||
|
self.save_index(&idx);
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 写入缓存(流式 chunk);按上限(GB)逐出。返回写入总字节数。
|
||||||
|
pub async fn put<E: std::fmt::Display>(
|
||||||
|
&self,
|
||||||
|
guid: &str,
|
||||||
|
ext: &str,
|
||||||
|
max_gb: u32,
|
||||||
|
mut stream: impl futures_util::Stream<Item = Result<bytes::Bytes, E>> + Unpin,
|
||||||
|
) -> Result<u64, String> {
|
||||||
|
let safe_guid = sanitize(guid);
|
||||||
|
let ext = if ext.is_empty() { "bin" } else { ext };
|
||||||
|
let file = format!("{safe_guid}.{ext}");
|
||||||
|
let path = self.root.join(&file);
|
||||||
|
let mut total: u64 = 0;
|
||||||
|
let mut f = fs::File::create(&path).map_err(|e| format!("创建缓存文件失败: {e}"))?;
|
||||||
|
while let Some(chunk) = futures_util::StreamExt::next(&mut stream).await {
|
||||||
|
let chunk = chunk.map_err(|e| format!("读取流失败: {e}"))?;
|
||||||
|
total += chunk.len() as u64;
|
||||||
|
f.write_all(chunk.as_ref()).map_err(|e| format!("写入缓存失败: {e}"))?;
|
||||||
|
}
|
||||||
|
f.flush().ok();
|
||||||
|
|
||||||
|
let mut idx = self.load_index();
|
||||||
|
idx.insert(
|
||||||
|
guid.to_string(),
|
||||||
|
CacheEntry {
|
||||||
|
size: total,
|
||||||
|
last_used: self.now_ms(),
|
||||||
|
file,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
self.save_index(&idx);
|
||||||
|
self.evict(max_gb);
|
||||||
|
Ok(total)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 按上限(GB)逐出。max_gb==0 视为全部清空。
|
||||||
|
fn evict(&self, max_gb: u32) {
|
||||||
|
if max_gb == 0 {
|
||||||
|
self.clear();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let max_bytes = max_gb as u64 * 1024 * 1024 * 1024;
|
||||||
|
let mut idx = self.load_index();
|
||||||
|
let mut total: u64 = idx.values().map(|e| e.size).sum();
|
||||||
|
let mut order: Vec<(String, u64)> = idx.iter().map(|(g, e)| (g.clone(), e.last_used)).collect();
|
||||||
|
order.sort_by_key(|(_, t)| *t);
|
||||||
|
for (guid, _) in order {
|
||||||
|
if total <= max_bytes {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if let Some(e) = idx.remove(&guid) {
|
||||||
|
let _ = fs::remove_file(self.root.join(&e.file));
|
||||||
|
total = total.saturating_sub(e.size);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.save_index(&idx);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 当前占用与条目数。
|
||||||
|
pub fn status(&self) -> serde_json::Value {
|
||||||
|
let idx = self.load_index();
|
||||||
|
let total: u64 = idx.values().map(|e| e.size).sum();
|
||||||
|
json!({
|
||||||
|
"count": idx.len(),
|
||||||
|
"usedBytes": total,
|
||||||
|
"usedMb": (total as f64 / 1024.0 / 1024.0 * 10.0).round() / 10.0,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear(&self) {
|
||||||
|
let idx = self.load_index();
|
||||||
|
for e in idx.values() {
|
||||||
|
let _ = fs::remove_file(self.root.join(&e.file));
|
||||||
|
}
|
||||||
|
fs::remove_file(&self.index_path).ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sanitize(s: &str) -> String {
|
||||||
|
s.chars()
|
||||||
|
.map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' })
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
//! 飞牛音乐原生接口纯函数工具(登录签名、地址规范化、设备 ID)。
|
||||||
|
//! 接口路径/认证方式对照 FeiNiuMusic(Flutter) `api_client.dart` 的第三方实现。
|
||||||
|
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
/// 规范化服务器地址:去首尾空白、去尾部各层斜杠、去误粘贴的 `/music/api/v1` 后缀。
|
||||||
|
pub fn normalize_base_url(input: &str) -> String {
|
||||||
|
let mut u = input.trim().trim_end_matches('/').to_string();
|
||||||
|
let lower = u.to_lowercase();
|
||||||
|
if lower.ends_with("/music/api/v1") {
|
||||||
|
u = u[..u.len() - "/music/api/v1".len()].to_string();
|
||||||
|
}
|
||||||
|
u.trim_end_matches('/').to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// SHA-256 十六进制(登录时密码签名,对齐原生客户端 `sha256Hex(password)`)。
|
||||||
|
pub fn sha256_hex(input: &str) -> String {
|
||||||
|
let mut hasher = Sha256::new();
|
||||||
|
hasher.update(input.as_bytes());
|
||||||
|
format!("{:x}", hasher.finalize())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 32 位 hex 设备 ID(首次生成后落 settings 复用;不依赖 rand,用时间戳+进程号哈希)。
|
||||||
|
pub fn generate_device_id() -> String {
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
let nanos = SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.map(|d| d.as_nanos())
|
||||||
|
.unwrap_or(0);
|
||||||
|
sha256_hex(&format!("{}-{}", nanos, std::process::id()))[..32].to_string()
|
||||||
|
}
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
//! FnConnect 远程连接解析(参考 feiniu-car-music `fn-api.js`)。
|
||||||
|
//!
|
||||||
|
//! fnId → 网关 `https://5ddd.com/api/v1/fn/con`(authx md5 签名)→ 内网/公网/中继候选 →
|
||||||
|
//! 探测可达性 → 得到可用的 base_url(含 mode=relay 的中继地址)。
|
||||||
|
|
||||||
|
use md5::Md5;
|
||||||
|
use rand::RngCore;
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
/// 网关地址与签名常量(对齐 feiniu-car-music)。
|
||||||
|
const FN_CONNECT_URL: &str = "https://5ddd.com/api/v1/fn/con";
|
||||||
|
const FN_AUTHX_PREFIX: &str = "NDzZTVxnRKP8Z0jXg1VAMonaG8akvh";
|
||||||
|
const FN_API_KEY: &str = "zIGtkc3dqZnJpd29qZXJqa2w7c";
|
||||||
|
|
||||||
|
fn md5_hex(input: &str) -> String {
|
||||||
|
let mut h = Md5::new();
|
||||||
|
h.update(input.as_bytes());
|
||||||
|
format!("{:x}", h.finalize())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sha256_hex(input: &str) -> String {
|
||||||
|
let mut h = Sha256::new();
|
||||||
|
h.update(input.as_bytes());
|
||||||
|
format!("{:x}", h.finalize())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 从输入识别 fnId:`fnos.net/<id>`、`<id>.5ddd.com`、或裸 fnId。
|
||||||
|
pub fn extract_fn_id(input: &str) -> Option<String> {
|
||||||
|
let s = input.trim();
|
||||||
|
if s.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if let Some(id) = s.split_once("fnos.net/").map(|(_, r)| r.split('/').next().unwrap_or("")) {
|
||||||
|
if !id.is_empty() {
|
||||||
|
return Some(id.trim().to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(rest) = s.rsplit_once("/") {
|
||||||
|
let last = rest.1;
|
||||||
|
if last.ends_with(".5ddd.com") {
|
||||||
|
return Some(last.trim_end_matches(".5ddd.com").to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if s.ends_with(".5ddd.com") {
|
||||||
|
return Some(s.trim_end_matches(".5ddd.com").to_string());
|
||||||
|
}
|
||||||
|
// 裸 fnId
|
||||||
|
if s.len() >= 3 && s.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_') && !s.starts_with("http") {
|
||||||
|
return Some(s.to_string());
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 计算网关 authx 签名。
|
||||||
|
fn fn_authx(method: &str, url: &str, data: &Value) -> String {
|
||||||
|
let body = if method.eq_ignore_ascii_case("get") {
|
||||||
|
String::new()
|
||||||
|
} else {
|
||||||
|
serde_json::to_string(data).unwrap_or_default()
|
||||||
|
};
|
||||||
|
let mut nonce = String::new();
|
||||||
|
let mut rng = rand::thread_rng();
|
||||||
|
for _ in 0..6 {
|
||||||
|
nonce.push(char::from(b'0' + (rng.next_u32() % 10) as u8));
|
||||||
|
}
|
||||||
|
let timestamp = std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.map(|d| d.as_millis().to_string())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let raw = format!(
|
||||||
|
"{FN_AUTHX_PREFIX}_{url}_{nonce}_{timestamp}_{}__{FN_API_KEY}",
|
||||||
|
md5_hex(&body)
|
||||||
|
);
|
||||||
|
format!("nonce={nonce}×tamp={timestamp}&sign={}", md5_hex(&raw))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 从网关查询 fnId 的连接参数。
|
||||||
|
pub async fn query_fn_connect(fn_id: &str) -> Result<Value, String> {
|
||||||
|
let client = reqwest::Client::builder()
|
||||||
|
.timeout(std::time::Duration::from_secs(10))
|
||||||
|
.build()
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let body = json!({ "fnId": fn_id });
|
||||||
|
let resp = client
|
||||||
|
.post(FN_CONNECT_URL)
|
||||||
|
.header("Content-Type", "application/json")
|
||||||
|
.header("authx", fn_authx("post", "/api/v1/fn/con", &body))
|
||||||
|
.json(&body)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("FnConnect 网关不可达: {e}"))?;
|
||||||
|
let b: Value = resp.json().await.map_err(|e| e.to_string())?;
|
||||||
|
if b["code"].as_i64().unwrap_or(-1) != 0 {
|
||||||
|
return Err(b["msg"].as_str().unwrap_or("FnConnect 网关返回错误").to_string());
|
||||||
|
}
|
||||||
|
Ok(b["data"].clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 构建候选 base_url 列表。返回 (url, is_relay)。
|
||||||
|
pub fn build_candidates(data: &Value) -> Vec<(String, bool)> {
|
||||||
|
let mut out: Vec<(String, bool)> = Vec::new();
|
||||||
|
let port = &data["port"];
|
||||||
|
let http = port["httpPort"].as_u64().unwrap_or(5666);
|
||||||
|
let https = port["httpsPort"].as_u64().unwrap_or(5667);
|
||||||
|
let empty = vec![];
|
||||||
|
for ip in data["ipv4"].as_array().unwrap_or(&empty).iter().filter_map(|v| v.as_str()) {
|
||||||
|
out.push((format!("http://{ip}:{http}"), false));
|
||||||
|
out.push((format!("https://{ip}:{https}"), false));
|
||||||
|
}
|
||||||
|
for ip in data["publicIpv4"].as_array().unwrap_or(&empty).iter().filter_map(|v| v.as_str()) {
|
||||||
|
out.push((format!("http://{ip}:{http}"), false));
|
||||||
|
out.push((format!("https://{ip}:{https}"), false));
|
||||||
|
}
|
||||||
|
for ip in data["publicIpv6"].as_array().unwrap_or(&empty).iter().filter_map(|v| v.as_str()) {
|
||||||
|
out.push((format!("http://[{ip}]:{http}"), false));
|
||||||
|
out.push((format!("https://[{ip}]:{https}"), false));
|
||||||
|
}
|
||||||
|
let relays = data["fn"].as_array().unwrap_or(&empty);
|
||||||
|
let relay_addrs: Vec<String> = if relays.is_empty() {
|
||||||
|
vec!["5ddd.com".to_string()]
|
||||||
|
} else {
|
||||||
|
relays
|
||||||
|
.iter()
|
||||||
|
.filter_map(|v| v.as_str().map(|s| s.to_string()))
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
for addr in relay_addrs {
|
||||||
|
let domain = addr.split(':').next().unwrap_or(&addr).to_string();
|
||||||
|
out.push((format!("https://{domain}"), true));
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 探测某个 base_url 是否可用。
|
||||||
|
async fn probe(url: &str) -> bool {
|
||||||
|
let client = reqwest::Client::builder()
|
||||||
|
.timeout(std::time::Duration::from_secs(6))
|
||||||
|
.build()
|
||||||
|
.unwrap_or_else(|_| reqwest::Client::new());
|
||||||
|
let full = format!("{}/music/api/v1/track/list?page=1&size=1", url.trim_end_matches('/'));
|
||||||
|
match client.get(&full).send().await {
|
||||||
|
Ok(resp) => resp.status().as_u16() < 500,
|
||||||
|
Err(_) => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 解析 fnId → 第一个可达的 base_url;返回 (base_url, is_relay)。
|
||||||
|
pub async fn resolve_base_url(fn_id: &str) -> Result<(String, bool), String> {
|
||||||
|
let data = query_fn_connect(fn_id).await?;
|
||||||
|
let candidates = build_candidates(&data);
|
||||||
|
if candidates.is_empty() {
|
||||||
|
return Err("FnConnect 未返回可用地址".into());
|
||||||
|
}
|
||||||
|
for (url, relay) in &candidates {
|
||||||
|
if probe(url).await {
|
||||||
|
return Ok((url.clone(), *relay));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(format!("FnConnect 候选均不可达({} 个)", candidates.len()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// sha256 hex(登录用)。
|
||||||
|
pub fn sha256_hex_pub(input: &str) -> String {
|
||||||
|
sha256_hex(input)
|
||||||
|
}
|
||||||
@@ -0,0 +1,410 @@
|
|||||||
|
//! fnOS 文件服务客户端(WebSocket 协议 + HTTP 上传)。
|
||||||
|
//!
|
||||||
|
//! 协议参照 `FNOSP/fnnas-api`:
|
||||||
|
//! 1. 连接 `ws://{host}:{port}/websocket?type=main`
|
||||||
|
//! 2. `util.crypto.getRSAPub` 取 RSA 公钥与 si
|
||||||
|
//! 3. `user.login`:随机 AES key/iv,AES-CBC 加密登录体 + RSA 加密 key,发 `{"req":"encrypted",...}`
|
||||||
|
//! 4. 之后每个请求 `{base64(HMAC-SHA256(json))}{json}` 签名
|
||||||
|
//! 5. 上传:WS `file.checkUpload` → HTTP `POST /upload`(Trim-Token/Trim-Path/Trim-Sign)
|
||||||
|
//! 6. 删除:WS `file.rm`
|
||||||
|
//!
|
||||||
|
//! 仅支持 http://(ws://)直连;https/frp 的文件上传留待后续。
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit};
|
||||||
|
use aes::Aes256;
|
||||||
|
use base64::Engine;
|
||||||
|
use futures_util::{SinkExt, StreamExt};
|
||||||
|
use hmac::{Hmac, Mac};
|
||||||
|
use rand::RngCore;
|
||||||
|
use rsa::pkcs8::DecodePublicKey;
|
||||||
|
use rsa::{Pkcs1v15Encrypt, RsaPublicKey};
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
use sha2::Sha256;
|
||||||
|
use tokio_tungstenite::tungstenite::Message;
|
||||||
|
use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream};
|
||||||
|
|
||||||
|
type HmacSha256 = Hmac<Sha256>;
|
||||||
|
type WsStream = WebSocketStream<MaybeTlsStream<tokio::net::TcpStream>>;
|
||||||
|
|
||||||
|
const KEY_CHARS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||||
|
|
||||||
|
fn random_key() -> String {
|
||||||
|
let mut rng = rand::thread_rng();
|
||||||
|
(0..32)
|
||||||
|
.map(|_| {
|
||||||
|
let i = rng.next_u64() as usize % KEY_CHARS.len();
|
||||||
|
KEY_CHARS[i] as char
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn random_iv() -> [u8; 16] {
|
||||||
|
let mut iv = [0u8; 16];
|
||||||
|
rand::thread_rng().fill_bytes(&mut iv);
|
||||||
|
iv
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 手动 AES-256-CBC 加密(避免 cbc crate trait 兼容问题),PKCS7 填充,返回 base64。
|
||||||
|
fn aes_cbc_encrypt_b64(data: &[u8], key: &[u8; 32], iv: &[u8; 16]) -> String {
|
||||||
|
let cipher = Aes256::new(key.into());
|
||||||
|
let mut padded = data.to_vec();
|
||||||
|
let pad_len = 16 - (padded.len() % 16);
|
||||||
|
padded.extend(std::iter::repeat(pad_len as u8).take(pad_len));
|
||||||
|
let mut out = Vec::with_capacity(padded.len());
|
||||||
|
let mut prev = *iv;
|
||||||
|
for chunk in padded.chunks(16) {
|
||||||
|
let mut block = [0u8; 16];
|
||||||
|
for i in 0..16 {
|
||||||
|
block[i] = chunk[i] ^ prev[i];
|
||||||
|
}
|
||||||
|
cipher.encrypt_block((&mut block).into());
|
||||||
|
out.extend_from_slice(&block);
|
||||||
|
prev = block;
|
||||||
|
}
|
||||||
|
base64::engine::general_purpose::STANDARD.encode(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// AES-256-CBC 解密 → 返回 base64(明文)(对齐 fnnas-api 的 aes_decrypt)。
|
||||||
|
fn aes_cbc_decrypt_b64(ciphertext_b64: &str, key: &[u8; 32], iv: &[u8; 16]) -> Result<String, String> {
|
||||||
|
let ct = base64::engine::general_purpose::STANDARD
|
||||||
|
.decode(ciphertext_b64)
|
||||||
|
.map_err(|e| format!("AES 密文解码失败: {e}"))?;
|
||||||
|
let cipher = Aes256::new(key.into());
|
||||||
|
let mut prev = *iv;
|
||||||
|
let mut plain = Vec::with_capacity(ct.len());
|
||||||
|
for chunk in ct.chunks(16) {
|
||||||
|
let mut block = [0u8; 16];
|
||||||
|
block.copy_from_slice(chunk);
|
||||||
|
let enc = block;
|
||||||
|
cipher.decrypt_block((&mut block).into());
|
||||||
|
for i in 0..16 {
|
||||||
|
plain.push(block[i] ^ prev[i]);
|
||||||
|
}
|
||||||
|
prev = enc;
|
||||||
|
}
|
||||||
|
// 去 PKCS7 填充
|
||||||
|
if let Some(&last) = plain.last() {
|
||||||
|
let n = last as usize;
|
||||||
|
if n > 0 && n <= 16 && plain.len() >= n && plain[plain.len() - n..].iter().all(|&b| b == last) {
|
||||||
|
plain.truncate(plain.len() - n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(base64::engine::general_purpose::STANDARD.encode(plain))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rsa_encrypt_b64(pub_pem: &str, data: &str) -> Result<String, String> {
|
||||||
|
let key = RsaPublicKey::from_public_key_pem(pub_pem)
|
||||||
|
.map_err(|e| format!("解析 RSA 公钥失败: {e}"))?;
|
||||||
|
let mut rng = rand::thread_rng();
|
||||||
|
let ct = key
|
||||||
|
.encrypt(&mut rng, Pkcs1v15Encrypt, data.as_bytes())
|
||||||
|
.map_err(|e| format!("RSA 加密失败: {e}"))?;
|
||||||
|
Ok(base64::engine::general_purpose::STANDARD.encode(ct))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hmac_sha256_b64(key: &[u8], data: &str) -> String {
|
||||||
|
let mut mac = <HmacSha256 as Mac>::new_from_slice(key).expect("hmac key");
|
||||||
|
mac.update(data.as_bytes());
|
||||||
|
base64::engine::general_purpose::STANDARD.encode(mac.finalize().into_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reqid() -> String {
|
||||||
|
let n = SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.map(|d| d.as_millis())
|
||||||
|
.unwrap_or(0);
|
||||||
|
format!("0000000000000000{n:x}")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ws_url(base_url: &str) -> String {
|
||||||
|
let u = base_url.trim_end_matches('/');
|
||||||
|
u.replacen("http://", "ws://", 1) + "/websocket?type=main"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 一次 fnOS 会话(登录后复用;命令层按 connection 存于 Feiniu)。
|
||||||
|
pub struct FnOsSession {
|
||||||
|
pub base_url: String,
|
||||||
|
token: Mutex<String>,
|
||||||
|
sign_key: Mutex<Vec<u8>>,
|
||||||
|
ws: Arc<tokio::sync::Mutex<Option<WsStream>>>,
|
||||||
|
pending: Arc<Mutex<HashMap<String, tokio::sync::oneshot::Sender<Value>>>>,
|
||||||
|
reader: Arc<AtomicBool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FnOsSession {
|
||||||
|
/// 建立会话(新 WS 连接 + 登录)。
|
||||||
|
pub async fn connect(base_url: &str, username: &str, password: &str) -> Result<Self, String> {
|
||||||
|
let url = ws_url(base_url);
|
||||||
|
let (ws, _) = connect_async(&url)
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("连接 fnOS WebSocket 失败: {e}"))?;
|
||||||
|
let session = Self {
|
||||||
|
base_url: base_url.trim_end_matches('/').to_string(),
|
||||||
|
token: Mutex::new(String::new()),
|
||||||
|
sign_key: Mutex::new(Vec::new()),
|
||||||
|
ws: Arc::new(tokio::sync::Mutex::new(Some(ws))),
|
||||||
|
pending: Arc::new(Mutex::new(HashMap::new())),
|
||||||
|
reader: Arc::new(AtomicBool::new(false)),
|
||||||
|
};
|
||||||
|
session.login(username, password).await?;
|
||||||
|
Ok(session)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn token(&self) -> String {
|
||||||
|
self.token.lock().unwrap_or_else(|e| e.into_inner()).clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ensure_reader(&self) {
|
||||||
|
if self.reader.swap(true, Ordering::SeqCst) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let ws = self.ws.clone();
|
||||||
|
let pending = self.pending.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
loop {
|
||||||
|
let msg = {
|
||||||
|
let mut guard = ws.lock().await;
|
||||||
|
let Some(stream) = guard.as_mut() else { break };
|
||||||
|
match stream.next().await {
|
||||||
|
Some(Ok(m)) => m,
|
||||||
|
_ => break,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Message::Text(text) = msg {
|
||||||
|
if let Ok(v) = serde_json::from_str::<Value>(&text) {
|
||||||
|
if let Some(rid) = v["reqid"].as_str() {
|
||||||
|
if let Some(sender) =
|
||||||
|
pending.lock().unwrap_or_else(|e| e.into_inner()).remove(rid)
|
||||||
|
{
|
||||||
|
let _ = sender.send(v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let pendings: Vec<_> = pending
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|e| e.into_inner())
|
||||||
|
.drain()
|
||||||
|
.map(|(_, s)| s)
|
||||||
|
.collect();
|
||||||
|
for s in pendings {
|
||||||
|
let _ = s.send(Value::Null);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 发送签名请求并等待响应。
|
||||||
|
async fn request(&self, req: &str, data: Value) -> Result<Value, String> {
|
||||||
|
self.ensure_reader();
|
||||||
|
let rid = reqid();
|
||||||
|
let mut body = json!({ "req": req, "reqid": rid });
|
||||||
|
if let Value::Object(map) = data {
|
||||||
|
for (k, v) in map {
|
||||||
|
body[k] = v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let json_str = serde_json::to_string(&body).map_err(|e| e.to_string())?;
|
||||||
|
let sign_key = self.sign_key.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||||
|
let message = if sign_key.is_empty() {
|
||||||
|
json_str.clone()
|
||||||
|
} else {
|
||||||
|
hmac_sha256_b64(&sign_key, &json_str) + &json_str
|
||||||
|
};
|
||||||
|
|
||||||
|
let (tx, rx) = tokio::sync::oneshot::channel::<Value>();
|
||||||
|
self.pending
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|e| e.into_inner())
|
||||||
|
.insert(rid.clone(), tx);
|
||||||
|
{
|
||||||
|
let mut guard = self.ws.lock().await;
|
||||||
|
let stream = guard
|
||||||
|
.as_mut()
|
||||||
|
.ok_or_else(|| "fnOS 连接已断开".to_string())?;
|
||||||
|
stream
|
||||||
|
.send(Message::Text(message.into()))
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("发送请求失败: {e}"))?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let resp = tokio::time::timeout(Duration::from_secs(10), rx)
|
||||||
|
.await
|
||||||
|
.map_err(|_| "fnOS 请求超时".to_string())?
|
||||||
|
.map_err(|_| "fnOS 请求通道关闭".to_string())?;
|
||||||
|
if resp.is_null() {
|
||||||
|
return Err("fnOS 连接已断开".to_string());
|
||||||
|
}
|
||||||
|
if let Some(errno) = resp["errno"].as_i64() {
|
||||||
|
if errno != 0 {
|
||||||
|
return Err(format!("fnOS 请求失败(errno {errno})"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn login(&self, username: &str, password: &str) -> Result<(), String> {
|
||||||
|
let resp = self.request("util.crypto.getRSAPub", Value::Null).await?;
|
||||||
|
let pub_pem = resp["pub"].as_str().ok_or("getRSAPub 未返回 pub")?.to_string();
|
||||||
|
let si = resp["si"].as_str().unwrap_or("").to_string();
|
||||||
|
|
||||||
|
let key = random_key();
|
||||||
|
let iv = random_iv();
|
||||||
|
let login_body = json!({
|
||||||
|
"user": username,
|
||||||
|
"password": password,
|
||||||
|
"deviceType": "Browser",
|
||||||
|
"deviceName": "Thing Client",
|
||||||
|
"stay": false,
|
||||||
|
"si": si,
|
||||||
|
});
|
||||||
|
let json_str = serde_json::to_string(&login_body).map_err(|e| e.to_string())?;
|
||||||
|
let key_bytes: [u8; 32] = key
|
||||||
|
.as_bytes()
|
||||||
|
.try_into()
|
||||||
|
.map_err(|_| "AES 密钥长度错误".to_string())?;
|
||||||
|
let aes_b64 = aes_cbc_encrypt_b64(json_str.as_bytes(), &key_bytes, &iv);
|
||||||
|
let rsa_b64 = rsa_encrypt_b64(&pub_pem, &key)?;
|
||||||
|
let enc = json!({
|
||||||
|
"req": "encrypted",
|
||||||
|
"iv": base64::engine::general_purpose::STANDARD.encode(iv),
|
||||||
|
"rsa": rsa_b64,
|
||||||
|
"aes": aes_b64,
|
||||||
|
});
|
||||||
|
let resp = self.request("encrypted", enc).await?;
|
||||||
|
let token = resp["token"].as_str().ok_or("fnOS 登录未返回 token")?.to_string();
|
||||||
|
let secret = resp["secret"].as_str().ok_or("fnOS 登录未返回 secret")?.to_string();
|
||||||
|
let secret_dec = aes_cbc_decrypt_b64(&secret, &key_bytes, &iv)?;
|
||||||
|
let sign_key = base64::engine::general_purpose::STANDARD
|
||||||
|
.decode(&secret_dec)
|
||||||
|
.map_err(|e| format!("sign_key base64 解码失败: {e}"))?;
|
||||||
|
*self.token.lock().unwrap_or_else(|e| e.into_inner()) = token;
|
||||||
|
*self.sign_key.lock().unwrap_or_else(|e| e.into_inner()) = sign_key;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `file.checkUpload`:返回 uploadName。
|
||||||
|
pub async fn check_upload(&self, nas_path: &str, size: u64, overwrite: u32) -> Result<String, String> {
|
||||||
|
let resp = self
|
||||||
|
.request(
|
||||||
|
"file.checkUpload",
|
||||||
|
json!({ "size": size, "path": nas_path, "overwrite": overwrite }),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
resp["uploadName"]
|
||||||
|
.as_str()
|
||||||
|
.map(|s| s.to_string())
|
||||||
|
.ok_or_else(|| "checkUpload 未返回 uploadName".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `file.rm`:删除 NAS 文件(移入回收站)。
|
||||||
|
pub async fn delete_file(&self, nas_path: &str) -> Result<(), String> {
|
||||||
|
let name = nas_path.rsplit('/').next().unwrap_or(nas_path).to_string();
|
||||||
|
self.request(
|
||||||
|
"file.rm",
|
||||||
|
json!({
|
||||||
|
"files": [nas_path],
|
||||||
|
"moveToTrashbin": true,
|
||||||
|
"details": { "name": name, "count": 1, "dir": 0 },
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `file.ls`:列出目录。
|
||||||
|
pub async fn list(&self, path: &str) -> Result<Value, String> {
|
||||||
|
self.request("file.ls", json!({ "path": path })).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// HTTP 上传到 NAS(需要已登录的 session)。返回上传后的文件名。
|
||||||
|
pub async fn upload_file(
|
||||||
|
session: &FnOsSession,
|
||||||
|
local_path: &std::path::Path,
|
||||||
|
nas_path: &str,
|
||||||
|
overwrite: u32,
|
||||||
|
) -> Result<String, String> {
|
||||||
|
let size = std::fs::metadata(local_path)
|
||||||
|
.map_err(|e| format!("读取本地文件失败: {e}"))?
|
||||||
|
.len();
|
||||||
|
let upload_name = session.check_upload(nas_path, size, overwrite).await?;
|
||||||
|
let parent = nas_path.rsplit('/').nth(1).unwrap_or("").to_string();
|
||||||
|
let trim_path = if parent.is_empty() {
|
||||||
|
upload_name.clone()
|
||||||
|
} else {
|
||||||
|
format!("{parent}/{upload_name}")
|
||||||
|
};
|
||||||
|
let mtim = SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.map(|d| d.as_secs())
|
||||||
|
.unwrap_or(0)
|
||||||
|
.to_string();
|
||||||
|
let sign_key = session.sign_key.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||||
|
let trim_sign = hmac_sha256_b64(&sign_key, &trim_path);
|
||||||
|
let token = session.token();
|
||||||
|
|
||||||
|
let file_name = local_path
|
||||||
|
.file_name()
|
||||||
|
.and_then(|n| n.to_str())
|
||||||
|
.unwrap_or("music.bin")
|
||||||
|
.to_string();
|
||||||
|
let bytes = std::fs::read(local_path).map_err(|e| format!("读取本地文件失败: {e}"))?;
|
||||||
|
let mime = guess_mime(local_path);
|
||||||
|
let form = reqwest::multipart::Form::new().part(
|
||||||
|
"trim-upload-file",
|
||||||
|
reqwest::multipart::Part::bytes(bytes)
|
||||||
|
.file_name(file_name)
|
||||||
|
.mime_str(mime)
|
||||||
|
.map_err(|e| e.to_string())?,
|
||||||
|
);
|
||||||
|
|
||||||
|
let client = reqwest::Client::builder()
|
||||||
|
.no_proxy()
|
||||||
|
.timeout(Duration::from_secs(300))
|
||||||
|
.build()
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let resp = client
|
||||||
|
.post(format!("{}/upload", session.base_url))
|
||||||
|
.header("Trim-Token", token)
|
||||||
|
.header("Trim-Path", trim_path)
|
||||||
|
.header("Trim-Sign", trim_sign)
|
||||||
|
.header("Trim-Mtim", mtim)
|
||||||
|
.header("Trim-Overwrite", overwrite.to_string())
|
||||||
|
.header("Referer", format!("{}/", session.base_url))
|
||||||
|
.header("User-Agent", "Thing/1.0")
|
||||||
|
.header("Accept", "application/json, text/plain, */*")
|
||||||
|
.multipart(form)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("上传请求失败: {e}"))?;
|
||||||
|
let status = resp.status();
|
||||||
|
if !status.is_success() {
|
||||||
|
let body = resp.text().await.unwrap_or_default();
|
||||||
|
return Err(format!("上传失败(HTTP {status}): {body}"));
|
||||||
|
}
|
||||||
|
Ok(upload_name)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn guess_mime(p: &std::path::Path) -> &'static str {
|
||||||
|
match p
|
||||||
|
.extension()
|
||||||
|
.and_then(|e| e.to_str())
|
||||||
|
.map(|e| e.to_lowercase())
|
||||||
|
.as_deref()
|
||||||
|
{
|
||||||
|
Some("mp3") => "audio/mpeg",
|
||||||
|
Some("flac") => "audio/flac",
|
||||||
|
Some("wav") => "audio/wav",
|
||||||
|
Some("m4a") => "audio/mp4",
|
||||||
|
Some("aac") => "audio/aac",
|
||||||
|
Some("ogg") => "audio/ogg",
|
||||||
|
Some("ape") => "audio/x-ape",
|
||||||
|
_ => "application/octet-stream",
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,588 @@
|
|||||||
|
//! 飞牛音乐(NAS)原生接口客户端 + 本地流代理的运行期。
|
||||||
|
//!
|
||||||
|
//! 支持多连接(本地 / frp / 预留 FnConnect),当前以"激活连接"为准。
|
||||||
|
//! 原生接口路径/认证(`music-token` Cookie、`x-access-code` 安全码、`/user/password-login` 登录)
|
||||||
|
//! 对照 FeiNiuMusic(Flutter) `api_client.dart` 的第三方纯前端实现翻译。
|
||||||
|
//! 所有对 NAS 的 HTTP 请求在本模块收敛(页面/命令层不直接发请求)。
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use specta::Type;
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
|
||||||
|
use super::MusicSettings;
|
||||||
|
|
||||||
|
pub use conn::normalize_base_url;
|
||||||
|
mod cache;
|
||||||
|
mod conn;
|
||||||
|
mod fnconnect;
|
||||||
|
mod fnos;
|
||||||
|
pub mod proxy;
|
||||||
|
|
||||||
|
pub use cache::CacheManager;
|
||||||
|
pub use fnconnect::{extract_fn_id, resolve_base_url};
|
||||||
|
pub use fnos::FnOsSession;
|
||||||
|
|
||||||
|
use conn::{generate_device_id, sha256_hex};
|
||||||
|
use proxy::{ProxyCfg, ProxyShared};
|
||||||
|
|
||||||
|
/// 一条飞牛音乐连接(持久化在 `MusicSettings`)。
|
||||||
|
#[derive(Serialize, Deserialize, Clone, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct FeiniuConnection {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
/// "lan" | "frp" | "fnconnect"(fnconnect 预留)
|
||||||
|
pub kind: String,
|
||||||
|
/// 服务器地址(http://192.168.x.x:5666 或 https://域名)
|
||||||
|
pub base_url: String,
|
||||||
|
pub username: String,
|
||||||
|
pub token: String,
|
||||||
|
pub device_id: String,
|
||||||
|
pub access_code: String,
|
||||||
|
/// https 遇到自签证书时忽略校验
|
||||||
|
pub insecure: bool,
|
||||||
|
/// fnconnect 连接的 fnId(如 fnos.net/<id> 或裸 id)
|
||||||
|
#[serde(default)]
|
||||||
|
pub fn_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for FeiniuConnection {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
id: String::new(),
|
||||||
|
name: String::new(),
|
||||||
|
kind: "lan".to_string(),
|
||||||
|
base_url: String::new(),
|
||||||
|
username: String::new(),
|
||||||
|
token: String::new(),
|
||||||
|
device_id: String::new(),
|
||||||
|
access_code: String::new(),
|
||||||
|
insecure: false,
|
||||||
|
fn_id: String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 当前激活连接信息(运行期副本,与 `MusicSettings` 的激活连接一致)。
|
||||||
|
struct Conn {
|
||||||
|
base_url: String,
|
||||||
|
token: String,
|
||||||
|
username: String,
|
||||||
|
device_id: String,
|
||||||
|
access_code: String,
|
||||||
|
insecure: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// LAN 直连,`no_proxy` 避免被代理模块(mihomo)拦走;按 insecure 惰性重建(支持自签证书)。
|
||||||
|
struct ClientSlot {
|
||||||
|
insecure: bool,
|
||||||
|
client: reqwest::Client,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Feiniu {
|
||||||
|
client: Mutex<Option<ClientSlot>>,
|
||||||
|
conn: Mutex<Conn>,
|
||||||
|
proxy: Mutex<Option<(u16, ProxyShared)>>,
|
||||||
|
cache: CacheManager,
|
||||||
|
/// fnOS 文件服务会话:connection id → 会话
|
||||||
|
fnos_sessions: Mutex<HashMap<String, Arc<FnOsSession>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Feiniu {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
client: Mutex::new(None),
|
||||||
|
conn: Mutex::new(Conn {
|
||||||
|
base_url: String::new(),
|
||||||
|
token: String::new(),
|
||||||
|
username: String::new(),
|
||||||
|
device_id: String::new(),
|
||||||
|
access_code: String::new(),
|
||||||
|
insecure: false,
|
||||||
|
}),
|
||||||
|
proxy: Mutex::new(None),
|
||||||
|
cache: CacheManager::new(Path::new("placeholder")), // 由 set_cache_root 重建
|
||||||
|
fnos_sessions: Mutex::new(HashMap::new()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Feiniu {
|
||||||
|
/// 设置缓存根目录({app_data}/music/cache),应用启动时调用一次。
|
||||||
|
pub fn set_cache_root(&mut self, app_data_dir: &Path) {
|
||||||
|
self.cache = CacheManager::new(app_data_dir);
|
||||||
|
}
|
||||||
|
/// 取(并惰性构建)对应 insecure 的 reqwest client。
|
||||||
|
fn client(&self, insecure: bool) -> reqwest::Client {
|
||||||
|
let mut g = self.client.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
let hit = g.as_ref().map(|s| s.insecure == insecure).unwrap_or(false);
|
||||||
|
if !hit {
|
||||||
|
*g = Some(ClientSlot {
|
||||||
|
insecure,
|
||||||
|
client: reqwest::Client::builder()
|
||||||
|
.no_proxy()
|
||||||
|
.timeout(Duration::from_secs(10))
|
||||||
|
.danger_accept_invalid_certs(insecure)
|
||||||
|
.build()
|
||||||
|
.unwrap_or_else(|_| reqwest::Client::new()),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
g.as_ref().unwrap().client.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 从持久化设置刷新运行期连接与代理配置(以激活连接为准;幂等)。
|
||||||
|
pub fn sync_with_settings(&self, s: &MusicSettings) {
|
||||||
|
let (base_url, token, username, device_id, access_code, insecure) =
|
||||||
|
match s.feiniu_active() {
|
||||||
|
Some(c) => (
|
||||||
|
c.base_url.clone(),
|
||||||
|
c.token.clone(),
|
||||||
|
c.username.clone(),
|
||||||
|
c.device_id.clone(),
|
||||||
|
c.access_code.clone(),
|
||||||
|
c.insecure,
|
||||||
|
),
|
||||||
|
None => (
|
||||||
|
String::new(),
|
||||||
|
String::new(),
|
||||||
|
String::new(),
|
||||||
|
String::new(),
|
||||||
|
String::new(),
|
||||||
|
false,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
if let Ok(mut c) = self.conn.lock() {
|
||||||
|
c.base_url = base_url;
|
||||||
|
c.token = token;
|
||||||
|
c.username = username;
|
||||||
|
c.device_id = device_id;
|
||||||
|
c.access_code = access_code;
|
||||||
|
c.insecure = insecure;
|
||||||
|
}
|
||||||
|
// 确保 client 构建到位(insecure 变化时重建)
|
||||||
|
self.client(insecure);
|
||||||
|
self.sync_proxy_cfg();
|
||||||
|
self.sync_proxy_client();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sync_proxy_cfg(&self) {
|
||||||
|
if let Ok(g) = self.proxy.lock() {
|
||||||
|
if let Some((_, shared)) = g.as_ref() {
|
||||||
|
let cfg = self.current_cfg();
|
||||||
|
if let Ok(mut c) = shared.cfg.lock() {
|
||||||
|
*c = cfg;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sync_proxy_client(&self) {
|
||||||
|
let (_, client) = self.conn_client();
|
||||||
|
if let Ok(mut g) = self.proxy.lock() {
|
||||||
|
if let Some((_, shared)) = g.as_mut() {
|
||||||
|
shared.client = client;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn conn_client(&self) -> (bool, reqwest::Client) {
|
||||||
|
let insecure = self.conn.lock().unwrap_or_else(|e| e.into_inner()).insecure;
|
||||||
|
(insecure, self.client(insecure))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn current_cfg(&self) -> ProxyCfg {
|
||||||
|
let c = self.conn.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
ProxyCfg {
|
||||||
|
base_url: c.base_url.clone(),
|
||||||
|
token: c.token.clone(),
|
||||||
|
access_code: c.access_code.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn auth_triple(&self) -> (String, String, String) {
|
||||||
|
let c = self.conn.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
(c.base_url.clone(), c.token.clone(), c.access_code.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 对某个 base_url 执行登录(探测/登录连接共用)。
|
||||||
|
/// 成功返回 `(userToken, device_id)` 并更新运行期 conn;命令层负责落回对应连接持久化。
|
||||||
|
pub async fn login(
|
||||||
|
&self,
|
||||||
|
base_url: &str,
|
||||||
|
username: &str,
|
||||||
|
password: &str,
|
||||||
|
) -> Result<(String, String), String> {
|
||||||
|
let base = normalize_base_url(base_url);
|
||||||
|
let (device_id, insecure) = {
|
||||||
|
let c = self.conn.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
let d = if c.device_id.is_empty() {
|
||||||
|
generate_device_id()
|
||||||
|
} else {
|
||||||
|
c.device_id.clone()
|
||||||
|
};
|
||||||
|
(d, c.insecure)
|
||||||
|
};
|
||||||
|
let body = json!({
|
||||||
|
"username": username,
|
||||||
|
"password": sha256_hex(password),
|
||||||
|
"deviceId": device_id,
|
||||||
|
});
|
||||||
|
let resp = self
|
||||||
|
.client(insecure)
|
||||||
|
.post(format!("{base}/music/api/v1/user/password-login"))
|
||||||
|
.json(&body)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
let kind = if e.is_timeout() {
|
||||||
|
"连接超时(NAS 不可达?)"
|
||||||
|
} else {
|
||||||
|
"连接失败"
|
||||||
|
};
|
||||||
|
format!("{kind}: {e}")
|
||||||
|
})?;
|
||||||
|
let status = resp.status();
|
||||||
|
let b: Value = resp
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|_| json!({ "code": status.as_u16() }));
|
||||||
|
let code = b["code"].as_i64().unwrap_or(i64::from(status.as_u16()));
|
||||||
|
if code != 0 {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
let token = b["data"]["userToken"]
|
||||||
|
.as_str()
|
||||||
|
.ok_or_else(|| "登录失败:未返回 token".to_string())?
|
||||||
|
.to_string();
|
||||||
|
|
||||||
|
if let Ok(mut c) = self.conn.lock() {
|
||||||
|
c.base_url = base;
|
||||||
|
c.token = token.clone();
|
||||||
|
c.username = username.to_string();
|
||||||
|
c.device_id = device_id.clone();
|
||||||
|
}
|
||||||
|
self.sync_proxy_cfg();
|
||||||
|
Ok((token, device_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 登出:仅清运行期 token(保留连接信息与账号)。
|
||||||
|
pub fn logout(&self) {
|
||||||
|
if let Ok(mut c) = self.conn.lock() {
|
||||||
|
c.token.clear();
|
||||||
|
}
|
||||||
|
self.sync_proxy_cfg();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 当前激活连接配置(前端状态展示 + 是否已登录)。
|
||||||
|
pub fn config(&self) -> Value {
|
||||||
|
let c = self.conn.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
json!({
|
||||||
|
"baseUrl": c.base_url,
|
||||||
|
"username": c.username,
|
||||||
|
"loggedIn": !c.token.is_empty(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 分页拉取曲目列表:`GET /music/api/v1/track/list`(可选关键词)。
|
||||||
|
pub async fn list_tracks(&self, page: u32, size: u32, keyword: Option<&str>) -> Result<Value, String> {
|
||||||
|
let mut query = vec![
|
||||||
|
("page".to_string(), page.to_string()),
|
||||||
|
("size".to_string(), size.to_string()),
|
||||||
|
];
|
||||||
|
let kw = keyword.unwrap_or("").trim().to_string();
|
||||||
|
if !kw.is_empty() {
|
||||||
|
query.push(("keyword".to_string(), kw));
|
||||||
|
}
|
||||||
|
self.authed_get("/music/api/v1/track/list", query).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 歌词:`GET /music/api/v1/lyric/list?trackGUID=<guid>`。
|
||||||
|
pub async fn lyric(&self, guid: &str) -> Result<String, String> {
|
||||||
|
let v = self
|
||||||
|
.authed_get(
|
||||||
|
"/music/api/v1/lyric/list",
|
||||||
|
vec![("trackGUID".to_string(), guid.to_string())],
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
Ok(extract_lyric_text(&v))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 本地媒体地址前缀:`http://127.0.0.1:<port>/feiniu`。首次调用惰性启动代理。
|
||||||
|
pub async fn media_prefix(&self) -> Result<String, String> {
|
||||||
|
let port = self.ensure_proxy().await?;
|
||||||
|
Ok(format!("http://127.0.0.1:{port}/feiniu"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 递归扫描本地曲库目录中的音频文件,返回轻量条目(不解析时长/封面)。
|
||||||
|
pub fn scan_local(&self, dirs: &[String]) -> Value {
|
||||||
|
const EXTS: [&str; 7] = ["mp3", "flac", "wav", "m4a", "aac", "ogg", "ape"];
|
||||||
|
let mut items: Vec<Value> = Vec::new();
|
||||||
|
for dir in dirs {
|
||||||
|
let p = Path::new(dir);
|
||||||
|
if !p.is_dir() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for entry in walkdir::WalkDir::new(p).follow_links(false) {
|
||||||
|
let Ok(entry) = entry else { continue };
|
||||||
|
if !entry.file_type().is_file() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let path = entry.path();
|
||||||
|
let ext = path
|
||||||
|
.extension()
|
||||||
|
.and_then(|e| e.to_str())
|
||||||
|
.map(|e| e.to_lowercase())
|
||||||
|
.unwrap_or_default();
|
||||||
|
if !EXTS.contains(&ext.as_str()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let size = entry.metadata().map(|m| m.len()).unwrap_or(0);
|
||||||
|
let mtim = entry
|
||||||
|
.metadata()
|
||||||
|
.ok()
|
||||||
|
.and_then(|m| m.modified().ok())
|
||||||
|
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||||
|
.map(|d| d.as_secs())
|
||||||
|
.unwrap_or(0);
|
||||||
|
let name = path
|
||||||
|
.file_stem()
|
||||||
|
.and_then(|n| n.to_str())
|
||||||
|
.unwrap_or("未知")
|
||||||
|
.to_string();
|
||||||
|
items.push(json!({
|
||||||
|
"path": path.to_string_lossy(),
|
||||||
|
"title": name,
|
||||||
|
"size": size,
|
||||||
|
"mtim": mtim,
|
||||||
|
"dir": dir,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
json!({ "items": items })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 缓存状态。
|
||||||
|
pub fn cache_status(&self) -> Value {
|
||||||
|
self.cache.status()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 清空缓存。
|
||||||
|
pub fn cache_clear(&self) {
|
||||||
|
self.cache.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 命中缓存直接返回文件路径;未命中则从 NAS 流式拉取写入缓存后返回。
|
||||||
|
/// 返回缓存文件路径。失败返回 Err。
|
||||||
|
pub async fn cache_fetch(&self, guid: &str, max_gb: u32) -> Result<Option<String>, String> {
|
||||||
|
if let Some(hit) = self.cache.hit(guid) {
|
||||||
|
return Ok(Some(hit));
|
||||||
|
}
|
||||||
|
let (base, token, access_code) = self.auth_triple();
|
||||||
|
if base.is_empty() || token.is_empty() {
|
||||||
|
return Err("未登录".into());
|
||||||
|
}
|
||||||
|
let (_, client) = self.conn_client();
|
||||||
|
let mut rb = client.get(format!("{base}/music/api/v1/track/stream?guid={guid}"));
|
||||||
|
rb = rb.header("cookie", format!("music-token={token}"));
|
||||||
|
if !access_code.is_empty() {
|
||||||
|
use base64::Engine;
|
||||||
|
rb = rb
|
||||||
|
.header(
|
||||||
|
"x-access-code",
|
||||||
|
base64::engine::general_purpose::STANDARD.encode(access_code.as_bytes()),
|
||||||
|
)
|
||||||
|
.header("x-access-source", "app");
|
||||||
|
}
|
||||||
|
let resp = rb.send().await.map_err(|e| format!("拉取失败: {e}"))?;
|
||||||
|
if !resp.status().is_success() {
|
||||||
|
return Err(format!("拉取失败(HTTP {})", resp.status().as_u16()));
|
||||||
|
}
|
||||||
|
let ct = resp
|
||||||
|
.headers()
|
||||||
|
.get("content-type")
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.map(|s| s.to_string())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let ext = match ct.split('/').last() {
|
||||||
|
Some("flac") => "flac",
|
||||||
|
Some("mpeg") => "mp3",
|
||||||
|
Some("wav") => "wav",
|
||||||
|
Some("ogg") => "ogg",
|
||||||
|
Some("mp4") => "m4a",
|
||||||
|
Some("aac") => "aac",
|
||||||
|
_ => "bin",
|
||||||
|
};
|
||||||
|
let stream = resp.bytes_stream();
|
||||||
|
let path = self
|
||||||
|
.cache
|
||||||
|
.put(guid, ext, max_gb, stream)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e)?;
|
||||||
|
let _ = path;
|
||||||
|
Ok(self.cache.hit(guid))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== fnOS 文件服务(P6:上传/删除) =====
|
||||||
|
|
||||||
|
/// fnOS 登录:为指定连接建立文件服务会话。
|
||||||
|
pub async fn fnos_login(
|
||||||
|
&self,
|
||||||
|
connection_id: &str,
|
||||||
|
base_url: &str,
|
||||||
|
username: &str,
|
||||||
|
password: &str,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let session = Arc::new(FnOsSession::connect(base_url, username, password).await?);
|
||||||
|
if let Ok(mut m) = self.fnos_sessions.lock() {
|
||||||
|
m.insert(connection_id.to_string(), session);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fnos_logout(&self, connection_id: &str) {
|
||||||
|
if let Ok(mut m) = self.fnos_sessions.lock() {
|
||||||
|
m.remove(connection_id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fnos_logged_in(&self, connection_id: &str) -> bool {
|
||||||
|
self.fnos_sessions
|
||||||
|
.lock()
|
||||||
|
.map(|m| m.contains_key(connection_id))
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 上传本地文件到 NAS(走 fnOS 会话;会话缺失返回 Err)。
|
||||||
|
pub async fn fnos_upload(
|
||||||
|
&self,
|
||||||
|
connection_id: &str,
|
||||||
|
local_path: &std::path::Path,
|
||||||
|
nas_path: &str,
|
||||||
|
) -> Result<String, String> {
|
||||||
|
let session = self
|
||||||
|
.fnos_sessions
|
||||||
|
.lock()
|
||||||
|
.map(|m| m.get(connection_id).cloned())
|
||||||
|
.ok()
|
||||||
|
.flatten()
|
||||||
|
.ok_or_else(|| "请先登录 NAS 文件服务(设置 → 连接 → fnOS 登录)")?;
|
||||||
|
fnos::upload_file(&session, local_path, nas_path, 2).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 删除 NAS 文件。
|
||||||
|
pub async fn fnos_delete(&self, connection_id: &str, nas_path: &str) -> Result<(), String> {
|
||||||
|
let session = self
|
||||||
|
.fnos_sessions
|
||||||
|
.lock()
|
||||||
|
.map(|m| m.get(connection_id).cloned())
|
||||||
|
.ok()
|
||||||
|
.flatten()
|
||||||
|
.ok_or_else(|| "请先登录 NAS 文件服务")?;
|
||||||
|
session.delete_file(nas_path).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 列出 NAS 目录。
|
||||||
|
pub async fn fnos_list(&self, connection_id: &str, path: &str) -> Result<Value, String> {
|
||||||
|
let session = self
|
||||||
|
.fnos_sessions
|
||||||
|
.lock()
|
||||||
|
.map(|m| m.get(connection_id).cloned())
|
||||||
|
.ok()
|
||||||
|
.flatten()
|
||||||
|
.ok_or_else(|| "请先登录 NAS 文件服务")?;
|
||||||
|
session.list(path).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn ensure_proxy(&self) -> Result<u16, String> {
|
||||||
|
if let Ok(g) = self.proxy.lock() {
|
||||||
|
if let Some((port, _)) = g.as_ref() {
|
||||||
|
return Ok(*port);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let (_, client) = self.conn_client();
|
||||||
|
let shared = ProxyShared {
|
||||||
|
client,
|
||||||
|
cfg: Arc::new(Mutex::new(self.current_cfg())),
|
||||||
|
};
|
||||||
|
let port = proxy::start(shared.clone()).await?;
|
||||||
|
if let Ok(mut g) = self.proxy.lock() {
|
||||||
|
*g = Some((port, shared));
|
||||||
|
}
|
||||||
|
Ok(port)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn authed_get(&self, path: &str, query: Vec<(String, String)>) -> Result<Value, String> {
|
||||||
|
let (base, token, access_code) = self.auth_triple();
|
||||||
|
if base.is_empty() || token.is_empty() {
|
||||||
|
return Err("未登录".into());
|
||||||
|
}
|
||||||
|
let (_, client) = self.conn_client();
|
||||||
|
let qrefs: Vec<(&str, &str)> = query.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
|
||||||
|
let mut rb = client.get(format!("{base}{path}")).query(&qrefs);
|
||||||
|
rb = rb.header("cookie", format!("music-token={token}"));
|
||||||
|
if !access_code.is_empty() {
|
||||||
|
use base64::Engine;
|
||||||
|
rb = rb
|
||||||
|
.header(
|
||||||
|
"x-access-code",
|
||||||
|
base64::engine::general_purpose::STANDARD.encode(access_code.as_bytes()),
|
||||||
|
)
|
||||||
|
.header("x-access-source", "app");
|
||||||
|
}
|
||||||
|
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 code = body["code"].as_i64().unwrap_or(i64::from(status.as_u16()));
|
||||||
|
if code != 0 {
|
||||||
|
if status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN {
|
||||||
|
return Err("登录已过期,请重新登录".into());
|
||||||
|
}
|
||||||
|
let msg = body["msg"]
|
||||||
|
.as_str()
|
||||||
|
.map(|s| s.to_string())
|
||||||
|
.unwrap_or_else(|| format!("请求失败(HTTP {status})"));
|
||||||
|
return Err(msg);
|
||||||
|
}
|
||||||
|
Ok(body["data"].clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 尽力从 /lyric/list 响应中取第一段歌词文本(响应结构未文档化,做宽松映射)。
|
||||||
|
fn extract_lyric_text(v: &Value) -> String {
|
||||||
|
match v {
|
||||||
|
Value::Array(arr) => arr
|
||||||
|
.first()
|
||||||
|
.map(|it| {
|
||||||
|
it["content"]
|
||||||
|
.as_str()
|
||||||
|
.or_else(|| it["lyric"].as_str())
|
||||||
|
.or_else(|| it["text"].as_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_string()
|
||||||
|
})
|
||||||
|
.unwrap_or_default(),
|
||||||
|
Value::Object(_) => v["content"]
|
||||||
|
.as_str()
|
||||||
|
.or_else(|| v["lyric"].as_str())
|
||||||
|
.or_else(|| v["text"].as_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_string(),
|
||||||
|
_ => String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
//! 飞牛音乐本地流代理(axum)。
|
||||||
|
//!
|
||||||
|
//! 原生 `/track/stream`、`/static/cover` 需要 `Cookie: music-token=<token>`,而
|
||||||
|
//! WebView 的 `<audio>/<img>` 无法设置 Cookie。本模块绑定 `127.0.0.1:<动态端口>`,
|
||||||
|
//! 转发请求时注入 Cookie 与可选的安全码头,前端直接用本地地址播放/显示,天然支持 Range/seek。
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use axum::{
|
||||||
|
extract::{Query, State},
|
||||||
|
http::{header, HeaderMap, StatusCode},
|
||||||
|
response::{IntoResponse, Response},
|
||||||
|
routing::get,
|
||||||
|
Router,
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::conn::normalize_base_url;
|
||||||
|
|
||||||
|
/// 由 Feiniu 运行期与代理 handler 共享的连接配置(登录更新、登出置空)。
|
||||||
|
#[derive(Clone, Default)]
|
||||||
|
pub struct ProxyCfg {
|
||||||
|
pub base_url: String,
|
||||||
|
pub token: String,
|
||||||
|
pub access_code: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct ProxyShared {
|
||||||
|
pub client: reqwest::Client,
|
||||||
|
pub cfg: Arc<Mutex<ProxyCfg>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 启动本地流代理,绑定到 `127.0.0.1:0`(动态空闲端口),返回实际端口。
|
||||||
|
/// 代理以独立 tokio 任务常驻应用存活期;token 变化经共享 `ProxyCfg` 即时生效,无需重启。
|
||||||
|
pub async fn start(shared: ProxyShared) -> Result<u16, String> {
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("绑定本地端口失败: {e}"))?;
|
||||||
|
let port = listener
|
||||||
|
.local_addr()
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
.port();
|
||||||
|
let app = Router::new()
|
||||||
|
.route("/feiniu/stream", get(proxy_stream))
|
||||||
|
.route("/feiniu/cover", get(proxy_cover))
|
||||||
|
.with_state(shared);
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if let Err(e) = axum::serve(listener, app).await {
|
||||||
|
crate::logger::log_error("music", &format!("飞牛流代理异常: {e}"));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Ok(port)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn proxy_stream(
|
||||||
|
State(s): State<ProxyShared>,
|
||||||
|
Query(q): Query<HashMap<String, String>>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
) -> Response {
|
||||||
|
let guid = q.get("guid").cloned().unwrap_or_default().trim().to_string();
|
||||||
|
if guid.is_empty() {
|
||||||
|
return (StatusCode::BAD_REQUEST, "missing guid").into_response();
|
||||||
|
}
|
||||||
|
forward(
|
||||||
|
&s,
|
||||||
|
"/music/api/v1/track/stream",
|
||||||
|
vec![("guid".to_string(), guid)],
|
||||||
|
&headers,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn proxy_cover(
|
||||||
|
State(s): State<ProxyShared>,
|
||||||
|
Query(q): Query<HashMap<String, String>>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
) -> Response {
|
||||||
|
let cover_id = q
|
||||||
|
.get("coverId")
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.trim()
|
||||||
|
.to_string();
|
||||||
|
if cover_id.is_empty() {
|
||||||
|
return (StatusCode::BAD_REQUEST, "missing coverId").into_response();
|
||||||
|
}
|
||||||
|
let size = q.get("size").cloned().unwrap_or_else(|| "320".into());
|
||||||
|
forward(
|
||||||
|
&s,
|
||||||
|
"/music/api/v1/static/cover",
|
||||||
|
vec![
|
||||||
|
("coverId".to_string(), cover_id),
|
||||||
|
("size".to_string(), size),
|
||||||
|
],
|
||||||
|
&headers,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 统一转发:向 NAS 发起上游 GET,注入 Cookie/安全码,透传 Range 与响应头,流式回传 body。
|
||||||
|
async fn forward(
|
||||||
|
s: &ProxyShared,
|
||||||
|
path: &str,
|
||||||
|
query: Vec<(String, String)>,
|
||||||
|
headers: &HeaderMap,
|
||||||
|
) -> Response {
|
||||||
|
let cfg = match s.cfg.lock() {
|
||||||
|
Ok(g) => g.clone(),
|
||||||
|
Err(e) => e.into_inner().clone(),
|
||||||
|
};
|
||||||
|
if cfg.base_url.is_empty() || cfg.token.is_empty() {
|
||||||
|
return (StatusCode::UNAUTHORIZED, "飞牛音乐未登录").into_response();
|
||||||
|
}
|
||||||
|
|
||||||
|
let base = normalize_base_url(&cfg.base_url);
|
||||||
|
let url = format!("{base}{path}");
|
||||||
|
let qrefs: Vec<(&str, &str)> = query.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
|
||||||
|
|
||||||
|
let mut rb = s.client.get(&url).query(&qrefs);
|
||||||
|
rb = rb.header("cookie", format!("music-token={}", cfg.token));
|
||||||
|
if !cfg.access_code.is_empty() {
|
||||||
|
use base64::Engine;
|
||||||
|
rb = rb
|
||||||
|
.header(
|
||||||
|
"x-access-code",
|
||||||
|
base64::engine::general_purpose::STANDARD.encode(cfg.access_code.as_bytes()),
|
||||||
|
)
|
||||||
|
.header("x-access-source", "app");
|
||||||
|
}
|
||||||
|
if let Some(range) = headers.get(header::RANGE) {
|
||||||
|
rb = rb.header(header::RANGE, range.clone());
|
||||||
|
}
|
||||||
|
drop(cfg);
|
||||||
|
|
||||||
|
let resp = match rb.send().await {
|
||||||
|
Ok(r) => r,
|
||||||
|
Err(e) => return (StatusCode::BAD_GATEWAY, format!("上游错误: {e}")).into_response(),
|
||||||
|
};
|
||||||
|
let status = resp.status();
|
||||||
|
|
||||||
|
let ct = resp.headers().get(header::CONTENT_TYPE).cloned();
|
||||||
|
let cl = resp.headers().get(header::CONTENT_LENGTH).cloned();
|
||||||
|
let cr = resp.headers().get(header::CONTENT_RANGE).cloned();
|
||||||
|
let ar = resp.headers().get(header::ACCEPT_RANGES).cloned();
|
||||||
|
|
||||||
|
let body = axum::body::Body::from_stream(resp.bytes_stream());
|
||||||
|
let mut out = Response::new(body);
|
||||||
|
*out.status_mut() = status;
|
||||||
|
let h = out.headers_mut();
|
||||||
|
if let Some(v) = ct {
|
||||||
|
h.insert(header::CONTENT_TYPE, v);
|
||||||
|
}
|
||||||
|
if let Some(v) = cl {
|
||||||
|
h.insert(header::CONTENT_LENGTH, v);
|
||||||
|
}
|
||||||
|
if let Some(v) = cr {
|
||||||
|
h.insert(header::CONTENT_RANGE, v);
|
||||||
|
}
|
||||||
|
if let Some(v) = ar {
|
||||||
|
h.insert(header::ACCEPT_RANGES, v);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
@@ -0,0 +1,595 @@
|
|||||||
|
//! 音乐下载模块(musicdl 桥接)。
|
||||||
|
//!
|
||||||
|
//! 架构:Vue 前端 → Tauri 命令 → [MusicManager] → stdio JSON-Lines → `bridge.py`
|
||||||
|
//! → musicdl(纯 Python 聚合下载器)。
|
||||||
|
//!
|
||||||
|
//! 目录布局({app_data_dir}/music/):
|
||||||
|
//! - `bridge.py`:桥接脚本(include_str! 内置,运行时写出)
|
||||||
|
//! - `runtime/python/`:便携 Python(python.org embeddable,含 pip)
|
||||||
|
//! - `runtime/get-pip.py`:pip 引导脚本(下载后删除)
|
||||||
|
//! - `runtime/*.zip`:下载过程中的临时安装包(完成后删除)
|
||||||
|
//! - `outputs/`:默认音乐下载目录
|
||||||
|
//!
|
||||||
|
//! 子模块:
|
||||||
|
//! - [`runtime`]:Python 运行时探测与便携版安装
|
||||||
|
//! - [`bridge`]:桥接进程生命周期(spawn / JSON 协议 / ping / 停止)
|
||||||
|
//! - [`commands`]:Tauri 命令层
|
||||||
|
|
||||||
|
mod bridge;
|
||||||
|
mod commands;
|
||||||
|
mod feiniu;
|
||||||
|
mod runtime;
|
||||||
|
|
||||||
|
pub use feiniu::{extract_fn_id, normalize_base_url, resolve_base_url, Feiniu, FeiniuConnection};
|
||||||
|
|
||||||
|
pub use commands::{
|
||||||
|
feiniu_activate_connection, feiniu_cache_clear, feiniu_cache_fetch, feiniu_cache_status,
|
||||||
|
feiniu_delete_connection, feiniu_fnconnect_resolve, feiniu_fnos_delete, feiniu_fnos_list,
|
||||||
|
feiniu_fnos_login, feiniu_fnos_logout, feiniu_fnos_status, feiniu_fnos_upload,
|
||||||
|
feiniu_get_config, feiniu_list_connections, feiniu_list_tracks, feiniu_login, feiniu_logout,
|
||||||
|
feiniu_lyric, feiniu_media_prefix, feiniu_save_connection, feiniu_scan_local,
|
||||||
|
feiniu_test_connection, music_cancel_runtime_install, music_download, music_download_cancel,
|
||||||
|
music_env_status, music_get_settings, music_get_sources, music_install_runtime,
|
||||||
|
music_parse_playlist, music_ping, music_resolve, music_save_settings, music_search,
|
||||||
|
music_stop_bridge,
|
||||||
|
};
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use specta::Type;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::fs;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::process::{Child, ChildStdin};
|
||||||
|
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
use tauri::AppHandle;
|
||||||
|
|
||||||
|
/// 便携 Python 版本(python.org embeddable,含 pip 引导)
|
||||||
|
pub const BUNDLED_PY_VERSION: &str = "3.12.10";
|
||||||
|
/// musicdl 锁定版本(其 API 每周都在变,必须锁版本并定期升级)
|
||||||
|
pub const MUSICDL_VERSION: &str = "2.13.11";
|
||||||
|
/// pip 镜像源(国内网络直连 PyPI 较慢,默认用清华镜像,可改回官方)
|
||||||
|
pub const PIP_INDEX_URL: &str = "https://pypi.tuna.tsinghua.edu.cn/simple";
|
||||||
|
/// 默认搜索源(网易云 / QQ音乐 / 酷狗)
|
||||||
|
pub const DEFAULT_SOURCES: [&str; 3] = [
|
||||||
|
"NeteaseMusicClient",
|
||||||
|
"QQMusicClient",
|
||||||
|
"KugouMusicClient",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// 桥接进程条目(自管 stdio,不走 ProcessManager)
|
||||||
|
pub(crate) struct BridgeEntry {
|
||||||
|
pub child: Child,
|
||||||
|
pub stdin: ChildStdin,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 解析出的 Python 运行时信息(内部使用,不序列化)
|
||||||
|
pub(crate) struct PythonEnv {
|
||||||
|
pub source: &'static str, // "system" | "bundled"
|
||||||
|
pub exe: PathBuf,
|
||||||
|
pub version: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 环境状态(返回前端,设置页「环境检查」面板展示)
|
||||||
|
#[derive(Serialize, Clone, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct MusicEnvStatus {
|
||||||
|
/// 系统 Python 版本(如 "3.14.5"),无则 None
|
||||||
|
pub python: Option<String>,
|
||||||
|
/// python 来源:"system" | "bundled" | "none"
|
||||||
|
pub python_source: String,
|
||||||
|
/// 便携 Python 可执行文件路径(未安装则 None)
|
||||||
|
pub bundled_python: Option<String>,
|
||||||
|
/// musicdl 是否可导入
|
||||||
|
pub musicdl_installed: bool,
|
||||||
|
/// musicdl 版本
|
||||||
|
pub musicdl_version: Option<String>,
|
||||||
|
/// FFmpeg 是否可用(部分音源需要,非必需)
|
||||||
|
pub ffmpeg: Option<String>,
|
||||||
|
/// 桥接进程是否在运行
|
||||||
|
pub bridge_running: bool,
|
||||||
|
/// 运行时目录({app_data_dir}/music)
|
||||||
|
pub runtime_dir: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 运行时安装进度事件负载(对应 events::MUSIC_RUNTIME_INSTALL_PROGRESS)
|
||||||
|
#[derive(Serialize, Clone, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct MusicInstallProgress {
|
||||||
|
pub stage: String,
|
||||||
|
pub percent: u32,
|
||||||
|
pub downloaded_bytes: u64,
|
||||||
|
pub total_bytes: Option<u64>,
|
||||||
|
pub message: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 音乐模块设置(settings.json 持久化;变更即时生效)
|
||||||
|
#[derive(Serialize, Deserialize, Clone, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct MusicSettings {
|
||||||
|
/// 下载保存目录
|
||||||
|
pub savedir: String,
|
||||||
|
/// 搜索源(musicdl 客户端名,如 NeteaseMusicClient)
|
||||||
|
pub sources: Vec<String>,
|
||||||
|
/// 下载时同步保存歌词
|
||||||
|
pub lyric_download: bool,
|
||||||
|
/// 下载时同步保存封面
|
||||||
|
pub cover_download: bool,
|
||||||
|
/// 搜索/下载请求是否走代理模块(mihomo mixed 端口)
|
||||||
|
pub use_proxy: bool,
|
||||||
|
/// 最大并发下载数
|
||||||
|
pub max_concurrent: u32,
|
||||||
|
/// 下载引擎:"musicdl" | "rust"(P2 生效)
|
||||||
|
pub download_engine: String,
|
||||||
|
/// 下载时是否弹窗选择音质(默认关;开启后点下载弹出所选歌曲档位并集选择)
|
||||||
|
pub select_quality_on_download: bool,
|
||||||
|
/// 下载时默认音质:"" 表示最高;否则为搜索音质档位 label(如 "无损"、"320K")
|
||||||
|
pub default_download_quality: String,
|
||||||
|
/// 飞牛音乐(NAS)连接:服务器地址(如 http://192.168.1.10:5666,空=未配置)
|
||||||
|
#[serde(default)]
|
||||||
|
pub feiniu_base_url: String,
|
||||||
|
/// 飞牛音乐登录 token(登录成功后保存)
|
||||||
|
#[serde(default)]
|
||||||
|
pub feiniu_token: String,
|
||||||
|
/// 飞牛音乐登录账号(展示 + 重新登录回填用)
|
||||||
|
#[serde(default)]
|
||||||
|
pub feiniu_username: String,
|
||||||
|
/// 飞牛音乐设备 ID(32 位 hex,登录签名用,一次生成复用)
|
||||||
|
#[serde(default)]
|
||||||
|
pub feiniu_device_id: String,
|
||||||
|
/// 飞牛音乐访问安全码(可选;仅需访问码的库才填,LAN 通常为空)
|
||||||
|
#[serde(default)]
|
||||||
|
pub feiniu_access_code: String,
|
||||||
|
/// 飞牛音乐连接列表(多连接:本地 / frp / 预留 fnconnect)
|
||||||
|
#[serde(default)]
|
||||||
|
pub feiniu_connections: Vec<FeiniuConnection>,
|
||||||
|
/// 当前激活连接的 id
|
||||||
|
#[serde(default)]
|
||||||
|
pub feiniu_active_id: String,
|
||||||
|
/// 本地曲库扫描目录(默认含音乐下载 savedir)
|
||||||
|
#[serde(default)]
|
||||||
|
pub feiniu_local_dirs: Vec<String>,
|
||||||
|
/// 播放缓存开关
|
||||||
|
#[serde(default)]
|
||||||
|
pub feiniu_cache_enabled: bool,
|
||||||
|
/// 缓存上限(GB)
|
||||||
|
#[serde(default)]
|
||||||
|
pub feiniu_cache_max_gb: u32,
|
||||||
|
/// 播放模式:"stream" 直连流式 | "cache" 缓存后播放
|
||||||
|
#[serde(default)]
|
||||||
|
pub feiniu_play_mode: String,
|
||||||
|
/// 飞牛曲库目标目录(NAS 绝对路径,如 vol1/1000/Music;上传到飞牛用)
|
||||||
|
#[serde(default)]
|
||||||
|
pub feiniu_library_nas_path: String,
|
||||||
|
/// 下载完成后自动上传到飞牛曲库
|
||||||
|
#[serde(default)]
|
||||||
|
pub feiniu_auto_upload: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MusicSettings {
|
||||||
|
/// 取激活连接:优先按 active_id,否则回退到第一条。
|
||||||
|
pub fn feiniu_active(&self) -> Option<&FeiniuConnection> {
|
||||||
|
self.feiniu_connections
|
||||||
|
.iter()
|
||||||
|
.find(|c| c.id == self.feiniu_active_id)
|
||||||
|
.or_else(|| self.feiniu_connections.first())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 兼容旧版单连接字段:若连接列表为空且存在旧 feiniu_* 字段,则迁移为一条默认连接。
|
||||||
|
pub fn migrate_feiniu(&mut self) {
|
||||||
|
if self.feiniu_connections.is_empty() {
|
||||||
|
if !self.feiniu_base_url.trim().is_empty() {
|
||||||
|
let base = self.feiniu_base_url.clone();
|
||||||
|
self.feiniu_connections.push(FeiniuConnection {
|
||||||
|
id: "default".to_string(),
|
||||||
|
name: base.clone(),
|
||||||
|
kind: "lan".to_string(),
|
||||||
|
base_url: base,
|
||||||
|
username: self.feiniu_username.clone(),
|
||||||
|
token: self.feiniu_token.clone(),
|
||||||
|
device_id: self.feiniu_device_id.clone(),
|
||||||
|
access_code: self.feiniu_access_code.clone(),
|
||||||
|
insecure: false,
|
||||||
|
fn_id: String::new(),
|
||||||
|
});
|
||||||
|
self.feiniu_active_id = "default".to_string();
|
||||||
|
}
|
||||||
|
} else if self.feiniu_active_id.is_empty()
|
||||||
|
|| !self.feiniu_connections.iter().any(|c| c.id == self.feiniu_active_id)
|
||||||
|
{
|
||||||
|
if let Some(c) = self.feiniu_connections.first() {
|
||||||
|
self.feiniu_active_id = c.id.clone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// settings 内存缓存条目(短时复用,避免高频调用反复读盘)
|
||||||
|
struct SettingsCacheEntry {
|
||||||
|
read_at: Instant,
|
||||||
|
settings: MusicSettings,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 音乐模块管理器
|
||||||
|
pub struct MusicManager {
|
||||||
|
root: PathBuf,
|
||||||
|
client: reqwest::Client,
|
||||||
|
/// 桥接进程(stdio 自管)
|
||||||
|
bridge: Mutex<Option<BridgeEntry>>,
|
||||||
|
/// 待响应请求表:id → oneshot(reader 线程按 id 分发)
|
||||||
|
pending: Arc<Mutex<HashMap<u64, tokio::sync::oneshot::Sender<serde_json::Value>>>>,
|
||||||
|
/// 请求 id 自增
|
||||||
|
next_id: AtomicU64,
|
||||||
|
/// 便携运行时安装/下载取消标志
|
||||||
|
runtime_cancel: Arc<AtomicBool>,
|
||||||
|
/// 正在执行的 pip/python 子进程 pid(取消时 taskkill)
|
||||||
|
install_pid: Arc<AtomicU64>,
|
||||||
|
/// 桥接启动互斥锁(防止并发 ensure_bridge 双重 spawn)
|
||||||
|
start_lock: Mutex<()>,
|
||||||
|
/// settings 内存缓存
|
||||||
|
settings_cache: Mutex<Option<SettingsCacheEntry>>,
|
||||||
|
/// 飞牛音乐(NAS)播放器运行期(连接 + 本地流代理)
|
||||||
|
feiniu: Feiniu,
|
||||||
|
/// AppHandle(桥接 reader 线程据此将事件转发给前端;setup 时设置)
|
||||||
|
app: Mutex<Option<AppHandle>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MusicManager {
|
||||||
|
pub fn new(app_data_dir: PathBuf) -> Self {
|
||||||
|
let root = app_data_dir.join("music");
|
||||||
|
for d in ["runtime", "outputs"] {
|
||||||
|
fs::create_dir_all(root.join(d)).ok();
|
||||||
|
}
|
||||||
|
let mut feiniu = Feiniu::default();
|
||||||
|
feiniu.set_cache_root(&app_data_dir);
|
||||||
|
Self {
|
||||||
|
root,
|
||||||
|
client: reqwest::Client::builder()
|
||||||
|
// 默认 30s 兜底超时;流式下载按块推进,不受此限制
|
||||||
|
.timeout(std::time::Duration::from_secs(30))
|
||||||
|
.build()
|
||||||
|
.unwrap_or_else(|_| reqwest::Client::new()),
|
||||||
|
bridge: Mutex::new(None),
|
||||||
|
pending: Arc::new(Mutex::new(HashMap::new())),
|
||||||
|
next_id: AtomicU64::new(1),
|
||||||
|
runtime_cancel: Arc::new(AtomicBool::new(false)),
|
||||||
|
install_pid: Arc::new(AtomicU64::new(0)),
|
||||||
|
start_lock: Mutex::new(()),
|
||||||
|
settings_cache: Mutex::new(None),
|
||||||
|
feiniu,
|
||||||
|
app: Mutex::new(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 设置 AppHandle(setup 阶段调用;桥接 reader 线程据此转发事件到前端)
|
||||||
|
pub fn set_app(&self, app: AppHandle) {
|
||||||
|
if let Ok(mut guard) = self.app.lock() {
|
||||||
|
*guard = Some(app);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn app_handle(&self) -> Option<AppHandle> {
|
||||||
|
self.app.lock().ok().and_then(|g| g.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 设置 ----------
|
||||||
|
/// 默认保存目录:系统「下载」目录(不可用时退回 {root}/outputs)
|
||||||
|
fn default_savedir(&self) -> String {
|
||||||
|
dirs::download_dir()
|
||||||
|
.unwrap_or_else(|| self.outputs_dir())
|
||||||
|
.to_string_lossy()
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_settings(&self) -> MusicSettings {
|
||||||
|
MusicSettings {
|
||||||
|
savedir: self.default_savedir(),
|
||||||
|
sources: DEFAULT_SOURCES.iter().map(|s| s.to_string()).collect(),
|
||||||
|
lyric_download: true,
|
||||||
|
cover_download: true,
|
||||||
|
use_proxy: false,
|
||||||
|
max_concurrent: 4,
|
||||||
|
download_engine: "musicdl".to_string(),
|
||||||
|
select_quality_on_download: false,
|
||||||
|
default_download_quality: "最高".to_string(), // 默认下载最高音质
|
||||||
|
feiniu_base_url: String::new(),
|
||||||
|
feiniu_token: String::new(),
|
||||||
|
feiniu_username: String::new(),
|
||||||
|
feiniu_device_id: String::new(),
|
||||||
|
feiniu_access_code: String::new(),
|
||||||
|
feiniu_connections: Vec::new(),
|
||||||
|
feiniu_active_id: String::new(),
|
||||||
|
feiniu_local_dirs: Vec::new(),
|
||||||
|
feiniu_cache_enabled: false,
|
||||||
|
feiniu_cache_max_gb: 5,
|
||||||
|
feiniu_play_mode: "stream".to_string(),
|
||||||
|
feiniu_library_nas_path: String::new(),
|
||||||
|
feiniu_auto_upload: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn settings_path(&self) -> PathBuf {
|
||||||
|
self.root.join("settings.json")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 读取设置(500ms 内存缓存;文件缺失/损坏时回退默认值)
|
||||||
|
pub fn load_settings(&self) -> MusicSettings {
|
||||||
|
if let Ok(cache) = self.settings_cache.lock() {
|
||||||
|
if let Some(entry) = cache.as_ref() {
|
||||||
|
if entry.read_at.elapsed() < Duration::from_millis(500) {
|
||||||
|
return entry.settings.clone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let defaults = self.default_settings();
|
||||||
|
let settings = fs::read_to_string(self.settings_path())
|
||||||
|
.ok()
|
||||||
|
.and_then(|s| serde_json::from_str::<MusicSettings>(&s).ok())
|
||||||
|
.unwrap_or_else(|| defaults.clone());
|
||||||
|
// 自愈:保存目录为空 / 源为空时补默认值
|
||||||
|
let mut settings = settings;
|
||||||
|
if settings.savedir.trim().is_empty() {
|
||||||
|
settings.savedir = defaults.savedir;
|
||||||
|
}
|
||||||
|
// 迁移:旧默认保存目录({root}/outputs)→ 系统下载目录
|
||||||
|
if settings.savedir == self.outputs_dir().to_string_lossy() {
|
||||||
|
settings.savedir = self.default_savedir();
|
||||||
|
}
|
||||||
|
if settings.sources.is_empty() {
|
||||||
|
settings.sources = defaults.sources;
|
||||||
|
}
|
||||||
|
// 飞牛音乐多连接迁移:旧单连接字段 → 连接列表
|
||||||
|
settings.migrate_feiniu();
|
||||||
|
if let Ok(mut cache) = self.settings_cache.lock() {
|
||||||
|
*cache = Some(SettingsCacheEntry {
|
||||||
|
read_at: Instant::now(),
|
||||||
|
settings: settings.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
settings
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 保存设置并更新缓存
|
||||||
|
pub fn save_settings(&self, settings: &MusicSettings) -> Result<(), String> {
|
||||||
|
let json = serde_json::to_string_pretty(settings).map_err(|e| format!("序列化设置失败: {}", e))?;
|
||||||
|
fs::write(self.settings_path(), json).map_err(|e| format!("写入设置失败: {}", e))?;
|
||||||
|
if let Ok(mut cache) = self.settings_cache.lock() {
|
||||||
|
*cache = Some(SettingsCacheEntry {
|
||||||
|
read_at: Instant::now(),
|
||||||
|
settings: settings.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 目录 ----------
|
||||||
|
pub fn runtime_dir(&self) -> PathBuf {
|
||||||
|
self.root.join("runtime")
|
||||||
|
}
|
||||||
|
/// 默认音乐下载目录
|
||||||
|
pub fn outputs_dir(&self) -> PathBuf {
|
||||||
|
self.root.join("outputs")
|
||||||
|
}
|
||||||
|
pub fn bridge_script_path(&self) -> PathBuf {
|
||||||
|
self.root.join("bridge.py")
|
||||||
|
}
|
||||||
|
pub fn bundled_python_exe(&self) -> PathBuf {
|
||||||
|
self.runtime_dir().join("python").join("python.exe")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Python 探测 ----------
|
||||||
|
/// 解析桥接要用的 Python 运行时。
|
||||||
|
/// 便携版优先:musicdl 只装入便携运行时,系统 Python 无法保证装有 musicdl;
|
||||||
|
/// 无便携版时退回系统 Python(此时 search 会报 musicdl 未安装,引导用户装便携版)。
|
||||||
|
pub fn resolve_python(&self) -> Result<PythonEnv, String> {
|
||||||
|
if let Some(env) = self.detect_bundled_python() {
|
||||||
|
return Ok(env);
|
||||||
|
}
|
||||||
|
if let Some(env) = detect_system_python() {
|
||||||
|
return Ok(env);
|
||||||
|
}
|
||||||
|
Err("未找到 Python 运行时:系统未安装 Python,且便携版未安装。请点击「安装便携版」".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 便携 Python 是否可用(exe 存在且能跑 --version)
|
||||||
|
pub fn detect_bundled_python(&self) -> Option<PythonEnv> {
|
||||||
|
detect_bundled_python_at(&self.bundled_python_exe())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 环境状态 ----------
|
||||||
|
/// 查询环境状态。子进程探测(python/musicdl/ffmpeg,便携 Python 冷启动可达数秒)
|
||||||
|
/// 放入阻塞线程池执行,避免阻塞主线程导致 UI 冻结。
|
||||||
|
pub async fn env_status(&self) -> Result<MusicEnvStatus, String> {
|
||||||
|
let bundled_exe = self.bundled_python_exe();
|
||||||
|
let bridge_running = self.bridge.lock().map(|b| b.is_some()).unwrap_or(false);
|
||||||
|
let runtime_dir = self.root.to_string_lossy().to_string();
|
||||||
|
let probe =
|
||||||
|
tauri::async_runtime::spawn_blocking(move || probe_env_blocking(bundled_exe))
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("环境探测任务失败: {}", e))?;
|
||||||
|
Ok(MusicEnvStatus {
|
||||||
|
python: probe.python,
|
||||||
|
python_source: probe.python_source.to_string(),
|
||||||
|
bundled_python: probe.bundled_python,
|
||||||
|
musicdl_installed: probe.musicdl_installed,
|
||||||
|
musicdl_version: probe.musicdl_version,
|
||||||
|
ffmpeg: probe.ffmpeg,
|
||||||
|
bridge_running,
|
||||||
|
runtime_dir,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 退出清理 ----------
|
||||||
|
/// 应用退出时停止桥接进程(stdin/stdout 随 child drop 关闭,reader 线程读到 EOF 自行退出)
|
||||||
|
pub fn cleanup_on_exit(&self) {
|
||||||
|
self.stop_bridge();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 内部工具 ----------
|
||||||
|
pub(crate) fn cancel(&self) {
|
||||||
|
self.runtime_cancel.store(true, Ordering::SeqCst);
|
||||||
|
let pid = self.install_pid.load(Ordering::SeqCst);
|
||||||
|
if pid != 0 {
|
||||||
|
// 杀掉正在执行的 pip/python 子进程,避免安装流程挂住
|
||||||
|
let _ = std::process::Command::new("taskkill")
|
||||||
|
.args(["/F", "/T", "/PID", &pid.to_string()])
|
||||||
|
.stdout(std::process::Stdio::null())
|
||||||
|
.stderr(std::process::Stdio::null())
|
||||||
|
.status();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn is_cancelled(&self) -> bool {
|
||||||
|
self.runtime_cancel.load(Ordering::SeqCst)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn start_lock(&self) -> &Mutex<()> {
|
||||||
|
&self.start_lock
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 环境探测结果(spawn_blocking 跨线程返回)
|
||||||
|
struct EnvProbe {
|
||||||
|
python: Option<String>,
|
||||||
|
python_source: &'static str,
|
||||||
|
bundled_python: Option<String>,
|
||||||
|
musicdl_installed: bool,
|
||||||
|
musicdl_version: Option<String>,
|
||||||
|
ffmpeg: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 阻塞式环境探测(串行 spawn 多个子进程,必须在阻塞线程池执行,禁止占用主线程)
|
||||||
|
fn probe_env_blocking(bundled_exe: PathBuf) -> EnvProbe {
|
||||||
|
let bundled = detect_bundled_python_at(&bundled_exe);
|
||||||
|
let sys_py = detect_system_python();
|
||||||
|
// 便携版优先(与 resolve_python 一致):musicdl 只装入便携运行时,
|
||||||
|
// 若按系统优先检查,装好便携版后 UI 仍会误报 musicdl 未安装
|
||||||
|
let python = bundled.as_ref().or(sys_py.as_ref());
|
||||||
|
|
||||||
|
let (musicdl_installed, musicdl_version) = match python {
|
||||||
|
Some(env) => check_musicdl(&env.exe),
|
||||||
|
None => (false, None),
|
||||||
|
};
|
||||||
|
EnvProbe {
|
||||||
|
python: python.map(|e| e.version.clone()),
|
||||||
|
python_source: match python {
|
||||||
|
Some(e) => e.source,
|
||||||
|
None => "none",
|
||||||
|
},
|
||||||
|
bundled_python: bundled.map(|e| e.exe.to_string_lossy().to_string()),
|
||||||
|
musicdl_installed,
|
||||||
|
musicdl_version,
|
||||||
|
ffmpeg: check_ffmpeg(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 指定路径的便携 Python 是否可用(exe 存在且能跑 --version)
|
||||||
|
fn detect_bundled_python_at(exe: &PathBuf) -> Option<PythonEnv> {
|
||||||
|
if !exe.exists() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let version = run_python_version(exe)?;
|
||||||
|
Some(PythonEnv {
|
||||||
|
source: "bundled",
|
||||||
|
exe: exe.clone(),
|
||||||
|
version,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 探测系统 Python:依次尝试 python / py / python3,解析 `--version` 输出。
|
||||||
|
/// 注意:Windows 的「应用商店别名」python 会在无安装时打印提示并以非零码退出,会被自然过滤。
|
||||||
|
fn detect_system_python() -> Option<PythonEnv> {
|
||||||
|
for candidate in ["python", "py", "python3"] {
|
||||||
|
let mut cmd = std::process::Command::new(candidate);
|
||||||
|
cmd.arg("--version");
|
||||||
|
crate::process_manager::setup_creation_flags(&mut cmd);
|
||||||
|
cmd.stdout(std::process::Stdio::piped())
|
||||||
|
.stderr(std::process::Stdio::piped())
|
||||||
|
.stdin(std::process::Stdio::null());
|
||||||
|
let out = cmd.output().ok()?;
|
||||||
|
let text = format!(
|
||||||
|
"{}{}",
|
||||||
|
String::from_utf8_lossy(&out.stdout),
|
||||||
|
String::from_utf8_lossy(&out.stderr)
|
||||||
|
);
|
||||||
|
if let Some(version) = parse_python_version(&text) {
|
||||||
|
return Some(PythonEnv {
|
||||||
|
source: "system",
|
||||||
|
exe: PathBuf::from(candidate),
|
||||||
|
version,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 运行 `python --version` 并解析版本号
|
||||||
|
fn run_python_version(exe: &PathBuf) -> Option<String> {
|
||||||
|
let mut cmd = std::process::Command::new(exe);
|
||||||
|
cmd.arg("--version");
|
||||||
|
crate::process_manager::setup_creation_flags(&mut cmd);
|
||||||
|
cmd.stdout(std::process::Stdio::piped())
|
||||||
|
.stderr(std::process::Stdio::piped())
|
||||||
|
.stdin(std::process::Stdio::null());
|
||||||
|
let out = cmd.output().ok()?;
|
||||||
|
let text = format!(
|
||||||
|
"{}{}",
|
||||||
|
String::from_utf8_lossy(&out.stdout),
|
||||||
|
String::from_utf8_lossy(&out.stderr)
|
||||||
|
);
|
||||||
|
parse_python_version(&text)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 从 "Python 3.14.5" 文本中提取 "3.14.5"
|
||||||
|
fn parse_python_version(text: &str) -> Option<String> {
|
||||||
|
text.split_whitespace().find_map(|w| {
|
||||||
|
let mut parts = w.split('.');
|
||||||
|
let major = parts.next()?.parse::<u32>().ok()?;
|
||||||
|
let minor = parts.next()?.parse::<u32>().ok()?;
|
||||||
|
if (major, minor) >= (3, 8) {
|
||||||
|
Some(w.to_string())
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 检查指定 Python 能否导入 musicdl(同步子进程调用,仅在设置页触发)
|
||||||
|
fn check_musicdl(exe: &PathBuf) -> (bool, Option<String>) {
|
||||||
|
let mut cmd = std::process::Command::new(exe);
|
||||||
|
cmd.args([
|
||||||
|
"-c",
|
||||||
|
"import musicdl; print(getattr(musicdl, '__version__', 'unknown'))",
|
||||||
|
]);
|
||||||
|
crate::process_manager::setup_creation_flags(&mut cmd);
|
||||||
|
cmd.stdout(std::process::Stdio::piped())
|
||||||
|
.stderr(std::process::Stdio::null())
|
||||||
|
.stdin(std::process::Stdio::null());
|
||||||
|
match cmd.output() {
|
||||||
|
Ok(out) if out.status.success() => {
|
||||||
|
let version = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||||
|
(true, Some(version))
|
||||||
|
}
|
||||||
|
_ => (false, None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 检查 FFmpeg 是否可用(部分海外音源需要,非必需)
|
||||||
|
fn check_ffmpeg() -> Option<String> {
|
||||||
|
let mut cmd = std::process::Command::new("ffmpeg");
|
||||||
|
cmd.arg("-version");
|
||||||
|
crate::process_manager::setup_creation_flags(&mut cmd);
|
||||||
|
cmd.stdout(std::process::Stdio::piped())
|
||||||
|
.stderr(std::process::Stdio::null())
|
||||||
|
.stdin(std::process::Stdio::null());
|
||||||
|
cmd.output()
|
||||||
|
.ok()
|
||||||
|
.and_then(|o| String::from_utf8(o.stdout).ok())
|
||||||
|
.and_then(|s| {
|
||||||
|
s.lines()
|
||||||
|
.next()
|
||||||
|
.map(|l| l.trim().to_string())
|
||||||
|
.filter(|l| !l.is_empty())
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,398 @@
|
|||||||
|
//! 便携 Python 运行时安装:流式下载 → 解压 → _pth 补丁 → get-pip 引导 → musicdl 安装。
|
||||||
|
//! 子模块通过 `impl super::MusicManager` 追加方法。
|
||||||
|
//!
|
||||||
|
//! 依赖下载源(已验证):
|
||||||
|
//! - https://www.python.org/ftp/python/{ver}/python-{ver}-embed-amd64.zip
|
||||||
|
//! - https://bootstrap.pypa.io/get-pip.py
|
||||||
|
//!
|
||||||
|
//! 取消:`MusicManager::cancel()` 置标志 + taskkill 当前 pip/python 子进程。
|
||||||
|
|
||||||
|
use std::fs;
|
||||||
|
use std::io::{Read, Write};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use futures_util::StreamExt;
|
||||||
|
use tauri::{AppHandle, Emitter};
|
||||||
|
|
||||||
|
use super::{MusicInstallProgress, MusicManager, PIP_INDEX_URL};
|
||||||
|
use crate::constants::events::MUSIC_RUNTIME_INSTALL_PROGRESS;
|
||||||
|
|
||||||
|
/// 用户主动取消安装的标记错误信息(前端据此静默处理)
|
||||||
|
pub(crate) const RUNTIME_CANCELLED: &str = "安装已取消";
|
||||||
|
|
||||||
|
impl MusicManager {
|
||||||
|
/// 安装便携 Python + musicdl(幂等:已就绪的步骤自动跳过),全程推送进度事件。
|
||||||
|
pub async fn install_runtime(&self, app: &AppHandle) -> Result<(), String> {
|
||||||
|
self.runtime_cancel.store(false, std::sync::atomic::Ordering::SeqCst);
|
||||||
|
let result = self.install_runtime_inner(app).await;
|
||||||
|
if let Err(ref e) = result {
|
||||||
|
if e != RUNTIME_CANCELLED {
|
||||||
|
let _ = app.emit(
|
||||||
|
MUSIC_RUNTIME_INSTALL_PROGRESS,
|
||||||
|
MusicInstallProgress {
|
||||||
|
stage: "error".into(),
|
||||||
|
percent: 0,
|
||||||
|
downloaded_bytes: 0,
|
||||||
|
total_bytes: None,
|
||||||
|
message: e.clone(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn install_runtime_inner(&self, app: &AppHandle) -> Result<(), String> {
|
||||||
|
let runtime_dir = self.runtime_dir();
|
||||||
|
fs::create_dir_all(&runtime_dir).map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
let python_exe = self.bundled_python_exe();
|
||||||
|
|
||||||
|
// ---------- 1. 便携 Python 已就绪则跳过下载/解压 ----------
|
||||||
|
if !(python_exe.exists() && super::run_python_version(&python_exe).is_some()) {
|
||||||
|
self.emit_progress(app, "download", 2, 0, None, "开始下载便携 Python...").await;
|
||||||
|
|
||||||
|
// 下载 embeddable zip(~11MB,流式写入)
|
||||||
|
let zip_path = runtime_dir.join(format!("python-{}-embed.zip", super::BUNDLED_PY_VERSION));
|
||||||
|
let zip_url = format!(
|
||||||
|
"https://www.python.org/ftp/python/{}/python-{}-embed-amd64.zip",
|
||||||
|
super::BUNDLED_PY_VERSION,
|
||||||
|
super::BUNDLED_PY_VERSION
|
||||||
|
);
|
||||||
|
self.download_stream(app, &zip_url, &zip_path).await?;
|
||||||
|
|
||||||
|
// 解压到 runtime/python/
|
||||||
|
self.emit_progress(app, "extract", 42, 0, None, "正在解压便携 Python...").await;
|
||||||
|
let python_dir = runtime_dir.join("python");
|
||||||
|
if python_dir.exists() {
|
||||||
|
fs::remove_dir_all(&python_dir).ok();
|
||||||
|
}
|
||||||
|
fs::create_dir_all(&python_dir).map_err(|e| e.to_string())?;
|
||||||
|
self.extract_zip(&zip_path, &python_dir)?;
|
||||||
|
fs::remove_file(&zip_path).ok();
|
||||||
|
|
||||||
|
// _pth 补丁:启用 site(否则无法识别 site-packages 与 pip)
|
||||||
|
self.emit_progress(app, "patch", 52, 0, None, "正在配置 Python 环境...").await;
|
||||||
|
self.patch_pth(&python_dir)?;
|
||||||
|
|
||||||
|
// 下载 get-pip.py 并引导 pip(只装 pip 本体,走官方源,包很小)
|
||||||
|
self.emit_progress(app, "pip", 54, 0, None, "正在引导 pip...").await;
|
||||||
|
let get_pip = runtime_dir.join("get-pip.py");
|
||||||
|
self.download_bytes(&"https://bootstrap.pypa.io/get-pip.py".to_string(), &get_pip)
|
||||||
|
.await?;
|
||||||
|
let pip_py = python_exe.clone();
|
||||||
|
let pip_py2 = pip_py.clone(); // 供 setuptools 步骤闭包使用(先于 move 克隆)
|
||||||
|
let get_pip2 = get_pip.clone();
|
||||||
|
self.run_blocking_step(
|
||||||
|
app,
|
||||||
|
"pip",
|
||||||
|
55,
|
||||||
|
60,
|
||||||
|
move |pid| {
|
||||||
|
let mut cmd = std::process::Command::new(&pip_py);
|
||||||
|
cmd.arg(&get_pip2).args(["--no-warn-script-location"]);
|
||||||
|
run_cmd_blocking(cmd, pid)
|
||||||
|
},
|
||||||
|
"正在安装 pip...",
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
fs::remove_file(&get_pip).ok();
|
||||||
|
|
||||||
|
// 安装 setuptools(musicdl 的 setup.py 构建依赖 setuptools.build_meta,
|
||||||
|
// 必须先于 musicdl 就位,否则构建阶段报 BackendUnavailable)
|
||||||
|
self.run_blocking_step(
|
||||||
|
app,
|
||||||
|
"pip",
|
||||||
|
62,
|
||||||
|
66,
|
||||||
|
move |pid| {
|
||||||
|
let mut cmd = std::process::Command::new(&pip_py2);
|
||||||
|
cmd.args([
|
||||||
|
"-m", "pip", "install", "--no-warn-script-location",
|
||||||
|
"--timeout", "60",
|
||||||
|
"--index-url", PIP_INDEX_URL,
|
||||||
|
"setuptools",
|
||||||
|
]);
|
||||||
|
run_cmd_blocking(cmd, pid)
|
||||||
|
},
|
||||||
|
"正在安装 setuptools...",
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
} else {
|
||||||
|
self.emit_progress(app, "check", 2, 0, None, "便携 Python 已就绪").await;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 2. 安装 musicdl(幂等:已安装则跳过) ----------
|
||||||
|
if !self.musicdl_ready(&python_exe).await {
|
||||||
|
let pip_py = python_exe.clone();
|
||||||
|
self.run_blocking_step(
|
||||||
|
app,
|
||||||
|
"musicdl",
|
||||||
|
68,
|
||||||
|
95,
|
||||||
|
move |pid| {
|
||||||
|
let mut cmd = std::process::Command::new(&pip_py);
|
||||||
|
cmd.args([
|
||||||
|
"-m", "pip", "install", "--no-warn-script-location",
|
||||||
|
"--timeout", "60",
|
||||||
|
"--index-url", PIP_INDEX_URL,
|
||||||
|
&format!("musicdl=={}", super::MUSICDL_VERSION),
|
||||||
|
]);
|
||||||
|
run_cmd_blocking(cmd, pid)
|
||||||
|
},
|
||||||
|
"正在安装 musicdl(下载依赖较多,可能需几分钟)...",
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.emit_progress(app, "done", 100, 0, None, "环境就绪").await;
|
||||||
|
crate::logger::log_info("music", "便携 Python + musicdl 安装完成");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 检查便携 Python 能否导入 musicdl
|
||||||
|
async fn musicdl_ready(&self, python_exe: &PathBuf) -> bool {
|
||||||
|
let exe = python_exe.clone();
|
||||||
|
let (ok, _) = super::check_musicdl(&exe);
|
||||||
|
ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 阶段工具 ----------
|
||||||
|
async fn emit_progress(
|
||||||
|
&self,
|
||||||
|
app: &AppHandle,
|
||||||
|
stage: &str,
|
||||||
|
percent: u32,
|
||||||
|
downloaded_bytes: u64,
|
||||||
|
total_bytes: Option<u64>,
|
||||||
|
message: &str,
|
||||||
|
) {
|
||||||
|
let _ = app.emit(
|
||||||
|
MUSIC_RUNTIME_INSTALL_PROGRESS,
|
||||||
|
MusicInstallProgress {
|
||||||
|
stage: stage.into(),
|
||||||
|
percent,
|
||||||
|
downloaded_bytes,
|
||||||
|
total_bytes,
|
||||||
|
message: message.into(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 流式下载(带取消 + 进度事件,percent 0-40 区间),复用内核下载模式
|
||||||
|
async fn download_stream(
|
||||||
|
&self,
|
||||||
|
app: &AppHandle,
|
||||||
|
url: &str,
|
||||||
|
dest: &Path,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let resp = self
|
||||||
|
.client
|
||||||
|
.get(url)
|
||||||
|
.timeout(std::time::Duration::from_secs(300))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("请求下载失败: {}", e))?;
|
||||||
|
let status = resp.status();
|
||||||
|
if !status.is_success() {
|
||||||
|
return Err(format!("下载返回 HTTP {}", status.as_u16()));
|
||||||
|
}
|
||||||
|
let total: Option<u64> = resp.content_length();
|
||||||
|
let mut file = fs::File::create(dest).map_err(|e| format!("创建文件失败: {}", e))?;
|
||||||
|
let mut stream = resp.bytes_stream();
|
||||||
|
let mut downloaded: u64 = 0;
|
||||||
|
let mut last_percent: u32 = 0;
|
||||||
|
while let Some(chunk) = stream.next().await {
|
||||||
|
if self.is_cancelled() {
|
||||||
|
drop(file);
|
||||||
|
fs::remove_file(dest).ok();
|
||||||
|
return Err(RUNTIME_CANCELLED.to_string());
|
||||||
|
}
|
||||||
|
let chunk = chunk.map_err(|e| format!("下载中断: {}", e))?;
|
||||||
|
file.write_all(&chunk).map_err(|e| format!("写入文件失败: {}", e))?;
|
||||||
|
downloaded += chunk.len() as u64;
|
||||||
|
let percent = total
|
||||||
|
.filter(|t| *t > 0)
|
||||||
|
.map(|t| ((downloaded as f64 / t as f64) * 38.0) as u32)
|
||||||
|
.unwrap_or(0)
|
||||||
|
.min(38);
|
||||||
|
if percent >= last_percent + 1 {
|
||||||
|
last_percent = percent;
|
||||||
|
self.emit_progress(
|
||||||
|
app,
|
||||||
|
"download",
|
||||||
|
percent,
|
||||||
|
downloaded,
|
||||||
|
total,
|
||||||
|
&format!("正在下载便携 Python ({:.1} MB)", downloaded as f64 / 1048576.0),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
file.flush().ok();
|
||||||
|
self.emit_progress(app, "download", 40, downloaded, total, "下载完成").await;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 小文件整体下载(get-pip.py),无进度
|
||||||
|
async fn download_bytes(&self, url: &str, dest: &Path) -> Result<(), String> {
|
||||||
|
let resp = self
|
||||||
|
.client
|
||||||
|
.get(url)
|
||||||
|
.timeout(std::time::Duration::from_secs(120))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("请求下载失败: {}", e))?;
|
||||||
|
let status = resp.status();
|
||||||
|
if !status.is_success() {
|
||||||
|
return Err(format!("下载返回 HTTP {}", status.as_u16()));
|
||||||
|
}
|
||||||
|
let bytes = resp.bytes().await.map_err(|e| format!("读取响应失败: {}", e))?;
|
||||||
|
fs::write(dest, &bytes).map_err(|e| format!("写入文件失败: {}", e))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 解压 zip(复用内核解压逻辑)
|
||||||
|
fn extract_zip(&self, zip_path: &Path, dest: &Path) -> Result<(), String> {
|
||||||
|
let file = fs::File::open(zip_path).map_err(|e| format!("打开 zip 失败: {}", e))?;
|
||||||
|
let mut archive = zip::ZipArchive::new(file).map_err(|e| format!("读取 zip 失败: {}", e))?;
|
||||||
|
for i in 0..archive.len() {
|
||||||
|
let mut entry = archive
|
||||||
|
.by_index(i)
|
||||||
|
.map_err(|e| format!("读取条目失败: {}", e))?;
|
||||||
|
let outpath = match entry.enclosed_name() {
|
||||||
|
Some(p) => dest.join(p),
|
||||||
|
None => continue,
|
||||||
|
};
|
||||||
|
if entry.is_dir() {
|
||||||
|
fs::create_dir_all(&outpath).map_err(|e| e.to_string())?;
|
||||||
|
} else {
|
||||||
|
if let Some(parent) = outpath.parent() {
|
||||||
|
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
|
let mut outfile = fs::File::create(&outpath).map_err(|e| e.to_string())?;
|
||||||
|
let mut buf = [0u8; 8192];
|
||||||
|
loop {
|
||||||
|
let n = entry.read(&mut buf).map_err(|e| e.to_string())?;
|
||||||
|
if n == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
outfile.write_all(&buf[..n]).map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 修改 pythonXY._pth:启用 `import site`(embeddable 默认注释掉,
|
||||||
|
/// 不启用则无法识别 site-packages / pip 安装的包)
|
||||||
|
fn patch_pth(&self, python_dir: &Path) -> Result<(), String> {
|
||||||
|
let entries = fs::read_dir(python_dir).map_err(|e| e.to_string())?;
|
||||||
|
let pth = entries
|
||||||
|
.filter_map(|e| e.ok())
|
||||||
|
.map(|e| e.path())
|
||||||
|
.find(|p| {
|
||||||
|
p.extension()
|
||||||
|
.and_then(|e| e.to_str())
|
||||||
|
.map(|e| e.eq_ignore_ascii_case("_pth"))
|
||||||
|
.unwrap_or(false)
|
||||||
|
})
|
||||||
|
.ok_or_else(|| "解压目录中未找到 ._pth 文件".to_string())?;
|
||||||
|
|
||||||
|
let content = fs::read_to_string(&pth).map_err(|e| e.to_string())?;
|
||||||
|
let mut patched = content.replace("#import site", "import site");
|
||||||
|
if !patched.contains("import site") {
|
||||||
|
patched.push_str("import site\n");
|
||||||
|
}
|
||||||
|
// 显式把 site-packages 加入 sys.path(pip 默认安装位置)
|
||||||
|
if !patched.contains("Lib\\site-packages") && !patched.contains("Lib/site-packages") {
|
||||||
|
patched.push_str("Lib\\site-packages\n");
|
||||||
|
}
|
||||||
|
fs::write(&pth, patched).map_err(|e| format!("写入 _pth 失败: {}", e))?;
|
||||||
|
crate::logger::log_info("music", &format!("已补丁 _pth: {}", pth.display()));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 执行一个阻塞子进程步骤(get-pip / setuptools / musicdl),带进度推送、取消检查与超时看门狗。
|
||||||
|
/// start_percent / end_percent:本步骤的进度区间(完成前推进到 end_percent)。
|
||||||
|
/// run 闭包接收「子进程 pid 记录器」,供取消时 taskkill。
|
||||||
|
async fn run_blocking_step<F>(
|
||||||
|
&self,
|
||||||
|
app: &AppHandle,
|
||||||
|
stage: &str,
|
||||||
|
start_percent: u32,
|
||||||
|
end_percent: u32,
|
||||||
|
run: F,
|
||||||
|
msg: &str,
|
||||||
|
) -> Result<(), String>
|
||||||
|
where
|
||||||
|
F: FnOnce(Arc<std::sync::atomic::AtomicU64>) -> Result<(), String> + Send + 'static,
|
||||||
|
{
|
||||||
|
if self.is_cancelled() {
|
||||||
|
return Err(RUNTIME_CANCELLED.to_string());
|
||||||
|
}
|
||||||
|
let pid_ref = self.install_pid.clone();
|
||||||
|
self.emit_progress(app, stage, start_percent, 0, None, msg).await;
|
||||||
|
let result = tauri::async_runtime::spawn_blocking(move || run(pid_ref.clone()))
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("任务执行失败: {}", e))?;
|
||||||
|
self.install_pid.store(0, std::sync::atomic::Ordering::SeqCst);
|
||||||
|
if self.is_cancelled() {
|
||||||
|
return Err(RUNTIME_CANCELLED.to_string());
|
||||||
|
}
|
||||||
|
result?;
|
||||||
|
self.emit_progress(app, stage, end_percent, 0, None, "完成").await;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 同步运行子进程,带超时看门狗(超时 taskkill),并记录 pid 供取消。
|
||||||
|
/// 输出(stdout+stderr 尾部)写入日志;失败返回错误信息。
|
||||||
|
fn run_cmd_blocking(
|
||||||
|
mut cmd: std::process::Command,
|
||||||
|
pid_ref: Arc<std::sync::atomic::AtomicU64>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
cmd.stdout(std::process::Stdio::piped())
|
||||||
|
.stderr(std::process::Stdio::piped())
|
||||||
|
.stdin(std::process::Stdio::null());
|
||||||
|
crate::process_manager::setup_creation_flags(&mut cmd);
|
||||||
|
|
||||||
|
let child = cmd.spawn().map_err(|e| format!("启动子进程失败: {}", e))?;
|
||||||
|
pid_ref.store(child.id() as u64, std::sync::atomic::Ordering::SeqCst);
|
||||||
|
|
||||||
|
// 超时看门狗:30 分钟后仍未结束则强杀(慢网络下 pip 装 musicdl 依赖可能超过 10 分钟)
|
||||||
|
let pid = child.id();
|
||||||
|
let (tx, rx) = std::sync::mpsc::channel::<()>();
|
||||||
|
let watcher = std::thread::spawn(move || {
|
||||||
|
if rx.recv_timeout(std::time::Duration::from_secs(1800)).is_err() {
|
||||||
|
let _ = std::process::Command::new("taskkill")
|
||||||
|
.args(["/F", "/T", "/PID", &pid.to_string()])
|
||||||
|
.stdout(std::process::Stdio::null())
|
||||||
|
.stderr(std::process::Stdio::null())
|
||||||
|
.status();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let output = child.wait_with_output();
|
||||||
|
let _ = tx.send(());
|
||||||
|
let _ = watcher.join();
|
||||||
|
|
||||||
|
match output {
|
||||||
|
Ok(out) => {
|
||||||
|
let text = format!(
|
||||||
|
"{}{}",
|
||||||
|
String::from_utf8_lossy(&out.stdout),
|
||||||
|
String::from_utf8_lossy(&out.stderr)
|
||||||
|
);
|
||||||
|
if out.status.success() {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
// 截取尾部 800 字符,便于定位 pip 报错
|
||||||
|
let tail: String = text.chars().rev().take(800).collect::<String>().chars().rev().collect();
|
||||||
|
Err(format!("子进程退出码 {}: {}", out.status.code().unwrap_or(-1), tail))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => Err(format!("读取子进程输出失败: {}", e)),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -127,8 +127,9 @@ pub fn setup_creation_flags(_cmd: &mut Command) {
|
|||||||
|
|
||||||
/// 将已启动的子进程加入 Job Object(异常退出时自动清理)
|
/// 将已启动的子进程加入 Job Object(异常退出时自动清理)
|
||||||
/// 在 Windows 上调用,非 Windows 平台为空操作
|
/// 在 Windows 上调用,非 Windows 平台为空操作
|
||||||
|
/// pub(crate):音乐模块的桥接进程(自管 stdio,不走 ProcessManager)也需加入 Job
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
fn assign_to_job(child: &Child) {
|
pub(crate) fn assign_to_job(child: &Child) {
|
||||||
use std::os::windows::io::AsRawHandle;
|
use std::os::windows::io::AsRawHandle;
|
||||||
if let Some(job) = get_job_handle() {
|
if let Some(job) = get_job_handle() {
|
||||||
let child_handle = child.as_raw_handle() as winapi::HANDLE;
|
let child_handle = child.as_raw_handle() as winapi::HANDLE;
|
||||||
|
|||||||
@@ -18,9 +18,9 @@
|
|||||||
use std::sync::Mutex;
|
use std::sync::Mutex;
|
||||||
use windows_sys::Win32::Foundation::{BOOL, HWND, POINT, RECT};
|
use windows_sys::Win32::Foundation::{BOOL, HWND, POINT, RECT};
|
||||||
use windows_sys::Win32::Graphics::Gdi::{
|
use windows_sys::Win32::Graphics::Gdi::{
|
||||||
BitBlt, CreateCompatibleBitmap, CreateCompatibleDC, DeleteDC, DeleteObject, GetDC, GetDIBits,
|
BitBlt, CombineRgn, CreateCompatibleBitmap, CreateCompatibleDC, CreateRectRgn, DeleteDC,
|
||||||
PatBlt, ReleaseDC, SelectObject, BITMAPINFO, BITMAPINFOHEADER, BLACKNESS, DIB_RGB_COLORS,
|
DeleteObject, GetDC, GetDIBits, PatBlt, ReleaseDC, SelectObject, SetWindowRgn, BITMAPINFO,
|
||||||
RGBQUAD, SRCCOPY,
|
BITMAPINFOHEADER, BLACKNESS, DIB_RGB_COLORS, RGBQUAD, RGN_DIFF, SRCCOPY,
|
||||||
};
|
};
|
||||||
use windows_sys::Win32::Storage::Xps::PrintWindow;
|
use windows_sys::Win32::Storage::Xps::PrintWindow;
|
||||||
use windows_sys::Win32::System::DataExchange::{
|
use windows_sys::Win32::System::DataExchange::{
|
||||||
@@ -34,7 +34,7 @@ use windows_sys::Win32::UI::WindowsAndMessaging::{
|
|||||||
WS_EX_TOOLWINDOW,
|
WS_EX_TOOLWINDOW,
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::{CaptureData, ScreenRect, WindowInfo};
|
use super::{CaptureData, ScreenRect, ScrollRegion, WindowInfo};
|
||||||
|
|
||||||
/// 捕获结果(PNG 字节 + 原始 BGRA 像素,像素用于剪贴板 DIB 构造,避免重复解码)
|
/// 捕获结果(PNG 字节 + 原始 BGRA 像素,像素用于剪贴板 DIB 构造,避免重复解码)
|
||||||
pub struct CapturedImage {
|
pub struct CapturedImage {
|
||||||
@@ -406,6 +406,71 @@ pub fn disable_window_transitions(hwnd: isize) -> Result<(), String> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 滚动截图模式:在覆盖层窗口上挖出选区带的"真孔"(内缩 INSET 保留蓝框),或清除恢复整窗。
|
||||||
|
///
|
||||||
|
/// 背景:Chromium 系浏览器(Edge/Chrome)的原生窗口遮挡检测(occlusion tracking)
|
||||||
|
/// 会把被**完全覆盖**的窗口标记为 occluded 并暂停渲染合成——滚动截图时覆盖层
|
||||||
|
/// 铺满全屏盖住目标窗口,网页"看起来完全不滚动",PrintWindow 抓到的也是静止帧。
|
||||||
|
/// 覆盖层并非 layered 窗口,即使其内容视觉透明,窗口矩形对遮挡检测仍算不透明覆盖。
|
||||||
|
/// 挖孔后目标窗口仅部分被覆盖(Chromium 要求完全覆盖才判 occluded,实测 60x60
|
||||||
|
/// 的小孔即可解除),恢复渲染与滚轮响应,拼接匹配随之正常。
|
||||||
|
///
|
||||||
|
/// - `region = Some`:孔 = 选区带内缩 INSET(保留 2px 蓝框 + 1px 白描边);
|
||||||
|
/// 选区过小(< 2*INSET+8)时不挖孔,避免退化区域
|
||||||
|
/// - `region = None`:SetWindowRgn(NULL) 清除窗口区域(恢复整窗)
|
||||||
|
///
|
||||||
|
/// 坐标:region 为屏幕物理像素(与滚动会话同源),按覆盖层窗口原点换算成窗口坐标。
|
||||||
|
/// 区域设置在窗口上持续有效,会话结束/新一轮截图开始时必须传 None 复位。
|
||||||
|
pub fn set_scroll_hole(hwnd: isize, region: Option<ScrollRegion>) -> Result<(), String> {
|
||||||
|
unsafe {
|
||||||
|
match region {
|
||||||
|
Some(r) => {
|
||||||
|
let mut wr: RECT = std::mem::zeroed();
|
||||||
|
if GetWindowRect(hwnd, &mut wr) == 0 {
|
||||||
|
return Err("GetWindowRect 失败".into());
|
||||||
|
}
|
||||||
|
const INSET: i32 = 4;
|
||||||
|
let hx1 = r.x - wr.left + INSET;
|
||||||
|
let hy1 = r.y - wr.top + INSET;
|
||||||
|
let hx2 = r.x + r.width - wr.left - INSET;
|
||||||
|
let hy2 = r.y + r.height - wr.top - INSET;
|
||||||
|
if hx2 - hx1 < 8 || hy2 - hy1 < 8 {
|
||||||
|
// 选区太小:不挖孔(保持整窗)
|
||||||
|
if SetWindowRgn(hwnd, 0, 1) == 0 {
|
||||||
|
return Err("SetWindowRgn 失败".into());
|
||||||
|
}
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let full = CreateRectRgn(0, 0, wr.right - wr.left, wr.bottom - wr.top);
|
||||||
|
let hole = CreateRectRgn(hx1, hy1, hx2, hy2);
|
||||||
|
if full == 0 || hole == 0 {
|
||||||
|
if full != 0 {
|
||||||
|
DeleteObject(full);
|
||||||
|
}
|
||||||
|
if hole != 0 {
|
||||||
|
DeleteObject(hole);
|
||||||
|
}
|
||||||
|
return Err("CreateRectRgn 失败".into());
|
||||||
|
}
|
||||||
|
CombineRgn(full, full, hole, RGN_DIFF);
|
||||||
|
// 组合结果 full 归 SetWindowRgn 所有;hole 用完即删
|
||||||
|
DeleteObject(hole);
|
||||||
|
if SetWindowRgn(hwnd, full, 1) == 0 {
|
||||||
|
DeleteObject(full);
|
||||||
|
return Err("SetWindowRgn 失败".into());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
if SetWindowRgn(hwnd, 0, 1) == 0 {
|
||||||
|
return Err("SetWindowRgn 失败".into());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// 枚举所有可见、有标题的顶层窗口(供窗口列表选择)
|
/// 枚举所有可见、有标题的顶层窗口(供窗口列表选择)
|
||||||
pub fn enum_visible_windows() -> Vec<WindowInfo> {
|
pub fn enum_visible_windows() -> Vec<WindowInfo> {
|
||||||
extern "system" fn enum_proc(hwnd: HWND, lparam: isize) -> i32 {
|
extern "system" fn enum_proc(hwnd: HWND, lparam: isize) -> i32 {
|
||||||
|
|||||||
@@ -10,6 +10,9 @@
|
|||||||
//! - screenshot_show_overlay:一次 IPC 完成覆盖层 show + focus(关键路径减少往返)
|
//! - screenshot_show_overlay:一次 IPC 完成覆盖层 show + focus(关键路径减少往返)
|
||||||
//! - screenshot_enum_windows:枚举可见顶层窗口
|
//! - screenshot_enum_windows:枚举可见顶层窗口
|
||||||
//! - screenshot_capture_window:按 hwnd 捕获指定窗口
|
//! - screenshot_capture_window:按 hwnd 捕获指定窗口
|
||||||
|
//! - screenshot_scroll_capture / screenshot_scroll_start / screenshot_scroll_finish /
|
||||||
|
//! screenshot_scroll_cancel:滚动截图(同步一次调用 / 会话式:启动、完成、取消)
|
||||||
|
//! - screenshot_set_scroll_hole:滚动模式遮罩挖孔(防 Chromium 遮挡检测冻结目标窗口)
|
||||||
//! - screenshot_take_editor_image_raw:取出编辑器图片(raw IPC,滚动截图会话直接写入)
|
//! - screenshot_take_editor_image_raw:取出编辑器图片(raw IPC,滚动截图会话直接写入)
|
||||||
//! - screenshot_compose_png / screenshot_compose_copy:raw RGBA → PNG(仅编码 / 剪贴板+编码)
|
//! - screenshot_compose_png / screenshot_compose_copy:raw RGBA → PNG(仅编码 / 剪贴板+编码)
|
||||||
//! - screenshot_copy_image:写入剪贴板(CF_DIB)
|
//! - screenshot_copy_image:写入剪贴板(CF_DIB)
|
||||||
@@ -372,6 +375,54 @@ pub fn screenshot_scroll_cancel() -> Result<(), String> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 滚动模式遮罩挖孔:在截图覆盖层窗口上挖出选区带的真孔(region = None 时复位整窗)。
|
||||||
|
///
|
||||||
|
/// Chromium 系浏览器(Edge/Chrome)的窗口遮挡检测会把被完全覆盖的窗口标记为
|
||||||
|
/// occluded 并暂停渲染——滚动截图时覆盖层铺满全屏,网页"看起来完全不滚动"。
|
||||||
|
/// 挖孔后目标窗口仅部分被覆盖,恢复渲染与滚轮响应(详见 capture::set_scroll_hole)。
|
||||||
|
/// 进入滚动模式时带选区调用,会话结束/新一轮截图开始时必须传 None 复位。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub fn screenshot_set_scroll_hole(
|
||||||
|
app: AppHandle,
|
||||||
|
region: Option<super::ScrollRegion>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
use raw_window_handle::HasWindowHandle;
|
||||||
|
|
||||||
|
let mut hwnds: Vec<isize> = Vec::new();
|
||||||
|
for (label, win) in app.webview_windows() {
|
||||||
|
if label.starts_with(crate::constants::windows::SCREENSHOT_OVERLAY) {
|
||||||
|
let hwnd = win
|
||||||
|
.window_handle()
|
||||||
|
.ok()
|
||||||
|
.and_then(|h| match h.as_raw() {
|
||||||
|
raw_window_handle::RawWindowHandle::Win32(w) => {
|
||||||
|
Some(w.hwnd.get() as isize)
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
});
|
||||||
|
if let Some(h) = hwnd {
|
||||||
|
hwnds.push(h);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if hwnds.is_empty() {
|
||||||
|
return Err("截图覆盖层窗口不存在".into());
|
||||||
|
}
|
||||||
|
for h in hwnds {
|
||||||
|
super::capture::set_scroll_hole(h, region)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
{
|
||||||
|
let _ = (app, region);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// 取出编辑器图片(原始 PNG 字节,raw IPC → 前端 ArrayBuffer → Blob URL,取出即清除)
|
/// 取出编辑器图片(原始 PNG 字节,raw IPC → 前端 ArrayBuffer → Blob URL,取出即清除)
|
||||||
///
|
///
|
||||||
/// 长图(滚动截图)可达数十 MB:raw IPC 相比 base64 JSON 事件传输省 ~33% 体积,
|
/// 长图(滚动截图)可达数十 MB:raw IPC 相比 base64 JSON 事件传输省 ~33% 体积,
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ use crate::download_engine::{DownloadEngine, ExtensionServer};
|
|||||||
use crate::logger::LogManager;
|
use crate::logger::LogManager;
|
||||||
use crate::mihomo_manager::MihomoManager;
|
use crate::mihomo_manager::MihomoManager;
|
||||||
use crate::monitor_kernel::{MonitorKernel, check_and_relaunch_if_needed};
|
use crate::monitor_kernel::{MonitorKernel, check_and_relaunch_if_needed};
|
||||||
|
use crate::music::MusicManager;
|
||||||
use crate::network_monitor::NetworkMonitor;
|
use crate::network_monitor::NetworkMonitor;
|
||||||
use crate::process_manager::{ProcessManager, start_monitoring_thread};
|
use crate::process_manager::{ProcessManager, start_monitoring_thread};
|
||||||
|
|
||||||
@@ -53,6 +54,13 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
let monitor = MonitorKernel::new(app_data_dir.clone());
|
let monitor = MonitorKernel::new(app_data_dir.clone());
|
||||||
app.manage(monitor);
|
app.manage(monitor);
|
||||||
|
|
||||||
|
// ===== 音乐模块:MusicManager(Python 运行时 + 桥接进程) =====
|
||||||
|
// 仅注册状态,不主动启动桥接(由前端模块激活/首次请求时按需拉起)
|
||||||
|
let music = MusicManager::new(app_data_dir.clone());
|
||||||
|
// 注入 AppHandle:桥接 reader 线程把下载事件行转发给前端
|
||||||
|
music.set_app(app.handle().clone());
|
||||||
|
app.manage(music);
|
||||||
|
|
||||||
// 网速采样不依赖提权,应用启动即开始
|
// 网速采样不依赖提权,应用启动即开始
|
||||||
let network_monitor = Arc::new(NetworkMonitor::new());
|
let network_monitor = Arc::new(NetworkMonitor::new());
|
||||||
app.manage(network_monitor.clone());
|
app.manage(network_monitor.clone());
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "thing",
|
"productName": "thing",
|
||||||
"version": "26.8.5",
|
"version": "26.9.1",
|
||||||
"identifier": "thing.lfeng.me",
|
"identifier": "thing.lfeng.me",
|
||||||
"build": {
|
"build": {
|
||||||
"beforeDevCommand": "bun run dev",
|
"beforeDevCommand": "bun run dev",
|
||||||
|
|||||||
@@ -241,6 +241,21 @@ export const commands = {
|
|||||||
downloaderInspect: (input: string) => __TAURI_INVOKE<TorrentInfo>("downloader_inspect", { input }),
|
downloaderInspect: (input: string) => __TAURI_INVOKE<TorrentInfo>("downloader_inspect", { input }),
|
||||||
/** 磁力任务:元数据解析成功后,用户勾选文件并确认开始下载 */
|
/** 磁力任务:元数据解析成功后,用户勾选文件并确认开始下载 */
|
||||||
downloaderSelectBtFiles: (id: string, onlyFiles: number[]) => __TAURI_INVOKE<null>("downloader_select_bt_files", { id, onlyFiles }),
|
downloaderSelectBtFiles: (id: string, onlyFiles: number[]) => __TAURI_INVOKE<null>("downloader_select_bt_files", { id, onlyFiles }),
|
||||||
|
/**
|
||||||
|
* 查询环境状态(Python / musicdl / FFmpeg / 桥接进程),设置页「环境检查」面板调用。
|
||||||
|
* 异步命令:子进程探测在阻塞线程池执行,避免冻结主线程/UI。
|
||||||
|
*/
|
||||||
|
musicEnvStatus: () => __TAURI_INVOKE<MusicEnvStatus>("music_env_status"),
|
||||||
|
/** 安装便携 Python + musicdl(幂等),全程推送 music-runtime-install-progress 事件 */
|
||||||
|
musicInstallRuntime: () => __TAURI_INVOKE<MusicEnvStatus>("music_install_runtime"),
|
||||||
|
/** 取消便携运行时安装/下载 */
|
||||||
|
musicCancelRuntimeInstall: () => __TAURI_INVOKE<null>("music_cancel_runtime_install"),
|
||||||
|
/** 停止桥接进程 */
|
||||||
|
musicStopBridge: () => __TAURI_INVOKE<null>("music_stop_bridge"),
|
||||||
|
/** 读取音乐模块设置 */
|
||||||
|
musicGetSettings: () => __TAURI_INVOKE<MusicSettings>("music_get_settings"),
|
||||||
|
/** 保存音乐模块设置(立即生效) */
|
||||||
|
musicSaveSettings: (settings: MusicSettings) => __TAURI_INVOKE<null>("music_save_settings", { settings }),
|
||||||
/** 禁用指定窗口(按 label 查找)的显示/隐藏过渡动画,消除覆盖层出现/消失时的缩放动画 */
|
/** 禁用指定窗口(按 label 查找)的显示/隐藏过渡动画,消除覆盖层出现/消失时的缩放动画 */
|
||||||
screenshotDisableTransitions: (label: string) => __TAURI_INVOKE<null>("screenshot_disable_transitions", { label }),
|
screenshotDisableTransitions: (label: string) => __TAURI_INVOKE<null>("screenshot_disable_transitions", { label }),
|
||||||
/** 一次 IPC 完成指定窗口的显示与聚焦(截图覆盖层显示关键路径,减少串行往返) */
|
/** 一次 IPC 完成指定窗口的显示与聚焦(截图覆盖层显示关键路径,减少串行往返) */
|
||||||
@@ -305,6 +320,20 @@ export const commands = {
|
|||||||
width: number,
|
width: number,
|
||||||
height: number,
|
height: number,
|
||||||
} | null, auto: boolean) => __TAURI_INVOKE<null>("screenshot_scroll_start", { hwnd, region, auto }),
|
} | null, auto: boolean) => __TAURI_INVOKE<null>("screenshot_scroll_start", { hwnd, region, auto }),
|
||||||
|
/**
|
||||||
|
* 滚动模式遮罩挖孔:在截图覆盖层窗口上挖出选区带的真孔(region = None 时复位整窗)。
|
||||||
|
*
|
||||||
|
* Chromium 系浏览器(Edge/Chrome)的窗口遮挡检测会把被完全覆盖的窗口标记为
|
||||||
|
* occluded 并暂停渲染——滚动截图时覆盖层铺满全屏,网页"看起来完全不滚动"。
|
||||||
|
* 挖孔后目标窗口仅部分被覆盖,恢复渲染与滚轮响应(详见 capture::set_scroll_hole)。
|
||||||
|
* 进入滚动模式时带选区调用,会话结束/新一轮截图开始时必须传 None 复位。
|
||||||
|
*/
|
||||||
|
screenshotSetScrollHole: (region: {
|
||||||
|
x: number,
|
||||||
|
y: number,
|
||||||
|
width: number,
|
||||||
|
height: number,
|
||||||
|
} | null) => __TAURI_INVOKE<null>("screenshot_set_scroll_hole", { region }),
|
||||||
/** 将 PNG base64 写入系统剪贴板(转 CF_DIB) */
|
/** 将 PNG base64 写入系统剪贴板(转 CF_DIB) */
|
||||||
screenshotCopyImage: (pngBase64: string) => __TAURI_INVOKE<null>("screenshot_copy_image", { pngBase64 }),
|
screenshotCopyImage: (pngBase64: string) => __TAURI_INVOKE<null>("screenshot_copy_image", { pngBase64 }),
|
||||||
/** 将 PNG base64 写入文件 */
|
/** 将 PNG base64 写入文件 */
|
||||||
@@ -522,6 +551,24 @@ export type ExtractResult = {
|
|||||||
error: string,
|
error: string,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** 一条飞牛音乐连接(持久化在 `MusicSettings`)。 */
|
||||||
|
export type FeiniuConnection = {
|
||||||
|
id: string,
|
||||||
|
name: string,
|
||||||
|
/** "lan" | "frp" | "fnconnect"(fnconnect 预留) */
|
||||||
|
kind: string,
|
||||||
|
/** 服务器地址(http://192.168.x.x:5666 或 https://域名) */
|
||||||
|
baseUrl: string,
|
||||||
|
username: string,
|
||||||
|
token: string,
|
||||||
|
deviceId: string,
|
||||||
|
accessCode: string,
|
||||||
|
/** https 遇到自签证书时忽略校验 */
|
||||||
|
insecure: boolean,
|
||||||
|
/** fnconnect 连接的 fnId(如 fnos.net/<id> 或裸 id) */
|
||||||
|
fnId?: string,
|
||||||
|
};
|
||||||
|
|
||||||
export type FileEntry = {
|
export type FileEntry = {
|
||||||
name: string,
|
name: string,
|
||||||
path: string,
|
path: string,
|
||||||
@@ -564,6 +611,74 @@ export type KernelUpdateInfo = {
|
|||||||
hasUpdate: boolean,
|
hasUpdate: boolean,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** 环境状态(返回前端,设置页「环境检查」面板展示) */
|
||||||
|
export type MusicEnvStatus = {
|
||||||
|
/** 系统 Python 版本(如 "3.14.5"),无则 None */
|
||||||
|
python: string | null,
|
||||||
|
/** python 来源:"system" | "bundled" | "none" */
|
||||||
|
pythonSource: string,
|
||||||
|
/** 便携 Python 可执行文件路径(未安装则 None) */
|
||||||
|
bundledPython: string | null,
|
||||||
|
/** musicdl 是否可导入 */
|
||||||
|
musicdlInstalled: boolean,
|
||||||
|
/** musicdl 版本 */
|
||||||
|
musicdlVersion: string | null,
|
||||||
|
/** FFmpeg 是否可用(部分音源需要,非必需) */
|
||||||
|
ffmpeg: string | null,
|
||||||
|
/** 桥接进程是否在运行 */
|
||||||
|
bridgeRunning: boolean,
|
||||||
|
/** 运行时目录({app_data_dir}/music) */
|
||||||
|
runtimeDir: string,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 音乐模块设置(settings.json 持久化;变更即时生效) */
|
||||||
|
export type MusicSettings = {
|
||||||
|
/** 下载保存目录 */
|
||||||
|
savedir: string,
|
||||||
|
/** 搜索源(musicdl 客户端名,如 NeteaseMusicClient) */
|
||||||
|
sources: string[],
|
||||||
|
/** 下载时同步保存歌词 */
|
||||||
|
lyricDownload: boolean,
|
||||||
|
/** 下载时同步保存封面 */
|
||||||
|
coverDownload: boolean,
|
||||||
|
/** 搜索/下载请求是否走代理模块(mihomo mixed 端口) */
|
||||||
|
useProxy: boolean,
|
||||||
|
/** 最大并发下载数 */
|
||||||
|
maxConcurrent: number,
|
||||||
|
/** 下载引擎:"musicdl" | "rust"(P2 生效) */
|
||||||
|
downloadEngine: string,
|
||||||
|
/** 下载时是否弹窗选择音质(默认关;开启后点下载弹出所选歌曲档位并集选择) */
|
||||||
|
selectQualityOnDownload: boolean,
|
||||||
|
/** 下载时默认音质:"" 表示最高;否则为搜索音质档位 label(如 "无损"、"320K") */
|
||||||
|
defaultDownloadQuality: string,
|
||||||
|
/** 飞牛音乐(NAS)连接:服务器地址(如 http://192.168.1.10:5666,空=未配置) */
|
||||||
|
feiniuBaseUrl?: string,
|
||||||
|
/** 飞牛音乐登录 token(登录成功后保存) */
|
||||||
|
feiniuToken?: string,
|
||||||
|
/** 飞牛音乐登录账号(展示 + 重新登录回填用) */
|
||||||
|
feiniuUsername?: string,
|
||||||
|
/** 飞牛音乐设备 ID(32 位 hex,登录签名用,一次生成复用) */
|
||||||
|
feiniuDeviceId?: string,
|
||||||
|
/** 飞牛音乐访问安全码(可选;仅需访问码的库才填,LAN 通常为空) */
|
||||||
|
feiniuAccessCode?: string,
|
||||||
|
/** 飞牛音乐连接列表(多连接:本地 / frp / 预留 fnconnect) */
|
||||||
|
feiniuConnections?: FeiniuConnection[],
|
||||||
|
/** 当前激活连接的 id */
|
||||||
|
feiniuActiveId?: string,
|
||||||
|
/** 本地曲库扫描目录(默认含音乐下载 savedir) */
|
||||||
|
feiniuLocalDirs?: string[],
|
||||||
|
/** 播放缓存开关 */
|
||||||
|
feiniuCacheEnabled?: boolean,
|
||||||
|
/** 缓存上限(GB) */
|
||||||
|
feiniuCacheMaxGb?: number,
|
||||||
|
/** 播放模式:"stream" 直连流式 | "cache" 缓存后播放 */
|
||||||
|
feiniuPlayMode?: string,
|
||||||
|
/** 飞牛曲库目标目录(NAS 绝对路径,如 vol1/1000/Music;上传到飞牛用) */
|
||||||
|
feiniuLibraryNasPath?: string,
|
||||||
|
/** 下载完成后自动上传到飞牛曲库 */
|
||||||
|
feiniuAutoUpload?: boolean,
|
||||||
|
};
|
||||||
|
|
||||||
/** 进程信息(返回给前端) */
|
/** 进程信息(返回给前端) */
|
||||||
export type ProcessInfo = {
|
export type ProcessInfo = {
|
||||||
id: string,
|
id: string,
|
||||||
|
|||||||
@@ -0,0 +1,157 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, ref, watch } from 'vue'
|
||||||
|
import { ArrowLeft, Search } from '@lucide/vue'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Card, CardContent } from '@/components/ui/card'
|
||||||
|
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||||
|
import { Separator } from '@/components/ui/separator'
|
||||||
|
import { useSearchStore } from '@/stores/searchStore'
|
||||||
|
import { registerAllTools, TOOLS_META } from './tools'
|
||||||
|
import {
|
||||||
|
getAllTools, getTool, searchTools,
|
||||||
|
CATEGORY_ORDER, CATEGORY_LABEL, type DevTool
|
||||||
|
} from './registry'
|
||||||
|
|
||||||
|
const searchStore = useSearchStore()
|
||||||
|
|
||||||
|
registerAllTools()
|
||||||
|
|
||||||
|
const allTools = getAllTools()
|
||||||
|
|
||||||
|
// ===== 列表视图:搜索 + 分类筛选 =====
|
||||||
|
const query = ref('')
|
||||||
|
const category = ref<'all' | DevTool['category']>('all')
|
||||||
|
|
||||||
|
const filteredTools = computed(() => {
|
||||||
|
const list = searchTools(query.value)
|
||||||
|
if (category.value === 'all') return list
|
||||||
|
return list.filter(t => t.category === category.value)
|
||||||
|
})
|
||||||
|
|
||||||
|
interface ToolGroup {
|
||||||
|
category: DevTool['category']
|
||||||
|
label: string
|
||||||
|
tools: DevTool[]
|
||||||
|
}
|
||||||
|
|
||||||
|
const groupedTools = computed<ToolGroup[]>(() => {
|
||||||
|
if (category.value !== 'all') {
|
||||||
|
return [{
|
||||||
|
category: category.value as DevTool['category'],
|
||||||
|
label: CATEGORY_LABEL[category.value as DevTool['category']],
|
||||||
|
tools: filteredTools.value
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
const groups: ToolGroup[] = []
|
||||||
|
for (const cat of CATEGORY_ORDER) {
|
||||||
|
const tools = filteredTools.value.filter(t => t.category === cat)
|
||||||
|
if (tools.length > 0) groups.push({ category: cat, label: CATEGORY_LABEL[cat], tools })
|
||||||
|
}
|
||||||
|
return groups
|
||||||
|
})
|
||||||
|
|
||||||
|
// ===== 详情视图 =====
|
||||||
|
const selectedId = ref<string | null>(null)
|
||||||
|
const selectedTool = computed<DevTool | null>(() => {
|
||||||
|
if (!selectedId.value) return null
|
||||||
|
return getTool(selectedId.value) ?? null
|
||||||
|
})
|
||||||
|
|
||||||
|
function openTool(id: string) {
|
||||||
|
selectedId.value = id
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 全局搜索跳转:工具索引 → 打开对应工具 =====
|
||||||
|
onMounted(() => {
|
||||||
|
const actions = new Map<number, () => void>()
|
||||||
|
TOOLS_META.forEach((t, i) => {
|
||||||
|
actions.set(i, () => openTool(t.id))
|
||||||
|
})
|
||||||
|
searchStore.registerActions('devtools', actions)
|
||||||
|
})
|
||||||
|
|
||||||
|
watch(selectedId, () => {
|
||||||
|
query.value = ''
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="h-full p-6 overflow-hidden flex flex-col">
|
||||||
|
<!-- 列表视图 -->
|
||||||
|
<template v-if="!selectedTool">
|
||||||
|
<div class="flex items-center gap-3 mb-4 shrink-0 flex-wrap">
|
||||||
|
<div class="relative flex-1 min-w-[180px] max-w-xs">
|
||||||
|
<Search class="absolute left-2.5 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
|
||||||
|
<Input v-model="query" placeholder="搜索工具..." class="h-8 pl-8 text-sm" />
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
v-for="cat in (['all', ...CATEGORY_ORDER] as const)"
|
||||||
|
:key="cat"
|
||||||
|
size="sm"
|
||||||
|
variant="ghost"
|
||||||
|
class="h-7 px-2.5 text-xs"
|
||||||
|
:class="category === cat ? 'bg-secondary text-foreground' : 'text-muted-foreground'"
|
||||||
|
@click="category = cat as typeof category"
|
||||||
|
>
|
||||||
|
{{ cat === 'all' ? '全部' : CATEGORY_LABEL[cat as DevTool['category']] }}
|
||||||
|
</Button>
|
||||||
|
<span class="text-xs text-muted-foreground ml-auto">{{ (category === 'all' ? allTools : filteredTools).length }} 个工具</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ScrollArea class="flex-1 min-h-0 -mr-3 pr-3">
|
||||||
|
<div v-if="filteredTools.length === 0" class="h-full flex items-center justify-center text-muted-foreground text-sm">
|
||||||
|
没有找到匹配的工具
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 按分类分组 -->
|
||||||
|
<div v-for="group in groupedTools" :key="group.category" class="mb-5">
|
||||||
|
<div class="flex items-center gap-2 mb-2">
|
||||||
|
<span class="text-xs font-medium text-muted-foreground">{{ group.label }}</span>
|
||||||
|
<Separator class="flex-1" />
|
||||||
|
</div>
|
||||||
|
<div class="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-3">
|
||||||
|
<Card
|
||||||
|
v-for="tool in group.tools"
|
||||||
|
:key="tool.id"
|
||||||
|
class="cursor-pointer transition-all hover:border-primary/50 hover:shadow-sm !py-0 !gap-0"
|
||||||
|
@click="openTool(tool.id)"
|
||||||
|
>
|
||||||
|
<CardContent class="p-4 flex flex-col gap-2">
|
||||||
|
<div class="size-9 rounded-lg bg-primary/10 text-primary flex items-center justify-center">
|
||||||
|
<component :is="tool.icon" class="size-5" />
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-col gap-0.5">
|
||||||
|
<span class="text-sm font-medium leading-tight">{{ tool.name }}</span>
|
||||||
|
<span class="text-xs text-muted-foreground leading-snug line-clamp-2">{{ tool.description }}</span>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</ScrollArea>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- 工具详情视图 -->
|
||||||
|
<template v-else>
|
||||||
|
<div class="flex items-center gap-3 mb-4 shrink-0">
|
||||||
|
<Button size="sm" variant="ghost" class="gap-1 h-8" @click="selectedId = null">
|
||||||
|
<ArrowLeft class="size-4" />
|
||||||
|
返回
|
||||||
|
</Button>
|
||||||
|
<div class="size-8 rounded-lg bg-primary/10 text-primary flex items-center justify-center">
|
||||||
|
<component :is="selectedTool.icon" class="size-4" />
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-col">
|
||||||
|
<span class="text-sm font-medium leading-tight">{{ selectedTool.name }}</span>
|
||||||
|
<span class="text-xs text-muted-foreground leading-snug">{{ selectedTool.description }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<ScrollArea class="flex-1 min-h-0 -mr-3 pr-3">
|
||||||
|
<div class="max-w-3xl px-1 pb-6">
|
||||||
|
<component :is="selectedTool.component" />
|
||||||
|
</div>
|
||||||
|
</ScrollArea>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { Check, Copy } from '@lucide/vue'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
|
||||||
|
const props = withDefaults(
|
||||||
|
defineProps<{
|
||||||
|
text: string
|
||||||
|
editable?: boolean
|
||||||
|
placeholder?: string
|
||||||
|
label?: string
|
||||||
|
minHeight?: string
|
||||||
|
}>(),
|
||||||
|
{ editable: false, placeholder: '结果...', label: '结果', minHeight: '120px' }
|
||||||
|
)
|
||||||
|
|
||||||
|
const emit = defineEmits<{
|
||||||
|
(e: 'update:text', v: string): void
|
||||||
|
(e: 'copy', text: string): void
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const copied = ref(false)
|
||||||
|
let copyTimer: number
|
||||||
|
|
||||||
|
const lineCount = computed(() => (props.text ? props.text.split('\n').length : 0))
|
||||||
|
const charCount = computed(() => props.text.length)
|
||||||
|
|
||||||
|
const copy = async () => {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(props.text)
|
||||||
|
emit('copy', props.text)
|
||||||
|
copied.value = true
|
||||||
|
window.clearTimeout(copyTimer)
|
||||||
|
copyTimer = window.setTimeout(() => (copied.value = false), 1500)
|
||||||
|
} catch {
|
||||||
|
/* 复制失败静默 */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const onInput = (v: string | number) => {
|
||||||
|
if (props.editable) emit('update:text', String(v))
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<span class="text-xs font-medium">{{ label }}</span>
|
||||||
|
<div class="flex items-center gap-2 text-[11px] text-muted-foreground">
|
||||||
|
<span>{{ lineCount }} 行</span>
|
||||||
|
<span>{{ charCount }} 字符</span>
|
||||||
|
<Button
|
||||||
|
v-if="!editable"
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
class="size-6"
|
||||||
|
:title="copied ? '已复制' : '复制'"
|
||||||
|
@click="copy"
|
||||||
|
>
|
||||||
|
<Check v-if="copied" class="size-3.5 text-green-500" />
|
||||||
|
<Copy v-else class="size-3.5" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Textarea
|
||||||
|
:model-value="props.text"
|
||||||
|
:readonly="!editable"
|
||||||
|
:placeholder="placeholder"
|
||||||
|
:style="{ minHeight }"
|
||||||
|
class="font-mono text-xs leading-relaxed resize-y"
|
||||||
|
@update:model-value="onInput"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
export interface SegmentedOption {
|
||||||
|
value: string
|
||||||
|
label: string
|
||||||
|
}
|
||||||
|
|
||||||
|
defineProps<{
|
||||||
|
options: SegmentedOption[]
|
||||||
|
modelValue: string
|
||||||
|
label?: string
|
||||||
|
size?: 'xs' | 'sm'
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const emit = defineEmits<{
|
||||||
|
(e: 'update:modelValue', v: string): void
|
||||||
|
}>()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex items-center gap-2 shrink-0">
|
||||||
|
<span v-if="label" class="text-sm text-muted-foreground">{{ label }}</span>
|
||||||
|
<div class="inline-flex rounded-md border border-border bg-muted/40 p-1">
|
||||||
|
<button
|
||||||
|
v-for="o in options"
|
||||||
|
:key="o.value"
|
||||||
|
type="button"
|
||||||
|
class="rounded px-3 font-medium transition-colors cursor-pointer"
|
||||||
|
:class="[
|
||||||
|
size === 'sm' ? 'py-1.5 text-sm' : 'py-1 text-sm',
|
||||||
|
modelValue === o.value
|
||||||
|
? 'bg-background text-foreground shadow-sm'
|
||||||
|
: 'text-muted-foreground hover:text-foreground'
|
||||||
|
]"
|
||||||
|
@click="emit('update:modelValue', o.value)"
|
||||||
|
>
|
||||||
|
{{ o.label }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import type { ModuleConfig } from '@/types/module'
|
||||||
|
import type { SearchIndexItem } from '@/stores/searchIndex'
|
||||||
|
import { TOOLS_META } from './tools'
|
||||||
|
|
||||||
|
/** 开发者工具模块:聚合大量轻量文本/编码/转换工具 */
|
||||||
|
|
||||||
|
const searchItems: SearchIndexItem[] = TOOLS_META.map((t) => ({
|
||||||
|
title: t.name,
|
||||||
|
description: t.description,
|
||||||
|
keywords: [t.name, ...t.keywords]
|
||||||
|
}))
|
||||||
|
|
||||||
|
export const moduleConfig: ModuleConfig = {
|
||||||
|
id: 'devtools',
|
||||||
|
name: '开发者工具',
|
||||||
|
icon: 'devtools',
|
||||||
|
description: 'JSON / Base64 / 时间戳 / 正则 / 颜色 / Cron / 密码等 20 个常用开发工具',
|
||||||
|
category: 'tool',
|
||||||
|
defaultEnabled: true,
|
||||||
|
loader: () => import('./DevToolsModule.vue'),
|
||||||
|
searchItems,
|
||||||
|
lifecycle: {
|
||||||
|
onEnable: async () => {},
|
||||||
|
onDisable: async () => {}
|
||||||
|
},
|
||||||
|
order: 60
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import type { Component } from 'vue'
|
||||||
|
|
||||||
|
export type DevToolCategory = 'encoding' | 'transform' | 'text' | 'generate' | 'reference'
|
||||||
|
|
||||||
|
export interface DevTool {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
description: string
|
||||||
|
category: DevToolCategory
|
||||||
|
keywords: string[]
|
||||||
|
icon: Component
|
||||||
|
component: Component
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 分类展示顺序 */
|
||||||
|
export const CATEGORY_ORDER: DevToolCategory[] = ['transform', 'encoding', 'text', 'generate', 'reference']
|
||||||
|
export const CATEGORY_LABEL: Record<DevToolCategory, string> = {
|
||||||
|
transform: '转换',
|
||||||
|
encoding: '编码',
|
||||||
|
text: '文本',
|
||||||
|
generate: '生成',
|
||||||
|
reference: '速查'
|
||||||
|
}
|
||||||
|
|
||||||
|
const allTools: DevTool[] = []
|
||||||
|
const registry = new Map<string, DevTool>()
|
||||||
|
|
||||||
|
export function registerTool(tool: DevTool): void {
|
||||||
|
if (registry.has(tool.id)) return
|
||||||
|
registry.set(tool.id, tool)
|
||||||
|
allTools.push(tool)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getTool(id: string): DevTool | undefined {
|
||||||
|
return registry.get(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAllTools(): DevTool[] {
|
||||||
|
return [...allTools]
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getToolsByCategory(): Record<DevToolCategory, DevTool[]> {
|
||||||
|
const result = {} as Record<DevToolCategory, DevTool[]>
|
||||||
|
for (const cat of CATEGORY_ORDER) result[cat] = []
|
||||||
|
for (const tool of allTools) {
|
||||||
|
result[tool.category].push(tool)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
export function searchTools(query: string): DevTool[] {
|
||||||
|
if (!query.trim()) return allTools
|
||||||
|
const q = query.trim().toLowerCase()
|
||||||
|
return allTools.filter(t =>
|
||||||
|
t.name.toLowerCase().includes(q) ||
|
||||||
|
t.description.toLowerCase().includes(q) ||
|
||||||
|
t.keywords.some(k => k.toLowerCase().includes(q))
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { ArrowDownUp, Upload } from '@lucide/vue'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import Segmented from '../components/Segmented.vue'
|
||||||
|
import ResultArea from '../components/ResultArea.vue'
|
||||||
|
|
||||||
|
type Tab = 'convert' | 'file'
|
||||||
|
|
||||||
|
const tab = ref<Tab>('convert')
|
||||||
|
const mode = ref<'encode' | 'decode'>('encode')
|
||||||
|
const input = ref('')
|
||||||
|
const error = ref('')
|
||||||
|
|
||||||
|
function encode(s: string): string {
|
||||||
|
const bytes = new TextEncoder().encode(s)
|
||||||
|
let bin = ''
|
||||||
|
for (const b of bytes) bin += String.fromCharCode(b)
|
||||||
|
return btoa(bin)
|
||||||
|
}
|
||||||
|
|
||||||
|
function decode(s: string): string {
|
||||||
|
const cleaned = s.replace(/[\r\n\s]/g, '')
|
||||||
|
const bin = atob(cleaned)
|
||||||
|
const bytes = Uint8Array.from(bin, ch => ch.charCodeAt(0))
|
||||||
|
return new TextDecoder().decode(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
const output = computed(() => {
|
||||||
|
error.value = ''
|
||||||
|
const v = input.value
|
||||||
|
if (!v) return ''
|
||||||
|
try {
|
||||||
|
return mode.value === 'encode' ? encode(v) : decode(v)
|
||||||
|
} catch (e) {
|
||||||
|
error.value = '解码失败:' + String(e)
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const swap = () => {
|
||||||
|
if (output.value) {
|
||||||
|
input.value = output.value
|
||||||
|
mode.value = mode.value === 'encode' ? 'decode' : 'encode'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 文件转 Base64 =====
|
||||||
|
const file = ref<File | null>(null)
|
||||||
|
const fileInput = ref<HTMLInputElement | null>(null)
|
||||||
|
const fileBase64 = ref('')
|
||||||
|
const fileError = ref('')
|
||||||
|
const fileLoading = ref(false)
|
||||||
|
const FILE_SIZE_LIMIT = 64 * 1024 * 1024 // 64MB 保护上限(Base64 展示本身就很占内存)
|
||||||
|
|
||||||
|
function formatSize(bytes: number): string {
|
||||||
|
if (bytes < 1024) return `${bytes} B`
|
||||||
|
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
||||||
|
return `${(bytes / 1024 / 1024).toFixed(1)} MB`
|
||||||
|
}
|
||||||
|
|
||||||
|
const mime = computed(() => file.value?.type || 'application/octet-stream')
|
||||||
|
|
||||||
|
async function onFileChange(e: Event) {
|
||||||
|
const el = e.target as HTMLInputElement
|
||||||
|
const f = el.files?.[0] ?? null
|
||||||
|
fileError.value = ''
|
||||||
|
fileBase64.value = ''
|
||||||
|
file.value = f
|
||||||
|
if (!f) return
|
||||||
|
if (f.size > FILE_SIZE_LIMIT) {
|
||||||
|
fileError.value = `文件过大(${formatSize(f.size)}),请使用 64MB 以内的文件`
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fileLoading.value = true
|
||||||
|
try {
|
||||||
|
const buf = await f.arrayBuffer()
|
||||||
|
const bytes = new Uint8Array(buf)
|
||||||
|
let bin = ''
|
||||||
|
const CHUNK = 0x8000
|
||||||
|
for (let i = 0; i < bytes.length; i += CHUNK) {
|
||||||
|
bin += String.fromCharCode(...bytes.subarray(i, i + CHUNK))
|
||||||
|
}
|
||||||
|
fileBase64.value = btoa(bin)
|
||||||
|
} catch (e) {
|
||||||
|
fileError.value = '读取失败:' + String(e)
|
||||||
|
} finally {
|
||||||
|
fileLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearFile() {
|
||||||
|
file.value = null
|
||||||
|
fileBase64.value = ''
|
||||||
|
fileError.value = ''
|
||||||
|
if (fileInput.value) fileInput.value.value = ''
|
||||||
|
}
|
||||||
|
|
||||||
|
const dataUrl = computed(() =>
|
||||||
|
fileBase64.value ? `data:${mime.value};base64,${fileBase64.value}` : ''
|
||||||
|
)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<Segmented
|
||||||
|
v-model="tab"
|
||||||
|
:options="[
|
||||||
|
{ value: 'convert', label: '文本互转' },
|
||||||
|
{ value: 'file', label: '文件转 Base64' }
|
||||||
|
]"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<!-- 文本互转 -->
|
||||||
|
<template v-if="tab === 'convert'">
|
||||||
|
<div class="flex items-center justify-between flex-wrap gap-2">
|
||||||
|
<Segmented
|
||||||
|
v-model="mode"
|
||||||
|
label="操作"
|
||||||
|
:options="[
|
||||||
|
{ value: 'encode', label: '编码' },
|
||||||
|
{ value: 'decode', label: '解码' }
|
||||||
|
]"
|
||||||
|
/>
|
||||||
|
<Button size="sm" variant="outline" class="h-8 text-sm gap-1" :disabled="!output" @click="swap">
|
||||||
|
<ArrowDownUp class="size-3.5" />
|
||||||
|
结果回填
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">{{ mode === 'encode' ? '原文' : 'Base64 字符串' }}</Label>
|
||||||
|
<Textarea v-model="input" placeholder="在此输入..." class="min-h-[120px] font-mono text-xs resize-y" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ResultArea :text="output" placeholder="结果" />
|
||||||
|
<p v-if="error" class="text-xs text-destructive">{{ error }}</p>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- 文件转 Base64 -->
|
||||||
|
<template v-else>
|
||||||
|
<div class="flex items-center gap-2 flex-wrap">
|
||||||
|
<Button size="sm" variant="outline" class="h-8 text-sm gap-1.5" @click="fileInput?.click()">
|
||||||
|
<Upload class="size-3.5" />
|
||||||
|
选择文件
|
||||||
|
</Button>
|
||||||
|
<input ref="fileInput" type="file" class="hidden" @change="onFileChange" />
|
||||||
|
<template v-if="file">
|
||||||
|
<span class="text-xs font-mono text-muted-foreground">{{ file.name }}({{ formatSize(file.size) }},{{ mime }})</span>
|
||||||
|
<Button size="sm" variant="ghost" class="h-7 text-xs" @click="clearFile">移除</Button>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
<p v-if="fileError" class="text-xs text-destructive">{{ fileError }}</p>
|
||||||
|
|
||||||
|
<template v-if="fileBase64">
|
||||||
|
<ResultArea :text="fileBase64" label="Base64" placeholder="Base64" minHeight="100px" />
|
||||||
|
<ResultArea :text="dataUrl" label="Data URL" placeholder="Data URL" minHeight="100px" />
|
||||||
|
<p class="text-xs text-muted-foreground">Base64 体积约为原文件的 4/3({{ formatSize(fileBase64.length) }})。</p>
|
||||||
|
</template>
|
||||||
|
<p v-else-if="!fileLoading" class="text-xs text-muted-foreground">选择文件后自动生成 Base64 与 Data URL。</p>
|
||||||
|
<p v-else class="text-xs text-muted-foreground">读取中...</p>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import Segmented from '../components/Segmented.vue'
|
||||||
|
import ResultArea from '../components/ResultArea.vue'
|
||||||
|
|
||||||
|
type CaseMode =
|
||||||
|
| 'camel' | 'pascal' | 'snake' | 'kebab'
|
||||||
|
| 'upper' | 'lower' | 'title'
|
||||||
|
| 'spaceToDash' | 'trimLines' | 'collapseSpace'
|
||||||
|
|
||||||
|
const modes: { value: CaseMode; label: string }[] = [
|
||||||
|
{ value: 'camel', label: 'camelCase' },
|
||||||
|
{ value: 'pascal', label: 'PascalCase' },
|
||||||
|
{ value: 'snake', label: 'snake_case' },
|
||||||
|
{ value: 'kebab', label: 'kebab-case' },
|
||||||
|
{ value: 'upper', label: '全大写' },
|
||||||
|
{ value: 'lower', label: '全小写' },
|
||||||
|
{ value: 'title', label: '标题式' },
|
||||||
|
{ value: 'spaceToDash', label: '空格转下划线' },
|
||||||
|
{ value: 'collapseSpace', label: '合并空行空白' },
|
||||||
|
{ value: 'trimLines', label: '每行去首尾空格' }
|
||||||
|
]
|
||||||
|
|
||||||
|
const mode = ref<CaseMode>('camel')
|
||||||
|
const input = ref('')
|
||||||
|
|
||||||
|
function toWords(s: string): string[] {
|
||||||
|
// 拆分 camelCase / snake_case / kebab-case / 空格,得到词
|
||||||
|
return s
|
||||||
|
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
||||||
|
.replace(/[_\-\s]+/g, ' ')
|
||||||
|
.trim()
|
||||||
|
.split(' ')
|
||||||
|
.filter(Boolean)
|
||||||
|
}
|
||||||
|
|
||||||
|
const output = computed(() => {
|
||||||
|
const v = input.value
|
||||||
|
if (!v) return ''
|
||||||
|
switch (mode.value) {
|
||||||
|
case 'upper':
|
||||||
|
return v.toUpperCase()
|
||||||
|
case 'lower':
|
||||||
|
return v.toLowerCase()
|
||||||
|
case 'title':
|
||||||
|
return v.replace(/\b\w/g, ch => ch.toUpperCase())
|
||||||
|
case 'spaceToDash':
|
||||||
|
return v.replace(/\s+/g, '_')
|
||||||
|
case 'collapseSpace':
|
||||||
|
return v.split(/\n+/).map(l => l.trim()).filter(Boolean).join('\n')
|
||||||
|
case 'trimLines':
|
||||||
|
return v.split('\n').map(l => l.trim()).join('\n')
|
||||||
|
case 'camel': // fallthrough
|
||||||
|
case 'pascal':
|
||||||
|
case 'snake':
|
||||||
|
case 'kebab':
|
||||||
|
break
|
||||||
|
}
|
||||||
|
const words = toWords(v).filter(Boolean)
|
||||||
|
if (words.length === 0) return ''
|
||||||
|
if (mode.value === 'camel') {
|
||||||
|
return words[0].toLowerCase() + words.slice(1).map(w => cap(w)).join('')
|
||||||
|
}
|
||||||
|
if (mode.value === 'pascal') {
|
||||||
|
return words.map(cap).join('')
|
||||||
|
}
|
||||||
|
const sep = mode.value === 'snake' ? '_' : '-'
|
||||||
|
return words.map(w => w.toLowerCase()).join(sep)
|
||||||
|
})
|
||||||
|
|
||||||
|
function cap(w: string): string {
|
||||||
|
return w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<Segmented v-model="mode" :options="modes" />
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">原文</Label>
|
||||||
|
<Textarea v-model="input" placeholder="在此输入..." class="min-h-[140px] font-mono text-xs resize-y" />
|
||||||
|
</div>
|
||||||
|
<ResultArea :text="output" placeholder="结果" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Switch } from '@/components/ui/switch'
|
||||||
|
|
||||||
|
const input = ref('')
|
||||||
|
const showFrequency = ref(true)
|
||||||
|
|
||||||
|
function utf8Bytes(s: string): number {
|
||||||
|
return new TextEncoder().encode(s).length
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 统计词:中文按字、英文按单词 */
|
||||||
|
function countWords(s: string): number {
|
||||||
|
const cjk = (s.match(/[\u4e00-\u9fff\u3400-\u4dbf]/g) ?? []).length
|
||||||
|
const latin = (s.match(/[a-zA-Z0-9]+(?:[-'’][a-zA-Z0-9]+)*/g) ?? []).length
|
||||||
|
return cjk + latin
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Stats {
|
||||||
|
chars: number
|
||||||
|
charsNoSpace: number
|
||||||
|
bytes: number
|
||||||
|
words: number
|
||||||
|
lines: number
|
||||||
|
nonEmptyLines: number
|
||||||
|
sentences: number
|
||||||
|
paragraphs: number
|
||||||
|
}
|
||||||
|
|
||||||
|
const stats = computed<Stats>(() => {
|
||||||
|
const v = input.value
|
||||||
|
const lines = v === '' ? 0 : v.split('\n').length
|
||||||
|
const nonEmpty = v.split('\n').filter(l => l.trim()).length
|
||||||
|
// 句子:以 。!?.!?;; 结尾的段落片段
|
||||||
|
const sentences = (v.match(/[^。!?!?\n]+[。!?!?]?/g) ?? []).filter(s => s.trim()).length
|
||||||
|
const paragraphs = v.split(/\n\s*\n/).filter(p => p.trim()).length
|
||||||
|
return {
|
||||||
|
chars: v.length,
|
||||||
|
charsNoSpace: v.replace(/\s/g, '').length,
|
||||||
|
bytes: utf8Bytes(v),
|
||||||
|
words: countWords(v),
|
||||||
|
lines,
|
||||||
|
nonEmptyLines: nonEmpty,
|
||||||
|
sentences,
|
||||||
|
paragraphs
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const FIELDS: Array<{ key: keyof Stats; label: string }> = [
|
||||||
|
{ key: 'chars', label: '字符数' },
|
||||||
|
{ key: 'charsNoSpace', label: '字符数(不含空白)' },
|
||||||
|
{ key: 'bytes', label: '字节数(UTF-8)' },
|
||||||
|
{ key: 'words', label: '词数(中文按字/英文按词)' },
|
||||||
|
{ key: 'lines', label: '行数' },
|
||||||
|
{ key: 'nonEmptyLines', label: '非空行数' },
|
||||||
|
{ key: 'sentences', label: '句子数' },
|
||||||
|
{ key: 'paragraphs', label: '段落数(空行分隔)' }
|
||||||
|
]
|
||||||
|
|
||||||
|
/** 高频字符 / 高频词 top 10 */
|
||||||
|
const topChars = computed(() => {
|
||||||
|
if (!showFrequency.value || !input.value) return []
|
||||||
|
const map = new Map<string, number>()
|
||||||
|
for (const ch of input.value) {
|
||||||
|
if (/\s/.test(ch)) continue
|
||||||
|
map.set(ch, (map.get(ch) ?? 0) + 1)
|
||||||
|
}
|
||||||
|
return [...map.entries()].sort((a, b) => b[1] - a[1]).slice(0, 10)
|
||||||
|
})
|
||||||
|
|
||||||
|
const topWords = computed(() => {
|
||||||
|
if (!showFrequency.value || !input.value) return []
|
||||||
|
const tokens = input.value.match(/[\u4e00-\u9fff]|[a-zA-Z0-9]+(?:[-'’][a-zA-Z0-9]+)*/g) ?? []
|
||||||
|
const map = new Map<string, number>()
|
||||||
|
for (const t of tokens) {
|
||||||
|
map.set(t, (map.get(t) ?? 0) + 1)
|
||||||
|
}
|
||||||
|
return [...map.entries()].sort((a, b) => b[1] - a[1]).slice(0, 10)
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<Label class="text-xs">文本</Label>
|
||||||
|
<label class="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
|
||||||
|
显示高频统计
|
||||||
|
<Switch v-model="showFrequency" />
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<Textarea v-model="input" placeholder="粘贴或输入文本,实时统计..." class="min-h-[160px] font-mono text-xs resize-y" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="rounded-md border border-border divide-y divide-border text-xs">
|
||||||
|
<div v-for="f in FIELDS" :key="f.key" class="flex justify-between px-3 py-1.5">
|
||||||
|
<span class="text-muted-foreground">{{ f.label }}</span>
|
||||||
|
<span class="font-mono">{{ stats[f.key].toLocaleString() }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-if="showFrequency && input">
|
||||||
|
<div class="grid grid-cols-2 gap-3">
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">高频字符 Top 10</Label>
|
||||||
|
<div class="rounded-md border border-border divide-y divide-border text-xs">
|
||||||
|
<div v-for="([ch, n], i) in topChars" :key="i" class="flex justify-between px-3 py-1">
|
||||||
|
<span class="font-mono w-8 text-center rounded bg-muted">{{ ch }}</span>
|
||||||
|
<span class="font-mono text-muted-foreground">{{ n }} 次</span>
|
||||||
|
</div>
|
||||||
|
<div v-if="topChars.length === 0" class="px-3 py-2 text-muted-foreground">无内容</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">高频词 Top 10</Label>
|
||||||
|
<div class="rounded-md border border-border divide-y divide-border text-xs">
|
||||||
|
<div v-for="([w, n], i) in topWords" :key="i" class="flex justify-between px-3 py-1">
|
||||||
|
<span class="font-mono">{{ w }}</span>
|
||||||
|
<span class="font-mono text-muted-foreground">{{ n }} 次</span>
|
||||||
|
</div>
|
||||||
|
<div v-if="topWords.length === 0" class="px-3 py-2 text-muted-foreground">无内容</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import ResultArea from '../components/ResultArea.vue'
|
||||||
|
|
||||||
|
const input = ref('#3b82f6')
|
||||||
|
const alpha = ref(1)
|
||||||
|
|
||||||
|
interface Rgb {
|
||||||
|
r: number
|
||||||
|
g: number
|
||||||
|
b: number
|
||||||
|
}
|
||||||
|
|
||||||
|
function clampByte(v: number): number {
|
||||||
|
return Math.min(255, Math.max(0, Math.round(v)))
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseColor(s: string): Rgb | null {
|
||||||
|
const v = s.trim().toLowerCase()
|
||||||
|
if (!v) return null
|
||||||
|
// #rgb / #rgba / #rrggbb / #rrggbbaa
|
||||||
|
const hex = v.match(/^#?([0-9a-f]{3,8})$/)
|
||||||
|
if (hex) {
|
||||||
|
const h = hex[1]
|
||||||
|
if (h.length === 3 || h.length === 4) {
|
||||||
|
const [r, g, b] = [h[0], h[1], h[2]].map(c => parseInt(c + c, 16))
|
||||||
|
return { r, g, b }
|
||||||
|
}
|
||||||
|
if (h.length === 6 || h.length === 8) {
|
||||||
|
return {
|
||||||
|
r: parseInt(h.slice(0, 2), 16),
|
||||||
|
g: parseInt(h.slice(2, 4), 16),
|
||||||
|
b: parseInt(h.slice(4, 6), 16)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
// rgb() / rgba()
|
||||||
|
const rgb = v.match(/^rgba?\(\s*(\d{1,3})[\s,]+(\d{1,3})[\s,]+(\d{1,3})/)
|
||||||
|
if (rgb) {
|
||||||
|
return { r: clampByte(Number(rgb[1])), g: clampByte(Number(rgb[2])), b: clampByte(Number(rgb[3])) }
|
||||||
|
}
|
||||||
|
// hsl() / hsla()
|
||||||
|
const hsl = v.match(/^hsla?\(\s*(\d{1,3}(?:\.\d+)?)\s*[,\s]\s*(\d{1,3})%\s*[,\s]\s*(\d{1,3})%/)
|
||||||
|
if (hsl) {
|
||||||
|
return hslToRgb(Number(hsl[1]), Number(hsl[2]) / 100, Number(hsl[3]) / 100)
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
function hslToRgb(h: number, s: number, l: number): Rgb {
|
||||||
|
h = ((h % 360) + 360) % 360
|
||||||
|
const c = (1 - Math.abs(2 * l - 1)) * s
|
||||||
|
const x = c * (1 - Math.abs(((h / 60) % 2) - 1))
|
||||||
|
const m = l - c / 2
|
||||||
|
let r = 0, g = 0, b = 0
|
||||||
|
if (h < 60) { r = c; g = x }
|
||||||
|
else if (h < 120) { r = x; g = c }
|
||||||
|
else if (h < 180) { g = c; b = x }
|
||||||
|
else if (h < 240) { g = x; b = c }
|
||||||
|
else if (h < 300) { r = x; b = c }
|
||||||
|
else { r = c; b = x }
|
||||||
|
return { r: clampByte((r + m) * 255), g: clampByte((g + m) * 255), b: clampByte((b + m) * 255) }
|
||||||
|
}
|
||||||
|
|
||||||
|
function rgbToHsl({ r, g, b }: Rgb): { h: number; s: number; l: number } {
|
||||||
|
const rn = r / 255, gn = g / 255, bn = b / 255
|
||||||
|
const max = Math.max(rn, gn, bn)
|
||||||
|
const min = Math.min(rn, gn, bn)
|
||||||
|
const l = (max + min) / 2
|
||||||
|
let h = 0
|
||||||
|
let s = 0
|
||||||
|
if (max !== min) {
|
||||||
|
const d = max - min
|
||||||
|
s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
|
||||||
|
if (max === rn) h = ((gn - bn) / d + (gn < bn ? 6 : 0)) * 60
|
||||||
|
else if (max === gn) h = ((bn - rn) / d + 2) * 60
|
||||||
|
else h = ((rn - gn) / d + 4) * 60
|
||||||
|
}
|
||||||
|
return { h: Math.round(h), s: Math.round(s * 100), l: Math.round(l * 100) }
|
||||||
|
}
|
||||||
|
|
||||||
|
function rgbToHsv({ r, g, b }: Rgb): { h: number; s: number; v: number } {
|
||||||
|
const rn = r / 255, gn = g / 255, bn = b / 255
|
||||||
|
const max = Math.max(rn, gn, bn)
|
||||||
|
const min = Math.min(rn, gn, bn)
|
||||||
|
const d = max - min
|
||||||
|
let h = 0
|
||||||
|
if (d !== 0) {
|
||||||
|
if (max === rn) h = (((gn - bn) / d) % 6) * 60
|
||||||
|
else if (max === gn) h = ((bn - rn) / d + 2) * 60
|
||||||
|
else h = ((rn - gn) / d + 4) * 60
|
||||||
|
}
|
||||||
|
h = Math.round(((h % 360) + 360) % 360)
|
||||||
|
return { h, s: Math.round((max === 0 ? 0 : d / max) * 100), v: Math.round(max * 100) }
|
||||||
|
}
|
||||||
|
|
||||||
|
function toHex({ r, g, b }: Rgb): string {
|
||||||
|
return '#' + [r, g, b].map(x => x.toString(16).padStart(2, '0')).join('')
|
||||||
|
}
|
||||||
|
|
||||||
|
const rgb = computed<Rgb | null>(() => parseColor(input.value))
|
||||||
|
|
||||||
|
const alphaInput = computed(() => {
|
||||||
|
const a = Math.min(1, Math.max(0, alpha.value))
|
||||||
|
return Math.round(a * 255)
|
||||||
|
.toString(16)
|
||||||
|
.padStart(2, '0')
|
||||||
|
})
|
||||||
|
|
||||||
|
const formats = computed(() => {
|
||||||
|
const c = rgb.value
|
||||||
|
if (!c) return null
|
||||||
|
const hsl = rgbToHsl(c)
|
||||||
|
const hsv = rgbToHsv(c)
|
||||||
|
return {
|
||||||
|
hex: toHex(c),
|
||||||
|
hexA: `${toHex(c)}${alphaInput.value}`,
|
||||||
|
rgb: `rgb(${c.r}, ${c.g}, ${c.b})`,
|
||||||
|
rgba: `rgba(${c.r}, ${c.g}, ${c.b}, ${alpha.value})`,
|
||||||
|
hsl: `hsl(${hsl.h}, ${hsl.s}%, ${hsl.l}%)`,
|
||||||
|
hsla: `hsla(${hsl.h}, ${hsl.s}%, ${hsl.l}%, ${alpha.value})`,
|
||||||
|
hsv: `hsv(${hsv.h}, ${hsv.s}%, ${hsv.v}%)`,
|
||||||
|
cmyk: rgbToCmyk(c)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
function rgbToCmyk({ r, g, b }: Rgb): string {
|
||||||
|
const rn = r / 255, gn = g / 255, bn = b / 255
|
||||||
|
const k = 1 - Math.max(rn, gn, bn)
|
||||||
|
if (k === 1) return 'cmyk(0%, 0%, 0%, 100%)'
|
||||||
|
const c = (1 - rn - k) / (1 - k)
|
||||||
|
const m = (1 - gn - k) / (1 - k)
|
||||||
|
const y = (1 - bn - k) / (1 - k)
|
||||||
|
const p = (x: number) => Math.round(x * 100)
|
||||||
|
return `cmyk(${p(c)}%, ${p(m)}%, ${p(y)}%, ${p(k)}%)`
|
||||||
|
}
|
||||||
|
|
||||||
|
// 亮度判断(W3C 公式),用于预览色上的文字颜色
|
||||||
|
const previewTextLight = computed(() => {
|
||||||
|
const c = rgb.value
|
||||||
|
if (!c) return true
|
||||||
|
return (c.r * 0.299 + c.g * 0.587 + c.b * 0.114) < 140
|
||||||
|
})
|
||||||
|
|
||||||
|
// 明暗梯度
|
||||||
|
const shades = computed(() => {
|
||||||
|
const c = rgb.value
|
||||||
|
if (!c) return []
|
||||||
|
const hsl = rgbToHsl(c)
|
||||||
|
return [-60, -40, -20, 0, 20, 40, 60].map(delta => {
|
||||||
|
const l = Math.min(96, Math.max(4, hsl.l + delta))
|
||||||
|
const rgb2 = hslToRgb(hsl.h, hsl.s / 100, l / 100)
|
||||||
|
return { label: delta === 0 ? `${l}%` : `${l}%`, color: toHex(rgb2) }
|
||||||
|
})
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<div class="flex items-end gap-3 flex-wrap">
|
||||||
|
<div class="flex flex-col gap-1.5 flex-1 min-w-[200px]">
|
||||||
|
<Label class="text-xs">颜色(支持 #hex / rgb() / hsl())</Label>
|
||||||
|
<Input v-model="input" placeholder="#3b82f6 或 rgb(59,130,246) 或 hsl(217,91%,60%)" class="font-mono text-sm" />
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">透明度 {{ alpha.toFixed(2) }}</Label>
|
||||||
|
<input v-model.number="alpha" type="range" min="0" max="1" step="0.01" class="w-40 accent-primary" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-if="formats && rgb">
|
||||||
|
<!-- 预览 -->
|
||||||
|
<div
|
||||||
|
class="rounded-md border border-border h-20 flex items-center justify-center font-mono text-sm"
|
||||||
|
:style="{ backgroundColor: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${alpha})`, color: previewTextLight ? '#ffffff' : '#000000' }"
|
||||||
|
>
|
||||||
|
{{ formats.hex }} {{ alpha < 1 ? `(透明度 ${alpha.toFixed(2)})` : '' }}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ResultArea :text="formats.hex" label="HEX" placeholder="HEX" minHeight="60px" />
|
||||||
|
<ResultArea v-if="alpha < 1" :text="formats.hexA" label="HEX + Alpha" placeholder="HEX" minHeight="60px" />
|
||||||
|
<ResultArea :text="formats.rgb" label="RGB" placeholder="RGB" minHeight="60px" />
|
||||||
|
<ResultArea v-if="alpha < 1" :text="formats.rgba" label="RGBA" placeholder="RGBA" minHeight="60px" />
|
||||||
|
<ResultArea :text="formats.hsl" label="HSL" placeholder="HSL" minHeight="60px" />
|
||||||
|
<ResultArea v-if="alpha < 1" :text="formats.hsla" label="HSLA" placeholder="HSLA" minHeight="60px" />
|
||||||
|
<ResultArea :text="formats.hsv" label="HSV" placeholder="HSV" minHeight="60px" />
|
||||||
|
<ResultArea :text="formats.cmyk" label="CMYK" placeholder="CMYK" minHeight="60px" />
|
||||||
|
|
||||||
|
<!-- 明暗梯度 -->
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">明暗梯度</Label>
|
||||||
|
<div class="flex rounded-md overflow-hidden border border-border h-10">
|
||||||
|
<div
|
||||||
|
v-for="(s, i) in shades"
|
||||||
|
:key="i"
|
||||||
|
class="flex-1 flex items-center justify-center text-[10px] font-mono cursor-pointer"
|
||||||
|
:style="{ backgroundColor: s.color, color: i < 3 ? '#fff' : '#000' }"
|
||||||
|
:title="s.color"
|
||||||
|
@click="input = s.color"
|
||||||
|
>
|
||||||
|
{{ s.label }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<p v-else-if="input" class="text-xs text-destructive">无法识别的颜色格式,支持 #hex / rgb() / rgba() / hsl() / hsla()。</p>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import ResultArea from '../components/ResultArea.vue'
|
||||||
|
|
||||||
|
const expr = ref('*/5 * * * *')
|
||||||
|
|
||||||
|
interface FieldMatcher {
|
||||||
|
/** 该字段是否为非通配(受限) */
|
||||||
|
restricted: boolean
|
||||||
|
match(v: number): boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseField(field: string, min: number, max: number): FieldMatcher {
|
||||||
|
const values = new Set<number>()
|
||||||
|
let restricted = false
|
||||||
|
for (const part of field.split(',')) {
|
||||||
|
const [rangePart, stepPart] = part.split('/')
|
||||||
|
const step = stepPart ? Number(stepPart) : 1
|
||||||
|
if (!Number.isFinite(step) || step < 1) throw new Error(`非法步长:${part}`)
|
||||||
|
let lo: number
|
||||||
|
let hi: number
|
||||||
|
if (rangePart === '*') {
|
||||||
|
if (!stepPart) {
|
||||||
|
// 纯通配:匹配任意值(不受限)
|
||||||
|
return { restricted: false, match: () => true }
|
||||||
|
}
|
||||||
|
lo = min
|
||||||
|
hi = max
|
||||||
|
} else if (rangePart.includes('-')) {
|
||||||
|
const [a, b] = rangePart.split('-').map(Number)
|
||||||
|
if (!Number.isFinite(a) || !Number.isFinite(b) || a < min || b > max || a > b) {
|
||||||
|
throw new Error(`非法范围:${part}(应在 ${min}-${max} 内)`)
|
||||||
|
}
|
||||||
|
lo = a
|
||||||
|
hi = b
|
||||||
|
} else {
|
||||||
|
const n = Number(rangePart)
|
||||||
|
if (!Number.isFinite(n) || n < min || n > max) {
|
||||||
|
throw new Error(`非法值:${part}(应在 ${min}-${max} 内)`)
|
||||||
|
}
|
||||||
|
lo = n
|
||||||
|
hi = n
|
||||||
|
}
|
||||||
|
restricted = true
|
||||||
|
for (let v = lo; v <= hi; v += step) values.add(v)
|
||||||
|
}
|
||||||
|
if (values.size === 0) throw new Error(`空字段:${field}`)
|
||||||
|
return { restricted, match: v => values.has(v) }
|
||||||
|
}
|
||||||
|
|
||||||
|
const FIELD_NAMES = ['分钟', '小时', '日', '月', '星期'] as const
|
||||||
|
// 星期允许 0-7(0 与 7 均为周日)
|
||||||
|
const FIELD_RANGES: Array<[number, number]> = [[0, 59], [0, 23], [1, 31], [1, 12], [0, 7]]
|
||||||
|
const DOW_NAMES = ['日', '一', '二', '三', '四', '五', '六']
|
||||||
|
|
||||||
|
/** 支持英文别名(星期/月份)与中文星期 */
|
||||||
|
function normalizeExpr(s: string): string {
|
||||||
|
const DOW_MAP: Record<string, string> = {
|
||||||
|
sun: '0', mon: '1', tue: '2', wed: '3', thu: '4', fri: '5', sat: '6',
|
||||||
|
'日': '0', '一': '1', '二': '2', '三': '3', '四': '4', '五': '5', '六': '6'
|
||||||
|
}
|
||||||
|
const MON_MAP: Record<string, string> = {
|
||||||
|
jan: '1', feb: '2', mar: '3', apr: '4', may: '5', jun: '6',
|
||||||
|
jul: '7', aug: '8', sep: '9', oct: '10', nov: '11', dec: '12'
|
||||||
|
}
|
||||||
|
let out = s.trim().toLowerCase()
|
||||||
|
for (const [k, v] of Object.entries(MON_MAP)) {
|
||||||
|
out = out.split(k).join(v)
|
||||||
|
}
|
||||||
|
for (const [k, v] of Object.entries(DOW_MAP)) {
|
||||||
|
out = out.split(k).join(v)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CronParsed {
|
||||||
|
minute: FieldMatcher
|
||||||
|
hour: FieldMatcher
|
||||||
|
dom: FieldMatcher
|
||||||
|
month: FieldMatcher
|
||||||
|
dow: FieldMatcher
|
||||||
|
domRestricted: boolean
|
||||||
|
dowRestricted: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseCron(s: string): CronParsed {
|
||||||
|
const parts = normalizeExpr(s).split(/\s+/)
|
||||||
|
if (parts.length !== 5) {
|
||||||
|
throw new Error(`应为 5 个字段(分 时 日 月 周),当前 ${parts.length} 个`)
|
||||||
|
}
|
||||||
|
const [minute, hour, dom, month, dowRaw] = parts.map((p, i) => parseField(p, FIELD_RANGES[i][0], FIELD_RANGES[i][1]))
|
||||||
|
// cron 标准允许星期用 0-7,其中 0 与 7 均为周日
|
||||||
|
const dow: FieldMatcher = {
|
||||||
|
restricted: dowRaw.restricted,
|
||||||
|
match: v => dowRaw.match(v) || (v === 0 && dowRaw.match(7))
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
minute, hour, dom, month, dow,
|
||||||
|
domRestricted: dom.restricted,
|
||||||
|
dowRestricted: dow.restricted
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 标准 cron 语义:日 与 星期 都受限时,任一匹配即可 */
|
||||||
|
function matches(p: CronParsed, d: Date): boolean {
|
||||||
|
if (!p.minute.match(d.getMinutes())) return false
|
||||||
|
if (!p.hour.match(d.getHours())) return false
|
||||||
|
if (!p.month.match(d.getMonth() + 1)) return false
|
||||||
|
const domOk = p.dom.match(d.getDate())
|
||||||
|
const dowOk = p.dow.match(d.getDay())
|
||||||
|
if (p.domRestricted && p.dowRestricted) return domOk || dowOk
|
||||||
|
return domOk && dowOk
|
||||||
|
}
|
||||||
|
|
||||||
|
function nextRuns(p: CronParsed, from: Date, n: number): Date[] {
|
||||||
|
const out: Date[] = []
|
||||||
|
const t = new Date(from.getTime())
|
||||||
|
t.setSeconds(0, 0)
|
||||||
|
t.setMinutes(t.getMinutes() + 1)
|
||||||
|
// 最多向前扫描 5 年(处理 2 月 29 日等罕见窗口)
|
||||||
|
const limit = new Date(from.getTime() + 5 * 365.25 * 24 * 3600 * 1000)
|
||||||
|
while (out.length < n && t < limit) {
|
||||||
|
if (matches(p, t)) out.push(new Date(t.getTime()))
|
||||||
|
t.setMinutes(t.getMinutes() + 1)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
const pad = (x: number) => String(x).padStart(2, '0')
|
||||||
|
function fmt(d: Date): string {
|
||||||
|
const week = `周${DOW_NAMES[d.getDay()]}`
|
||||||
|
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())} ${week}`
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = computed<{ runs: string[]; fields: string[] } | null>(() => {
|
||||||
|
const s = expr.value.trim()
|
||||||
|
if (!s) return null
|
||||||
|
try {
|
||||||
|
const p = parseCron(s)
|
||||||
|
const runs = nextRuns(p, new Date(), 6)
|
||||||
|
const fields = s.split(/\s+/)
|
||||||
|
return { runs: runs.map(fmt), fields }
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const error = computed(() => {
|
||||||
|
const s = expr.value.trim()
|
||||||
|
if (!s) return ''
|
||||||
|
try {
|
||||||
|
parseCron(s)
|
||||||
|
return ''
|
||||||
|
} catch (e) {
|
||||||
|
return String(e instanceof Error ? e.message : e)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
/** 人类可读的字段说明 */
|
||||||
|
const fieldDesc = computed<string[]>(() => {
|
||||||
|
const s = expr.value.trim()
|
||||||
|
if (!s || error.value) return []
|
||||||
|
const fields = normalizeExpr(s).split(/\s+/)
|
||||||
|
return fields.map((f, i) => {
|
||||||
|
if (f === '*') return `${FIELD_NAMES[i]}:任意`
|
||||||
|
return `${FIELD_NAMES[i]}:${f}`
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
const EXAMPLES = [
|
||||||
|
{ expr: '*/5 * * * *', desc: '每 5 分钟' },
|
||||||
|
{ expr: '0 * * * *', desc: '每小时整点' },
|
||||||
|
{ expr: '30 9 * * 1-5', desc: '工作日 9:30' },
|
||||||
|
{ expr: '0 0 1 * *', desc: '每月 1 日零点' },
|
||||||
|
{ expr: '0 12 */2 * *', desc: '每 2 天的 12:00' }
|
||||||
|
]
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">Cron 表达式(分 时 日 月 周,支持英文/中文星期与英文月份)</Label>
|
||||||
|
<Input v-model="expr" placeholder="*/5 * * * *" class="font-mono text-sm" :class="{ 'border-destructive': !!error }" />
|
||||||
|
<div class="flex items-center gap-2 flex-wrap">
|
||||||
|
<button
|
||||||
|
v-for="ex in EXAMPLES"
|
||||||
|
:key="ex.expr"
|
||||||
|
type="button"
|
||||||
|
class="text-xs px-2 py-0.5 rounded border border-border text-muted-foreground hover:text-foreground cursor-pointer transition-colors"
|
||||||
|
@click="expr = ex.expr"
|
||||||
|
>
|
||||||
|
{{ ex.desc }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p v-if="error" class="text-xs text-destructive">{{ error }}</p>
|
||||||
|
|
||||||
|
<template v-if="parsed">
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">字段拆解</Label>
|
||||||
|
<div class="rounded-md border border-border divide-y divide-border text-xs">
|
||||||
|
<div v-for="(f, i) in parsed.fields" :key="i" class="flex gap-3 px-3 py-1.5">
|
||||||
|
<span class="w-12 shrink-0 text-muted-foreground">{{ FIELD_NAMES[i] }}</span>
|
||||||
|
<span class="font-mono">{{ f }}</span>
|
||||||
|
<span class="ml-auto text-muted-foreground">{{ fieldDesc[i]?.split(':')[1] ?? '' }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">接下来 6 次执行时间</Label>
|
||||||
|
<div class="rounded-md border border-border divide-y divide-border text-xs font-mono">
|
||||||
|
<div v-for="(r, i) in parsed.runs" :key="i" class="px-3 py-1.5 flex gap-3">
|
||||||
|
<span class="text-muted-foreground w-4">+{{ i + 1 }}</span>
|
||||||
|
<span>{{ r }}</span>
|
||||||
|
</div>
|
||||||
|
<div v-if="parsed.runs.length === 0" class="px-3 py-2 text-muted-foreground">5 年内无执行时间(表达式可能过严,如 2 月 30 日)。</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ResultArea :text="parsed.runs.join('\n')" label="执行时间列表(可复制)" placeholder="执行时间" />
|
||||||
|
</template>
|
||||||
|
<p v-else-if="!expr" class="text-xs text-muted-foreground">输入 5 段式 cron 表达式,自动计算接下来 6 次执行时间。</p>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import ResultArea from '../components/ResultArea.vue'
|
||||||
|
|
||||||
|
const oldText = ref('')
|
||||||
|
const newText = ref('')
|
||||||
|
|
||||||
|
type Op = 'equal' | 'del' | 'add'
|
||||||
|
interface DiffLine {
|
||||||
|
op: Op
|
||||||
|
oldLine: string
|
||||||
|
line: string
|
||||||
|
newLine: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// LCS DP 为 O(n·m),行数过大会卡死 UI;超过上限停止计算并提示
|
||||||
|
const MAX_LINES = 3000
|
||||||
|
|
||||||
|
// 先裁剪公共前缀/后缀,LCS 只算中间差异部分(典型场景提速明显)
|
||||||
|
function diffLines(a: string[], b: string[]): DiffLine[] {
|
||||||
|
const out: DiffLine[] = []
|
||||||
|
let start = 0
|
||||||
|
while (start < a.length && start < b.length && a[start] === b[start]) {
|
||||||
|
out.push({ op: 'equal', oldLine: a[start], line: a[start], newLine: b[start] })
|
||||||
|
start++
|
||||||
|
}
|
||||||
|
let endA = a.length, endB = b.length
|
||||||
|
while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
|
||||||
|
endA--
|
||||||
|
endB--
|
||||||
|
}
|
||||||
|
const mid = lcsDiff(a.slice(start, endA), b.slice(start, endB))
|
||||||
|
// 后缀公共部分:a[endA..] 与 b[endB..] 逐行配对
|
||||||
|
const suffix: DiffLine[] = []
|
||||||
|
for (let i = a.length - 1; i >= endA; i--) {
|
||||||
|
const j = endB + (i - endA)
|
||||||
|
suffix.unshift({ op: 'equal', oldLine: a[i], line: a[i], newLine: b[j] })
|
||||||
|
}
|
||||||
|
return [...out, ...mid, ...suffix]
|
||||||
|
}
|
||||||
|
|
||||||
|
function lcsDiff(a: string[], b: string[]): DiffLine[] {
|
||||||
|
const n = a.length
|
||||||
|
const m = b.length
|
||||||
|
if (n === 0) return b.map(line => ({ op: 'add' as const, oldLine: '', line, newLine: '' }))
|
||||||
|
if (m === 0) return a.map(line => ({ op: 'del' as const, oldLine: line, line, newLine: '' }))
|
||||||
|
// LCS DP
|
||||||
|
const dp: number[][] = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0))
|
||||||
|
for (let i = n - 1; i >= 0; i--) {
|
||||||
|
for (let j = m - 1; j >= 0; j--) {
|
||||||
|
dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const out: DiffLine[] = []
|
||||||
|
let i = 0
|
||||||
|
let j = 0
|
||||||
|
while (i < n && j < m) {
|
||||||
|
if (a[i] === b[j]) {
|
||||||
|
out.push({ op: 'equal', oldLine: a[i], line: a[i], newLine: b[j] })
|
||||||
|
i++
|
||||||
|
j++
|
||||||
|
} else if (dp[i + 1][j] >= dp[i][j + 1]) {
|
||||||
|
out.push({ op: 'del', oldLine: a[i], line: a[i], newLine: '' })
|
||||||
|
i++
|
||||||
|
} else {
|
||||||
|
out.push({ op: 'add', oldLine: '', line: b[j], newLine: b[j] })
|
||||||
|
j++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while (i < n) {
|
||||||
|
out.push({ op: 'del', oldLine: a[i], line: a[i], newLine: '' })
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
while (j < m) {
|
||||||
|
out.push({ op: 'add', oldLine: '', line: b[j], newLine: b[j] })
|
||||||
|
j++
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
const tooLarge = computed(() =>
|
||||||
|
oldText.value.split('\n').length > MAX_LINES || newText.value.split('\n').length > MAX_LINES
|
||||||
|
)
|
||||||
|
|
||||||
|
const lines = computed(() => {
|
||||||
|
if (tooLarge.value) return []
|
||||||
|
return diffLines(oldText.value.split('\n'), newText.value.split('\n'))
|
||||||
|
})
|
||||||
|
|
||||||
|
const stats = computed(() => {
|
||||||
|
let adds = 0
|
||||||
|
let dels = 0
|
||||||
|
for (const l of lines.value) {
|
||||||
|
if (l.op === 'add') adds++
|
||||||
|
else if (l.op === 'del') dels++
|
||||||
|
}
|
||||||
|
return { adds, dels }
|
||||||
|
})
|
||||||
|
|
||||||
|
const unifiedText = computed(() => {
|
||||||
|
if (lines.value.length === 0) return ''
|
||||||
|
return lines.value
|
||||||
|
.map(l => (l.op === 'add' ? '+' : l.op === 'del' ? '-' : ' ') + l.line)
|
||||||
|
.join('\n')
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<div class="grid grid-cols-2 gap-3">
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs text-red-500">旧文本(删除 {{ stats.dels }} 行)</Label>
|
||||||
|
<Textarea v-model="oldText" placeholder="旧文本..." class="min-h-[140px] font-mono text-xs resize-y" />
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs text-green-500">新文本(新增 {{ stats.adds }} 行)</Label>
|
||||||
|
<Textarea v-model="newText" placeholder="新文本..." class="min-h-[140px] font-mono text-xs resize-y" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">差异预览</Label>
|
||||||
|
<div class="rounded-md border border-border max-h-64 overflow-auto font-mono text-xs leading-relaxed">
|
||||||
|
<div v-if="tooLarge" class="p-3 text-destructive">文本超过 {{ MAX_LINES }} 行,差异计算已停止(LCS 算法复杂度 O(n·m)),请缩减输入。</div>
|
||||||
|
<div v-else-if="lines.length === 0 || (oldText === '' && newText === '')" class="p-3 text-muted-foreground">输入两边文本查看差异。</div>
|
||||||
|
<div
|
||||||
|
v-for="(l, i) in lines"
|
||||||
|
:key="i"
|
||||||
|
class="flex whitespace-pre px-2 py-0.5"
|
||||||
|
:class="{
|
||||||
|
'bg-red-500/10 text-red-600 dark:text-red-400': l.op === 'del',
|
||||||
|
'bg-green-500/10 text-green-600 dark:text-green-400': l.op === 'add',
|
||||||
|
'text-muted-foreground': l.op === 'equal'
|
||||||
|
}"
|
||||||
|
>
|
||||||
|
<span class="w-5 shrink-0 select-none">{{ l.op === 'add' ? '+' : l.op === 'del' ? '-' : ' ' }}</span>
|
||||||
|
<span class="break-all">{{ l.line }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ResultArea :text="unifiedText" label="统一格式(可复制)" placeholder="unified diff" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import Segmented from '../components/Segmented.vue'
|
||||||
|
import ResultArea from '../components/ResultArea.vue'
|
||||||
|
|
||||||
|
type Eol = 'CRLF' | 'LF' | 'CR'
|
||||||
|
|
||||||
|
const target = ref<Eol>('LF')
|
||||||
|
const input = ref('')
|
||||||
|
|
||||||
|
const detectEol = computed<Eol | 'mixed' | 'none'>(() => {
|
||||||
|
const v = input.value
|
||||||
|
if (!v) return 'none'
|
||||||
|
// 注意:\r\n 中的 \n 也会命中 /\n/,必须用负向后顾排除 CRLF 中的 LF
|
||||||
|
const hasCrlf = v.includes('\r\n')
|
||||||
|
const hasLfOnly = /(?<!\r)\n/.test(v)
|
||||||
|
const hasCrOnly = /\r(?!\n)/.test(v)
|
||||||
|
if (!hasCrlf && !hasLfOnly && !hasCrOnly) return 'none'
|
||||||
|
if (hasCrlf && !hasLfOnly && !hasCrOnly) return 'CRLF'
|
||||||
|
if (!hasCrlf && hasLfOnly && !hasCrOnly) return 'LF'
|
||||||
|
if (!hasCrlf && !hasLfOnly && hasCrOnly) return 'CR'
|
||||||
|
return 'mixed'
|
||||||
|
})
|
||||||
|
|
||||||
|
const detectLabel: Record<string, string> = {
|
||||||
|
CRLF: 'CRLF(Windows)',
|
||||||
|
LF: 'LF(Unix / macOS)',
|
||||||
|
CR: 'CR(旧 Mac)',
|
||||||
|
mixed: '混合',
|
||||||
|
none: '未检测到换行符'
|
||||||
|
}
|
||||||
|
|
||||||
|
const output = computed(() => {
|
||||||
|
const v = input.value
|
||||||
|
if (!v) return ''
|
||||||
|
const sep = target.value === 'CRLF' ? '\r\n' : target.value === 'LF' ? '\n' : '\r'
|
||||||
|
return v.replace(/\r\n|\r|\n/g, sep)
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<Segmented
|
||||||
|
v-model="target"
|
||||||
|
label="目标行尾符"
|
||||||
|
:options="[
|
||||||
|
{ value: 'CRLF', label: 'CRLF (\\r\\n)' },
|
||||||
|
{ value: 'LF', label: 'LF (\\n)' },
|
||||||
|
{ value: 'CR', label: 'CR (\\r)' }
|
||||||
|
]"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<p class="text-xs text-muted-foreground">当前检测:<span class="font-medium">{{ detectLabel[detectEol] }}</span></p>
|
||||||
|
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">原文</Label>
|
||||||
|
<Textarea v-model="input" placeholder="在此输入..." class="min-h-[160px] font-mono text-xs resize-y" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ResultArea :text="output" placeholder="结果" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { ArrowDownUp } from '@lucide/vue'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import Segmented from '../components/Segmented.vue'
|
||||||
|
import ResultArea from '../components/ResultArea.vue'
|
||||||
|
|
||||||
|
const type = ref<'html' | 'json'>('html')
|
||||||
|
const mode = ref<'encode' | 'decode'>('encode')
|
||||||
|
const input = ref('')
|
||||||
|
|
||||||
|
function htmlEncode(s: string): string {
|
||||||
|
return s
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'/g, ''')
|
||||||
|
}
|
||||||
|
|
||||||
|
function htmlDecode(s: string): string {
|
||||||
|
return s
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'|'/g, "'")
|
||||||
|
.replace(/ | /g, ' ')
|
||||||
|
}
|
||||||
|
|
||||||
|
function jsonEncode(s: string): string {
|
||||||
|
return JSON.stringify(s).slice(1, -1)
|
||||||
|
}
|
||||||
|
|
||||||
|
function jsonDecode(s: string): string {
|
||||||
|
// 粘贴的原文可能含真实换行等控制字符,直接拼进 JSON 字符串会解析失败;
|
||||||
|
// 仅转义控制字符(已转义的反斜杠序列不受影响,其中的控制字符不是裸的)
|
||||||
|
const escaped = s.replace(/[\u0000-\u001f]/g, c => {
|
||||||
|
const map: Record<string, string> = { '\n': '\\n', '\r': '\\r', '\t': '\\t', '\b': '\\b', '\f': '\\f' }
|
||||||
|
return map[c] ?? '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0')
|
||||||
|
})
|
||||||
|
return JSON.parse('"' + escaped + '"')
|
||||||
|
}
|
||||||
|
|
||||||
|
const output = computed(() => {
|
||||||
|
const v = input.value
|
||||||
|
if (!v) return { text: '', error: '' }
|
||||||
|
try {
|
||||||
|
if (type.value === 'html') {
|
||||||
|
return { text: mode.value === 'encode' ? htmlEncode(v) : htmlDecode(v), error: '' }
|
||||||
|
}
|
||||||
|
return { text: mode.value === 'encode' ? jsonEncode(v) : jsonDecode(v), error: '' }
|
||||||
|
} catch (e) {
|
||||||
|
return { text: '', error: '转换失败:' + String(e) }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const swap = () => {
|
||||||
|
if (output.value.text) {
|
||||||
|
input.value = output.value.text
|
||||||
|
mode.value = mode.value === 'encode' ? 'decode' : 'encode'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<div class="flex items-center justify-between flex-wrap gap-3">
|
||||||
|
<div class="flex items-center gap-3 flex-wrap">
|
||||||
|
<Segmented
|
||||||
|
v-model="type"
|
||||||
|
label="类型"
|
||||||
|
:options="[
|
||||||
|
{ value: 'html', label: 'HTML' },
|
||||||
|
{ value: 'json', label: 'JSON 字符串' }
|
||||||
|
]"
|
||||||
|
/>
|
||||||
|
<Segmented
|
||||||
|
v-model="mode"
|
||||||
|
label="操作"
|
||||||
|
:options="[
|
||||||
|
{ value: 'encode', label: '转义' },
|
||||||
|
{ value: 'decode', label: '反转义' }
|
||||||
|
]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Button size="sm" variant="outline" class="h-8 text-sm gap-1" :disabled="!output.text" @click="swap">
|
||||||
|
<ArrowDownUp class="size-3.5" />
|
||||||
|
结果回填
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">原文 / 已转义文本</Label>
|
||||||
|
<Textarea v-model="input" placeholder="在此输入..." class="min-h-[120px] font-mono text-xs resize-y" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ResultArea :text="output.text" placeholder="结果" />
|
||||||
|
<p v-if="output.error" class="text-xs text-destructive">{{ output.error }}</p>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref, watch } from 'vue'
|
||||||
|
import { Upload } from '@lucide/vue'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Switch } from '@/components/ui/switch'
|
||||||
|
import Segmented from '../components/Segmented.vue'
|
||||||
|
import ResultArea from '../components/ResultArea.vue'
|
||||||
|
|
||||||
|
type HashAlgo = 'MD5' | 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512'
|
||||||
|
type Source = 'text' | 'file'
|
||||||
|
|
||||||
|
const algos: { value: HashAlgo; label: string }[] = [
|
||||||
|
{ value: 'MD5', label: 'MD5' },
|
||||||
|
{ value: 'SHA-1', label: 'SHA-1' },
|
||||||
|
{ value: 'SHA-256', label: 'SHA-256' },
|
||||||
|
{ value: 'SHA-384', label: 'SHA-384' },
|
||||||
|
{ value: 'SHA-512', label: 'SHA-512' }
|
||||||
|
]
|
||||||
|
|
||||||
|
const algo = ref<HashAlgo>('SHA-256')
|
||||||
|
const source = ref<Source>('text')
|
||||||
|
const uppercase = ref(false)
|
||||||
|
const useHmac = ref(false)
|
||||||
|
const hmacKey = ref('')
|
||||||
|
|
||||||
|
const input = ref('')
|
||||||
|
const output = ref('')
|
||||||
|
const loading = ref(false)
|
||||||
|
const error = ref('')
|
||||||
|
|
||||||
|
// ===== 文件 =====
|
||||||
|
const file = ref<File | null>(null)
|
||||||
|
const fileInput = ref<HTMLInputElement | null>(null)
|
||||||
|
const fileError = ref('')
|
||||||
|
const FILE_SIZE_LIMIT = 512 * 1024 * 1024 // 512MB 保护上限
|
||||||
|
|
||||||
|
function formatSize(bytes: number): string {
|
||||||
|
if (bytes < 1024) return `${bytes} B`
|
||||||
|
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
||||||
|
if (bytes < 1024 * 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} MB`
|
||||||
|
return `${(bytes / 1024 / 1024 / 1024).toFixed(2)} GB`
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onFileChange(e: Event) {
|
||||||
|
const el = e.target as HTMLInputElement
|
||||||
|
fileError.value = ''
|
||||||
|
file.value = el.files?.[0] ?? null
|
||||||
|
await compute()
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearFile() {
|
||||||
|
file.value = null
|
||||||
|
if (fileInput.value) fileInput.value.value = ''
|
||||||
|
void compute()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== MD5(WebCrypto 不支持,自行实现)=====
|
||||||
|
function md5(input: Uint8Array): string {
|
||||||
|
const S = [
|
||||||
|
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
|
||||||
|
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
|
||||||
|
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
|
||||||
|
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21
|
||||||
|
]
|
||||||
|
const K = new Uint32Array(64)
|
||||||
|
for (let i = 0; i < 64; i++) K[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296)
|
||||||
|
|
||||||
|
const len = input.length
|
||||||
|
const bitLenLo = (len * 8) >>> 0
|
||||||
|
const bitLenHi = Math.floor(len / 536870912) // len*8 / 2^32
|
||||||
|
const paddedLen = (((len + 8) >> 6) + 1) * 64
|
||||||
|
const msg = new Uint8Array(paddedLen)
|
||||||
|
msg.set(input)
|
||||||
|
msg[len] = 0x80
|
||||||
|
const dv = new DataView(msg.buffer)
|
||||||
|
dv.setUint32(paddedLen - 8, bitLenLo, true)
|
||||||
|
dv.setUint32(paddedLen - 4, bitLenHi, true)
|
||||||
|
|
||||||
|
let a0 = 0x67452301
|
||||||
|
let b0 = 0xefcdab89
|
||||||
|
let c0 = 0x98badcfe
|
||||||
|
let d0 = 0x10325476
|
||||||
|
const M = new Uint32Array(16)
|
||||||
|
for (let off = 0; off < paddedLen; off += 64) {
|
||||||
|
for (let i = 0; i < 16; i++) M[i] = dv.getUint32(off + i * 4, true)
|
||||||
|
let A = a0, B = b0, C = c0, D = d0
|
||||||
|
for (let i = 0; i < 64; i++) {
|
||||||
|
let F: number
|
||||||
|
let g: number
|
||||||
|
if (i < 16) { F = (B & C) | (~B & D); g = i }
|
||||||
|
else if (i < 32) { F = (D & B) | (~D & C); g = (5 * i + 1) % 16 }
|
||||||
|
else if (i < 48) { F = B ^ C ^ D; g = (3 * i + 5) % 16 }
|
||||||
|
else { F = C ^ (B | ~D); g = (7 * i) % 16 }
|
||||||
|
F = (F + A + K[i] + M[g]) >>> 0
|
||||||
|
A = D
|
||||||
|
D = C
|
||||||
|
C = B
|
||||||
|
B = (B + ((F << S[i]) | (F >>> (32 - S[i])))) >>> 0
|
||||||
|
}
|
||||||
|
a0 = (a0 + A) >>> 0
|
||||||
|
b0 = (b0 + B) >>> 0
|
||||||
|
c0 = (c0 + C) >>> 0
|
||||||
|
d0 = (d0 + D) >>> 0
|
||||||
|
}
|
||||||
|
const out = new Uint8Array(16)
|
||||||
|
const odv = new DataView(out.buffer)
|
||||||
|
odv.setUint32(0, a0, true)
|
||||||
|
odv.setUint32(4, b0, true)
|
||||||
|
odv.setUint32(8, c0, true)
|
||||||
|
odv.setUint32(12, d0, true)
|
||||||
|
return Array.from(out, b => b.toString(16).padStart(2, '0')).join('')
|
||||||
|
}
|
||||||
|
|
||||||
|
function toHex(buf: ArrayBuffer): string {
|
||||||
|
return Array.from(new Uint8Array(buf), b => b.toString(16).padStart(2, '0')).join('')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function compute() {
|
||||||
|
error.value = ''
|
||||||
|
fileError.value = ''
|
||||||
|
output.value = ''
|
||||||
|
if (source.value === 'text') {
|
||||||
|
const text = input.value
|
||||||
|
if (!text) return
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const data = new TextEncoder().encode(text)
|
||||||
|
output.value = await digest(algo.value, data)
|
||||||
|
} catch (e) {
|
||||||
|
error.value = '计算失败:' + String(e)
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const f = file.value
|
||||||
|
if (!f) return
|
||||||
|
if (f.size > FILE_SIZE_LIMIT) {
|
||||||
|
fileError.value = `文件过大(${formatSize(f.size)}),请使用 512MB 以内的文件`
|
||||||
|
return
|
||||||
|
}
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const data = new Uint8Array(await f.arrayBuffer())
|
||||||
|
output.value = await digest(algo.value, data)
|
||||||
|
} catch (e) {
|
||||||
|
error.value = '计算失败:' + String(e)
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function digest(algorithm: HashAlgo, data: Uint8Array): Promise<string> {
|
||||||
|
let hex: string
|
||||||
|
if (algorithm === 'MD5') {
|
||||||
|
hex = md5(data)
|
||||||
|
} else {
|
||||||
|
hex = toHex(await crypto.subtle.digest(algorithm, data))
|
||||||
|
}
|
||||||
|
if (useHmac.value) {
|
||||||
|
if (algorithm === 'MD5') {
|
||||||
|
throw new Error('HMAC 不支持 MD5,请选择 SHA 系列算法')
|
||||||
|
}
|
||||||
|
const enc = new TextEncoder()
|
||||||
|
const key = await crypto.subtle.importKey(
|
||||||
|
'raw', enc.encode(hmacKey.value),
|
||||||
|
{ name: 'HMAC', hash: { name: algorithm } },
|
||||||
|
false, ['sign']
|
||||||
|
)
|
||||||
|
hex = toHex(await crypto.subtle.sign('HMAC', key, data))
|
||||||
|
}
|
||||||
|
return hex
|
||||||
|
}
|
||||||
|
|
||||||
|
const displayOutput = computed(() =>
|
||||||
|
uppercase.value ? output.value.toUpperCase() : output.value
|
||||||
|
)
|
||||||
|
|
||||||
|
// 输入、算法、选项、文件变化时自动重算
|
||||||
|
watch([input, algo, source, uppercase, useHmac, hmacKey], () => {
|
||||||
|
void compute()
|
||||||
|
})
|
||||||
|
|
||||||
|
// 首次挂载如有初始值则计算(通常为空)
|
||||||
|
void compute()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<div class="flex items-center gap-3 flex-wrap">
|
||||||
|
<Segmented
|
||||||
|
v-model="source"
|
||||||
|
:options="[
|
||||||
|
{ value: 'text', label: '文本' },
|
||||||
|
{ value: 'file', label: '文件' }
|
||||||
|
]"
|
||||||
|
/>
|
||||||
|
<Segmented v-model="algo" label="算法" :options="algos" />
|
||||||
|
<label class="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
|
||||||
|
大写
|
||||||
|
<Switch v-model="uppercase" />
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="algo === 'MD5'" class="text-xs text-muted-foreground">
|
||||||
|
注:MD5 与 SHA-1 已不推荐用于安全场景,仅用于兼容旧系统或校验比对。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- HMAC -->
|
||||||
|
<div class="flex flex-col gap-2 rounded-md border border-border p-3">
|
||||||
|
<label class="flex items-center gap-2 text-xs cursor-pointer w-fit">
|
||||||
|
<Switch v-model="useHmac" />
|
||||||
|
<span class="font-medium">HMAC(密钥签名)</span>
|
||||||
|
</label>
|
||||||
|
<div v-if="useHmac" class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">密钥</Label>
|
||||||
|
<Input v-model="hmacKey" placeholder="HMAC 密钥(仅支持 SHA 系列)" class="font-mono text-sm" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 文本输入 -->
|
||||||
|
<div v-if="source === 'text'" class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">原文(文本)</Label>
|
||||||
|
<Textarea v-model="input" placeholder="在此输入文本..." class="min-h-[120px] font-mono text-xs resize-y" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 文件输入 -->
|
||||||
|
<div v-else class="flex flex-col gap-2">
|
||||||
|
<Label class="text-xs">选择文件</Label>
|
||||||
|
<div class="flex items-center gap-2 flex-wrap">
|
||||||
|
<Button size="sm" variant="outline" class="h-8 text-sm gap-1.5" @click="fileInput?.click()">
|
||||||
|
<Upload class="size-3.5" />
|
||||||
|
选择文件
|
||||||
|
</Button>
|
||||||
|
<input ref="fileInput" type="file" class="hidden" @change="onFileChange" />
|
||||||
|
<template v-if="file">
|
||||||
|
<span class="text-xs font-mono text-muted-foreground">{{ file.name }}({{ formatSize(file.size) }})</span>
|
||||||
|
<Button size="sm" variant="ghost" class="h-7 text-xs" @click="clearFile">移除</Button>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
<p v-if="fileError" class="text-xs text-destructive">{{ fileError }}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ResultArea :text="loading ? '计算中...' : displayOutput" :label="useHmac ? 'HMAC 摘要(十六进制)' : '摘要(十六进制)'" placeholder="摘要" />
|
||||||
|
<p v-if="error" class="text-xs text-destructive">{{ error }}</p>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import Segmented from '../components/Segmented.vue'
|
||||||
|
|
||||||
|
type Tab = 'status' | 'mime'
|
||||||
|
|
||||||
|
const tab = ref<Tab>('status')
|
||||||
|
const query = ref('')
|
||||||
|
|
||||||
|
interface StatusDef {
|
||||||
|
code: number
|
||||||
|
name: string
|
||||||
|
desc: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const STATUSES: StatusDef[] = [
|
||||||
|
// 1xx
|
||||||
|
{ code: 100, name: 'Continue', desc: '客户端应继续请求,常用于 Expect: 100-continue 大文件上传前探测' },
|
||||||
|
{ code: 101, name: 'Switching Protocols', desc: '服务器同意切换协议(如升级 WebSocket)' },
|
||||||
|
{ code: 102, name: 'Processing', desc: '服务器已收到请求,仍在处理(WebDAV)' },
|
||||||
|
{ code: 103, name: 'Early Hints', desc: '预加载提示,主响应前先返回 Link 头' },
|
||||||
|
// 2xx
|
||||||
|
{ code: 200, name: 'OK', desc: '请求成功' },
|
||||||
|
{ code: 201, name: 'Created', desc: '请求成功并创建了新资源(POST 之后常见)' },
|
||||||
|
{ code: 202, name: 'Accepted', desc: '请求已受理,但尚未处理完成(异步任务)' },
|
||||||
|
{ code: 204, name: 'No Content', desc: '成功但无返回体(DELETE / PUT 常见)' },
|
||||||
|
{ code: 206, name: 'Partial Content', desc: '范围请求成功(断点续传 / 视频拖动)' },
|
||||||
|
// 3xx
|
||||||
|
{ code: 301, name: 'Moved Permanently', desc: '永久重定向,搜索引擎更新链接(GET 保持、POST 可能转 GET)' },
|
||||||
|
{ code: 302, name: 'Found', desc: '临时重定向,浏览器可能将 POST 改为 GET' },
|
||||||
|
{ code: 303, name: 'See Other', desc: '临时重定向,强制使用 GET 访问新地址' },
|
||||||
|
{ code: 304, name: 'Not Modified', desc: '缓存有效(协商缓存命中,无返回体)' },
|
||||||
|
{ code: 307, name: 'Temporary Redirect', desc: '临时重定向,严格保持原请求方法与体' },
|
||||||
|
{ code: 308, name: 'Permanent Redirect', desc: '永久重定向,严格保持原请求方法与体' },
|
||||||
|
// 4xx
|
||||||
|
{ code: 400, name: 'Bad Request', desc: '请求语法错误 / 参数校验失败' },
|
||||||
|
{ code: 401, name: 'Unauthorized', desc: '未认证(缺少或无效的凭证,应带 WWW-Authenticate 头)' },
|
||||||
|
{ code: 402, name: 'Payment Required', desc: '要求付费(保留状态码,实际很少使用)' },
|
||||||
|
{ code: 403, name: 'Forbidden', desc: '已认证但无权限访问该资源' },
|
||||||
|
{ code: 404, name: 'Not Found', desc: '资源不存在' },
|
||||||
|
{ code: 405, name: 'Method Not Allowed', desc: '方法不被允许(应返回 Allow 头)' },
|
||||||
|
{ code: 406, name: 'Not Acceptable', desc: '请求的 Accept 头无法满足内容协商' },
|
||||||
|
{ code: 408, name: 'Request Timeout', desc: '客户端请求超时' },
|
||||||
|
{ code: 409, name: 'Conflict', desc: '请求与当前资源状态冲突(并发编辑 / 版本冲突)' },
|
||||||
|
{ code: 410, name: 'Gone', desc: '资源已永久消失(区别于 404)' },
|
||||||
|
{ code: 412, name: 'Precondition Failed', desc: '前置条件失败(If-Match / If-None-Match 校验不过)' },
|
||||||
|
{ code: 413, name: 'Content Too Large', desc: '请求体超过服务器限制' },
|
||||||
|
{ code: 415, name: 'Unsupported Media Type', desc: 'Content-Type 不支持' },
|
||||||
|
{ code: 418, name: "I'm a teapot", desc: '愚人节彩蛋:我是茶壶' },
|
||||||
|
{ code: 422, name: 'Unprocessable Content', desc: '语义正确但校验失败(表单校验常用)' },
|
||||||
|
{ code: 425, name: 'Too Early', desc: '过早重放(防重放攻击)' },
|
||||||
|
{ code: 428, name: 'Precondition Required', desc: '要求带条件请求头(防丢失更新)' },
|
||||||
|
{ code: 429, name: 'Too Many Requests', desc: '请求频率超限(限流,应带 Retry-After 头)' },
|
||||||
|
{ code: 431, name: 'Request Header Fields Too Large', desc: '请求头过大(Cookie 太多常见)' },
|
||||||
|
{ code: 451, name: 'Unavailable For Legal Reasons', desc: '因法律原因不可提供(审查)' },
|
||||||
|
// 5xx
|
||||||
|
{ code: 500, name: 'Internal Server Error', desc: '服务器内部错误(后端异常兜底)' },
|
||||||
|
{ code: 501, name: 'Not Implemented', desc: '服务器不支持该功能' },
|
||||||
|
{ code: 502, name: 'Bad Gateway', desc: '网关收到上游无效响应(后端挂了 / 崩溃)' },
|
||||||
|
{ code: 503, name: 'Service Unavailable', desc: '服务不可用(过载 / 维护中,可带 Retry-After)' },
|
||||||
|
{ code: 504, name: 'Gateway Timeout', desc: '网关等待上游超时(后端太慢)' },
|
||||||
|
{ code: 505, name: 'HTTP Version Not Supported', desc: 'HTTP 版本不支持' },
|
||||||
|
{ code: 507, name: 'Insufficient Storage', desc: '存储不足(WebDAV)' },
|
||||||
|
{ code: 508, name: 'Loop Detected', desc: '检测到无限循环(WebDAV)' },
|
||||||
|
{ code: 511, name: 'Network Authentication Required', desc: '需要网络认证(公共 Wi-Fi 门户)' }
|
||||||
|
]
|
||||||
|
|
||||||
|
interface MimeDef {
|
||||||
|
mime: string
|
||||||
|
ext: string
|
||||||
|
desc: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const MIMES: MimeDef[] = [
|
||||||
|
{ mime: 'text/html', ext: '.html .htm', desc: 'HTML 文档' },
|
||||||
|
{ mime: 'text/plain', ext: '.txt', desc: '纯文本' },
|
||||||
|
{ mime: 'text/css', ext: '.css', desc: '样式表' },
|
||||||
|
{ mime: 'text/javascript', ext: '.js .mjs', desc: 'JavaScript(旧写法 application/javascript)' },
|
||||||
|
{ mime: 'application/json', ext: '.json', desc: 'JSON 数据(API 最常用)' },
|
||||||
|
{ mime: 'application/xml', ext: '.xml', desc: 'XML 数据' },
|
||||||
|
{ mime: 'application/yaml', ext: '.yaml .yml', desc: 'YAML 配置' },
|
||||||
|
{ mime: 'application/toml', ext: '.toml', desc: 'TOML 配置' },
|
||||||
|
{ mime: 'text/csv', ext: '.csv', desc: '逗号分隔表格' },
|
||||||
|
{ mime: 'text/markdown', ext: '.md', desc: 'Markdown 文档' },
|
||||||
|
{ mime: 'image/jpeg', ext: '.jpg .jpeg', desc: 'JPEG 图片(有损压缩)' },
|
||||||
|
{ mime: 'image/png', ext: '.png', desc: 'PNG 图片(无损,支持透明)' },
|
||||||
|
{ mime: 'image/gif', ext: '.gif', desc: 'GIF 动图' },
|
||||||
|
{ mime: 'image/webp', ext: '.webp', desc: 'WebP 图片(现代格式,体积小)' },
|
||||||
|
{ mime: 'image/svg+xml', ext: '.svg', desc: 'SVG 矢量图' },
|
||||||
|
{ mime: 'image/avif', ext: '.avif', desc: 'AVIF 图片(新一代压缩)' },
|
||||||
|
{ mime: 'image/x-icon', ext: '.ico', desc: '网站图标' },
|
||||||
|
{ mime: 'audio/mpeg', ext: '.mp3', desc: 'MP3 音频' },
|
||||||
|
{ mime: 'audio/ogg', ext: '.ogg', desc: 'OGG 音频' },
|
||||||
|
{ mime: 'audio/wav', ext: '.wav', desc: 'WAV 无损音频' },
|
||||||
|
{ mime: 'video/mp4', ext: '.mp4', desc: 'MP4 视频' },
|
||||||
|
{ mime: 'video/webm', ext: '.webm', desc: 'WebM 视频' },
|
||||||
|
{ mime: 'video/x-matroska', ext: '.mkv', desc: 'MKV 视频' },
|
||||||
|
{ mime: 'application/pdf', ext: '.pdf', desc: 'PDF 文档' },
|
||||||
|
{ mime: 'application/zip', ext: '.zip', desc: 'ZIP 压缩包' },
|
||||||
|
{ mime: 'application/x-7z-compressed', ext: '.7z', desc: '7z 压缩包' },
|
||||||
|
{ mime: 'application/x-rar-compressed', ext: '.rar', desc: 'RAR 压缩包' },
|
||||||
|
{ mime: 'application/gzip', ext: '.gz', desc: 'GZip 压缩' },
|
||||||
|
{ mime: 'application/x-tar', ext: '.tar', desc: 'TAR 归档' },
|
||||||
|
{ mime: 'application/octet-stream', ext: '(默认)', desc: '未知二进制(浏览器会下载)' },
|
||||||
|
{ mime: 'application/wasm', ext: '.wasm', desc: 'WebAssembly 模块' },
|
||||||
|
{ mime: 'font/woff', ext: '.woff', desc: 'Web 字体(压缩)' },
|
||||||
|
{ mime: 'font/woff2', ext: '.woff2', desc: 'Web 字体(现代格式)' },
|
||||||
|
{ mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', ext: '.docx', desc: 'Word 文档' },
|
||||||
|
{ mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ext: '.xlsx', desc: 'Excel 表格' },
|
||||||
|
{ mime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation', ext: '.pptx', desc: 'PPT 演示文稿' },
|
||||||
|
{ mime: 'application/msword', ext: '.doc', desc: 'Word 旧格式' },
|
||||||
|
{ mime: 'application/vnd.ms-excel', ext: '.xls', desc: 'Excel 旧格式' },
|
||||||
|
{ mime: 'multipart/form-data', ext: '(表单)', desc: '文件上传表单(带 boundary)' },
|
||||||
|
{ mime: 'application/x-www-form-urlencoded', ext: '(表单)', desc: 'URL 编码表单(默认)' },
|
||||||
|
{ mime: 'application/grpc', ext: '(RPC)', desc: 'gRPC 请求(配合 proto)' }
|
||||||
|
]
|
||||||
|
|
||||||
|
const STATUS_CLASS: Record<string, string> = {
|
||||||
|
'1xx': 'bg-sky-500/10 text-sky-600 dark:text-sky-400 border-sky-500/30',
|
||||||
|
'2xx': 'bg-green-500/10 text-green-600 dark:text-green-400 border-green-500/30',
|
||||||
|
'3xx': 'bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/30',
|
||||||
|
'4xx': 'bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/30',
|
||||||
|
'5xx': 'bg-red-500/10 text-red-600 dark:text-red-400 border-red-500/30'
|
||||||
|
}
|
||||||
|
|
||||||
|
const statusGroups = computed(() => {
|
||||||
|
const q = query.value.trim().toLowerCase()
|
||||||
|
const filtered = q
|
||||||
|
? STATUSES.filter(s => String(s.code).includes(q) || s.name.toLowerCase().includes(q) || s.desc.toLowerCase().includes(q))
|
||||||
|
: STATUSES
|
||||||
|
const groups: Array<{ label: string; class: string; items: StatusDef[] }> = []
|
||||||
|
for (const [label, cls] of Object.entries(STATUS_CLASS)) {
|
||||||
|
const items = filtered.filter(s => String(s.code).startsWith(label[0]))
|
||||||
|
if (items.length > 0) groups.push({ label: `${label} ${label === '1xx' ? '信息' : label === '2xx' ? '成功' : label === '3xx' ? '重定向' : label === '4xx' ? '客户端错误' : '服务器错误'}`, class: cls, items })
|
||||||
|
}
|
||||||
|
return groups
|
||||||
|
})
|
||||||
|
|
||||||
|
const filteredMimes = computed(() => {
|
||||||
|
const q = query.value.trim().toLowerCase()
|
||||||
|
if (!q) return MIMES
|
||||||
|
return MIMES.filter(m => m.mime.includes(q) || m.ext.includes(q) || m.desc.toLowerCase().includes(q))
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<div class="flex items-center gap-3 flex-wrap">
|
||||||
|
<Segmented
|
||||||
|
v-model="tab"
|
||||||
|
:options="[
|
||||||
|
{ value: 'status', label: 'HTTP 状态码' },
|
||||||
|
{ value: 'mime', label: 'MIME 类型' }
|
||||||
|
]"
|
||||||
|
/>
|
||||||
|
<div class="relative flex-1 min-w-[160px] max-w-xs">
|
||||||
|
<Input v-model="query" placeholder="搜索…" class="h-8 text-sm" />
|
||||||
|
</div>
|
||||||
|
<span class="text-xs text-muted-foreground ml-auto">
|
||||||
|
{{ tab === 'status' ? `${STATUSES.length} 个状态码` : `${MIMES.length} 个常用类型` }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 状态码 -->
|
||||||
|
<template v-if="tab === 'status'">
|
||||||
|
<div v-for="group in statusGroups" :key="group.label" class="flex flex-col gap-2">
|
||||||
|
<span class="text-xs font-medium text-muted-foreground">{{ group.label }}</span>
|
||||||
|
<div class="rounded-md border border-border divide-y divide-border text-xs">
|
||||||
|
<div v-for="s in group.items" :key="s.code" class="flex items-start gap-3 px-3 py-2">
|
||||||
|
<Badge variant="outline" :class="['py-0 shrink-0 font-mono', group.class]">{{ s.code }}</Badge>
|
||||||
|
<div class="flex flex-col gap-0.5 min-w-0">
|
||||||
|
<span class="font-medium">{{ s.name }}</span>
|
||||||
|
<span class="text-muted-foreground leading-snug">{{ s.desc }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p v-if="statusGroups.length === 0" class="text-xs text-muted-foreground">没有匹配的状态码。</p>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- MIME -->
|
||||||
|
<template v-else>
|
||||||
|
<div class="rounded-md border border-border divide-y divide-border text-xs">
|
||||||
|
<div v-for="m in filteredMimes" :key="m.mime" class="flex items-start gap-3 px-3 py-2">
|
||||||
|
<span class="font-mono text-primary break-all w-64 shrink-0">{{ m.mime }}</span>
|
||||||
|
<span class="font-mono text-muted-foreground w-20 shrink-0">{{ m.ext }}</span>
|
||||||
|
<span class="text-muted-foreground min-w-0">{{ m.desc }}</span>
|
||||||
|
</div>
|
||||||
|
<div v-if="filteredMimes.length === 0" class="px-3 py-2 text-muted-foreground">没有匹配的 MIME 类型。</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import Segmented from '../components/Segmented.vue'
|
||||||
|
import ResultArea from '../components/ResultArea.vue'
|
||||||
|
|
||||||
|
type Tab = 'cidr' | 'convert'
|
||||||
|
|
||||||
|
const tab = ref<Tab>('cidr')
|
||||||
|
|
||||||
|
// ===== CIDR 计算 =====
|
||||||
|
const cidrInput = ref('192.168.1.0/24')
|
||||||
|
|
||||||
|
function parseIPv4(s: string): bigint | null {
|
||||||
|
const parts = s.trim().split('.')
|
||||||
|
if (parts.length !== 4) return null
|
||||||
|
let n = 0n
|
||||||
|
for (const p of parts) {
|
||||||
|
if (!/^\d{1,3}$/.test(p)) return null
|
||||||
|
const v = Number(p)
|
||||||
|
if (v > 255) return null
|
||||||
|
n = (n << 8n) | BigInt(v)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
function ipToString(n: bigint): string {
|
||||||
|
return [24n, 16n, 8n, 0n].map(shift => String((n >> shift) & 0xffn)).join('.')
|
||||||
|
}
|
||||||
|
|
||||||
|
const cidr = computed(() => {
|
||||||
|
const s = cidrInput.value.trim()
|
||||||
|
if (!s) return null
|
||||||
|
const [ipPart, maskPart] = s.split('/')
|
||||||
|
const ip = parseIPv4(ipPart)
|
||||||
|
if (ip === null) return { error: 'IPv4 地址格式不正确' }
|
||||||
|
let prefix: number
|
||||||
|
if (maskPart === undefined) {
|
||||||
|
prefix = 24
|
||||||
|
} else {
|
||||||
|
prefix = Number(maskPart)
|
||||||
|
if (!Number.isInteger(prefix) || prefix < 0 || prefix > 32) {
|
||||||
|
return { error: '前缀长度应在 0-32 之间' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const mask = prefix === 0 ? 0n : (0xffffffffn << BigInt(32 - prefix)) & 0xffffffffn
|
||||||
|
const network = ip & mask
|
||||||
|
const broadcast = network | (~mask & 0xffffffffn)
|
||||||
|
const total = 1n << BigInt(32 - prefix)
|
||||||
|
// 主机数:/31 无主机位(点对点),/32 单主机
|
||||||
|
const hosts = prefix >= 31 ? total : total - 2n
|
||||||
|
const firstHost = prefix >= 31 ? network : network + 1n
|
||||||
|
const lastHost = prefix >= 31 ? broadcast : broadcast - 1n
|
||||||
|
const wildcard = ~mask & 0xffffffffn
|
||||||
|
// 私有地址判断
|
||||||
|
const privateNote =
|
||||||
|
(ip >> 24n) === 10n ? 'A 类私有(10.0.0.0/8)'
|
||||||
|
: (ip >> 20n) === 0xac1n ? 'B 类私有(172.16.0.0/12)'
|
||||||
|
: (ip >> 16n) === 0xc0a8n ? 'C 类私有(192.168.0.0/16)'
|
||||||
|
: (ip >> 28n) === 14n ? '环回/保留(240.0.0.0/4)'
|
||||||
|
: ip === 0n ? '未指定地址'
|
||||||
|
: (ip >> 24n) === 127n ? '环回地址(127.0.0.0/8)'
|
||||||
|
: (ip >> 24n) === 169n && (ip >> 16n) === 0xa9fen ? '链路本地(169.254.0.0/16)'
|
||||||
|
: '公网地址'
|
||||||
|
return {
|
||||||
|
error: '',
|
||||||
|
network: ipToString(network),
|
||||||
|
broadcast: ipToString(broadcast),
|
||||||
|
mask: ipToString(mask),
|
||||||
|
wildcard: ipToString(wildcard),
|
||||||
|
firstHost: ipToString(firstHost),
|
||||||
|
lastHost: ipToString(lastHost),
|
||||||
|
hosts: hosts.toLocaleString(),
|
||||||
|
total: total.toLocaleString(),
|
||||||
|
prefix,
|
||||||
|
isAligned: (ip & mask) === network,
|
||||||
|
ipIsNetwork: ip === network,
|
||||||
|
privateNote,
|
||||||
|
binaryMask: ipToString(mask).split('.').map(p => Number(p).toString(2).padStart(8, '0')).join('.')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// ===== IP ↔ 整数互转 =====
|
||||||
|
const convertInput = ref('192.168.1.1')
|
||||||
|
|
||||||
|
const converted = computed(() => {
|
||||||
|
const s = convertInput.value.trim()
|
||||||
|
if (!s) return null
|
||||||
|
const ip = parseIPv4(s)
|
||||||
|
if (ip !== null) {
|
||||||
|
return {
|
||||||
|
dec: ip.toString(),
|
||||||
|
hex: '0x' + ip.toString(16).padStart(8, '0').toUpperCase(),
|
||||||
|
oct: ip.toString(8),
|
||||||
|
bin: ip.toString(2).padStart(32, '0').replace(/(.{8})(?=.)/g, '$1 '),
|
||||||
|
binaryMask: ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 尝试十进制整数
|
||||||
|
if (/^\d+$/.test(s)) {
|
||||||
|
const n = BigInt(s)
|
||||||
|
if (n <= 0xffffffffn) {
|
||||||
|
return { dec: s, hex: '0x' + n.toString(16).padStart(8, '0').toUpperCase(), oct: n.toString(8), bin: n.toString(2).padStart(32, '0').replace(/(.{8})(?=.)/g, '$1 '), binaryMask: '' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<Segmented
|
||||||
|
v-model="tab"
|
||||||
|
:options="[
|
||||||
|
{ value: 'cidr', label: 'CIDR 子网计算' },
|
||||||
|
{ value: 'convert', label: 'IP ↔ 整数' }
|
||||||
|
]"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<!-- CIDR -->
|
||||||
|
<template v-if="tab === 'cidr'">
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">IPv4 地址 / 前缀(如 192.168.1.100/26)</Label>
|
||||||
|
<Input v-model="cidrInput" placeholder="192.168.1.0/24" class="font-mono text-sm" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-if="cidr">
|
||||||
|
<p v-if="cidr.error" class="text-xs text-destructive">{{ cidr.error }}</p>
|
||||||
|
<template v-else>
|
||||||
|
<p v-if="!cidr.ipIsNetwork" class="text-xs text-amber-600 dark:text-amber-400">
|
||||||
|
注意:输入地址不是该子网的网络地址,已按网络 {{ cidr.network }}/{{ cidr.prefix }} 计算。
|
||||||
|
</p>
|
||||||
|
<div class="rounded-md border border-border divide-y divide-border text-xs">
|
||||||
|
<div class="flex gap-3 px-3 py-1.5">
|
||||||
|
<span class="w-24 shrink-0 text-muted-foreground">网络地址</span>
|
||||||
|
<span class="font-mono">{{ cidr.network }}/{{ cidr.prefix }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex gap-3 px-3 py-1.5">
|
||||||
|
<span class="w-24 shrink-0 text-muted-foreground">子网掩码</span>
|
||||||
|
<span class="font-mono">{{ cidr.mask }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex gap-3 px-3 py-1.5">
|
||||||
|
<span class="w-24 shrink-0 text-muted-foreground">掩码二进制</span>
|
||||||
|
<span class="font-mono break-all">{{ cidr.binaryMask }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex gap-3 px-3 py-1.5">
|
||||||
|
<span class="w-24 shrink-0 text-muted-foreground">反掩码</span>
|
||||||
|
<span class="font-mono">{{ cidr.wildcard }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex gap-3 px-3 py-1.5">
|
||||||
|
<span class="w-24 shrink-0 text-muted-foreground">广播地址</span>
|
||||||
|
<span class="font-mono">{{ cidr.broadcast }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex gap-3 px-3 py-1.5">
|
||||||
|
<span class="w-24 shrink-0 text-muted-foreground">可用主机范围</span>
|
||||||
|
<span class="font-mono">{{ cidr.firstHost }} ~ {{ cidr.lastHost }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex gap-3 px-3 py-1.5">
|
||||||
|
<span class="w-24 shrink-0 text-muted-foreground">可用主机数</span>
|
||||||
|
<span class="font-mono">{{ cidr.hosts }}(地址总数 {{ cidr.total }})</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex gap-3 px-3 py-1.5">
|
||||||
|
<span class="w-24 shrink-0 text-muted-foreground">地址类型</span>
|
||||||
|
<span>{{ cidr.privateNote }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</template>
|
||||||
|
<p v-else class="text-xs text-muted-foreground">输入 IPv4 地址与 CIDR 前缀,自动计算子网信息。</p>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- IP ↔ 整数 -->
|
||||||
|
<template v-else>
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">IP 地址或无符号整数</Label>
|
||||||
|
<Input v-model="convertInput" placeholder="192.168.1.1 或 3232235777" class="font-mono text-sm" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-if="converted">
|
||||||
|
<ResultArea :text="converted.dec" label="十进制整数" placeholder="十进制" minHeight="60px" />
|
||||||
|
<ResultArea :text="converted.hex" label="十六进制" placeholder="十六进制" minHeight="60px" />
|
||||||
|
<ResultArea :text="converted.oct" label="八进制" placeholder="八进制" minHeight="60px" />
|
||||||
|
<ResultArea :text="converted.bin" label="二进制" placeholder="二进制" minHeight="60px" />
|
||||||
|
</template>
|
||||||
|
<p v-else-if="convertInput" class="text-xs text-destructive">无法识别的输入(支持 IPv4 地址或 0-4294967295 整数)。</p>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import Segmented from '../components/Segmented.vue'
|
||||||
|
import ResultArea from '../components/ResultArea.vue'
|
||||||
|
|
||||||
|
const mode = ref<'format' | 'minify'>('format')
|
||||||
|
const indent = ref('2')
|
||||||
|
const sortKeys = ref(false)
|
||||||
|
const input = ref('')
|
||||||
|
|
||||||
|
const result = computed<{ text: string; error: string }>(() => {
|
||||||
|
const v = input.value.trim()
|
||||||
|
if (!v) return { text: '', error: '' }
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(v)
|
||||||
|
if (mode.value === 'minify') {
|
||||||
|
return { text: JSON.stringify(parsed), error: '' }
|
||||||
|
}
|
||||||
|
return { text: JSON.stringify(parsed, normalizeReplacer(sortKeys.value), Number(indent.value)), error: '' }
|
||||||
|
} catch (e) {
|
||||||
|
return { text: '', error: 'JSON 解析失败:' + String(e) }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const output = computed(() => result.value.text)
|
||||||
|
const error = computed(() => result.value.error)
|
||||||
|
|
||||||
|
const isValid = computed<boolean | null>(() => {
|
||||||
|
if (!input.value.trim()) return null
|
||||||
|
try {
|
||||||
|
JSON.parse(input.value)
|
||||||
|
return true
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
/** 深浅不一:sortKeys 时按 key 排序输出 */
|
||||||
|
function normalizeReplacer(sort: boolean): (this: unknown, key: string, value: unknown) => unknown {
|
||||||
|
if (!sort) return undefined as never
|
||||||
|
return function (this: unknown, _key: string, value: unknown) {
|
||||||
|
if (Array.isArray(value)) return value
|
||||||
|
if (value && typeof value === 'object') {
|
||||||
|
const obj = value as Record<string, unknown>
|
||||||
|
const sorted: Record<string, unknown> = {}
|
||||||
|
Object.keys(obj)
|
||||||
|
.sort()
|
||||||
|
.forEach(k => { sorted[k] = obj[k] })
|
||||||
|
return sorted
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<div class="flex items-center justify-between flex-wrap gap-3">
|
||||||
|
<div class="flex items-center gap-3 flex-wrap">
|
||||||
|
<Segmented
|
||||||
|
v-model="mode"
|
||||||
|
:options="[
|
||||||
|
{ value: 'format', label: '美化' },
|
||||||
|
{ value: 'minify', label: '压缩' }
|
||||||
|
]"
|
||||||
|
/>
|
||||||
|
<Segmented
|
||||||
|
v-model="indent"
|
||||||
|
label="缩进"
|
||||||
|
:options="[
|
||||||
|
{ value: '2', label: '2' },
|
||||||
|
{ value: '4', label: '4' },
|
||||||
|
{ value: '8', label: '8' }
|
||||||
|
]"
|
||||||
|
/>
|
||||||
|
<label class="flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer">
|
||||||
|
<input v-model="sortKeys" type="checkbox" class="accent-primary size-3.5" />
|
||||||
|
键排序
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">原始 JSON</Label>
|
||||||
|
<Textarea v-model="input" placeholder='输入 JSON,如 {"a":1,"b":[true,null]}' class="min-h-[160px] font-mono text-xs resize-y" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="isValid !== false" class="flex items-center gap-2 text-xs">
|
||||||
|
<span v-if="isValid === true" class="text-green-600 dark:text-green-400">✓ 合法 JSON</span>
|
||||||
|
</div>
|
||||||
|
<ResultArea :text="output" placeholder="结果" />
|
||||||
|
<p v-if="error" class="text-xs text-destructive break-all">{{ error }}</p>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import ResultArea from '../components/ResultArea.vue'
|
||||||
|
|
||||||
|
const token = ref('')
|
||||||
|
const error = ref('')
|
||||||
|
|
||||||
|
function base64UrlDecode(s: string): string {
|
||||||
|
const cleaned = s.replace(/-/g, '+').replace(/_/g, '/')
|
||||||
|
const pad = cleaned.length % 4
|
||||||
|
const normalized = pad ? cleaned + '='.repeat(4 - pad) : cleaned
|
||||||
|
const bin = atob(normalized)
|
||||||
|
const bytes = Uint8Array.from(bin, ch => ch.charCodeAt(0))
|
||||||
|
return new TextDecoder().decode(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TimeClaim {
|
||||||
|
name: string
|
||||||
|
value: string
|
||||||
|
local: string
|
||||||
|
status: 'ok' | 'expired' | 'not-yet' | 'unknown'
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = computed<{
|
||||||
|
header: string
|
||||||
|
payload: string
|
||||||
|
signature: string
|
||||||
|
timeClaims: TimeClaim[]
|
||||||
|
} | null>(() => {
|
||||||
|
error.value = ''
|
||||||
|
const t = token.value.trim()
|
||||||
|
if (!t) return null
|
||||||
|
const parts = t.split('.')
|
||||||
|
if (parts.length < 2) {
|
||||||
|
error.value = 'JWT 格式不正确(应为 header.payload.signature)'
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const header = formatJson(base64UrlDecode(parts[0]))
|
||||||
|
const payload = formatJson(base64UrlDecode(parts[1]))
|
||||||
|
const signature = parts[2] ?? ''
|
||||||
|
return { header, payload, signature, timeClaims: parseTimeClaims(payload) }
|
||||||
|
} catch (e) {
|
||||||
|
error.value = '解码失败:' + String(e)
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
function formatJson(s: string): string {
|
||||||
|
let pretty = s
|
||||||
|
try {
|
||||||
|
pretty = JSON.stringify(JSON.parse(s), null, 2)
|
||||||
|
} catch {
|
||||||
|
/* 非 JSON(如已损毁),原样展示 */
|
||||||
|
}
|
||||||
|
return pretty
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 解读 iat / nbf / exp 等时间声明(秒级时间戳) */
|
||||||
|
function parseTimeClaims(payload: string): TimeClaim[] {
|
||||||
|
let obj: unknown
|
||||||
|
try {
|
||||||
|
obj = JSON.parse(payload)
|
||||||
|
} catch {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
if (!obj || typeof obj !== 'object') return []
|
||||||
|
const p = obj as Record<string, unknown>
|
||||||
|
const claims: TimeClaim[] = []
|
||||||
|
const now = Math.floor(Date.now() / 1000)
|
||||||
|
const NAMES: Record<string, string> = { iat: 'iat(签发时间)', nbf: 'nbf(生效时间)', exp: 'exp(过期时间)' }
|
||||||
|
const pad = (x: number) => String(x).padStart(2, '0')
|
||||||
|
for (const key of ['iat', 'nbf', 'exp']) {
|
||||||
|
const v = p[key]
|
||||||
|
if (typeof v !== 'number' || !Number.isFinite(v)) continue
|
||||||
|
const d = new Date(v * 1000)
|
||||||
|
if (Number.isNaN(d.getTime())) continue
|
||||||
|
const local = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
|
||||||
|
let status: TimeClaim['status'] = 'ok'
|
||||||
|
if (key === 'exp' && v < now) status = 'expired'
|
||||||
|
else if (key === 'nbf' && v > now) status = 'not-yet'
|
||||||
|
else if (key === 'iat' && v > now + 60) status = 'unknown'
|
||||||
|
claims.push({ name: NAMES[key], value: String(v), local, status })
|
||||||
|
}
|
||||||
|
return claims
|
||||||
|
}
|
||||||
|
|
||||||
|
const STATUS_BADGE: Record<TimeClaim['status'], { label: string; class: string } | null> = {
|
||||||
|
ok: null,
|
||||||
|
expired: { label: '已过期', class: 'bg-red-500/10 text-red-600 dark:text-red-400 border-red-500/30' },
|
||||||
|
'not-yet': { label: '尚未生效', class: 'bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/30' },
|
||||||
|
unknown: { label: '签发时间在未来(时钟偏差?)', class: 'bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/30' }
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">JWT Token</Label>
|
||||||
|
<Textarea
|
||||||
|
v-model="token"
|
||||||
|
placeholder="eyJhbGciOi...(header.payload.signature)"
|
||||||
|
class="min-h-[70px] font-mono text-xs resize-y break-all"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-if="parsed">
|
||||||
|
<ResultArea :text="parsed.header" label="Header" placeholder="Header" />
|
||||||
|
<ResultArea :text="parsed.payload" label="Payload(载荷)" placeholder="Payload" />
|
||||||
|
<ResultArea :text="parsed.signature" label="Signature(签名)" placeholder="Signature" />
|
||||||
|
|
||||||
|
<div v-if="parsed.timeClaims.length > 0" class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">时间声明解读</Label>
|
||||||
|
<div class="rounded-md border border-border divide-y divide-border text-xs">
|
||||||
|
<div v-for="c in parsed.timeClaims" :key="c.name" class="flex items-center gap-3 px-3 py-2 flex-wrap">
|
||||||
|
<span class="font-mono text-muted-foreground">{{ c.name }}</span>
|
||||||
|
<span class="font-mono">{{ c.local }}</span>
|
||||||
|
<Badge v-if="STATUS_BADGE[c.status]" variant="outline" :class="['py-0 text-[10px] ml-auto', STATUS_BADGE[c.status]!.class]">
|
||||||
|
{{ STATUS_BADGE[c.status]!.label }}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<p v-else-if="!token" class="text-xs text-muted-foreground">在左侧粘贴 JWT,下方将自动解析 Header 与 Payload。</p>
|
||||||
|
<p v-else class="text-xs text-destructive">{{ error }}</p>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, ref } from 'vue'
|
||||||
|
import { Copy, RefreshCw } from '@lucide/vue'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Switch } from '@/components/ui/switch'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
|
||||||
|
const CHARSETS = {
|
||||||
|
lower: 'abcdefghijklmnopqrstuvwxyz',
|
||||||
|
upper: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
|
||||||
|
digits: '0123456789',
|
||||||
|
symbols: '!@#$%^&*_-+=?',
|
||||||
|
// 易混淆字符:l/1/I、O/0、等等
|
||||||
|
ambiguous: 'Il1O0o`\'"|'
|
||||||
|
}
|
||||||
|
|
||||||
|
const length = ref('16')
|
||||||
|
const count = ref('5')
|
||||||
|
const useLower = ref(true)
|
||||||
|
const useUpper = ref(true)
|
||||||
|
const useDigits = ref(true)
|
||||||
|
const useSymbols = ref(false)
|
||||||
|
const excludeAmbiguous = ref(true)
|
||||||
|
|
||||||
|
const passwords = ref<string[]>([])
|
||||||
|
const error = ref('')
|
||||||
|
|
||||||
|
const lengthNum = computed(() => {
|
||||||
|
const n = Math.floor(Number(length.value))
|
||||||
|
if (!Number.isFinite(n)) return 16
|
||||||
|
return Math.min(Math.max(n || 0, 4), 128)
|
||||||
|
})
|
||||||
|
|
||||||
|
const countNum = computed(() => {
|
||||||
|
const n = Math.floor(Number(count.value))
|
||||||
|
if (!Number.isFinite(n)) return 5
|
||||||
|
return Math.min(Math.max(n || 0, 1), 100)
|
||||||
|
})
|
||||||
|
|
||||||
|
const charset = computed(() => {
|
||||||
|
let s = ''
|
||||||
|
if (useLower.value) s += CHARSETS.lower
|
||||||
|
if (useUpper.value) s += CHARSETS.upper
|
||||||
|
if (useDigits.value) s += CHARSETS.digits
|
||||||
|
if (useSymbols.value) s += CHARSETS.symbols
|
||||||
|
if (excludeAmbiguous.value) {
|
||||||
|
for (const c of CHARSETS.ambiguous) s = s.split(c).join('')
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
})
|
||||||
|
|
||||||
|
/** 用 crypto.getRandomValues 生成无偏随机整数 [0, max) */
|
||||||
|
function randomInt(max: number): number {
|
||||||
|
// 拒绝采样消除模偏差
|
||||||
|
const limit = Math.floor(0x100000000 / max) * max
|
||||||
|
const buf = new Uint32Array(1)
|
||||||
|
let v: number
|
||||||
|
do {
|
||||||
|
crypto.getRandomValues(buf)
|
||||||
|
v = buf[0]
|
||||||
|
} while (v >= limit)
|
||||||
|
return v % max
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 熵估算:log2(charsetSize^length) = length * log2(size) */
|
||||||
|
const entropy = computed(() => {
|
||||||
|
const size = charset.value.length
|
||||||
|
if (size === 0) return 0
|
||||||
|
return Math.round(lengthNum.value * Math.log2(size))
|
||||||
|
})
|
||||||
|
|
||||||
|
const strength = computed(() => {
|
||||||
|
const e = entropy.value
|
||||||
|
if (e >= 128) return { label: '极强(128+ bit)', class: 'text-green-600 dark:text-green-400' }
|
||||||
|
if (e >= 80) return { label: '强(80-127 bit)', class: 'text-green-600 dark:text-green-400' }
|
||||||
|
if (e >= 60) return { label: '中等(60-79 bit)', class: 'text-amber-600 dark:text-amber-400' }
|
||||||
|
return { label: '弱(<60 bit)', class: 'text-red-600 dark:text-red-400' }
|
||||||
|
})
|
||||||
|
|
||||||
|
function generate() {
|
||||||
|
error.value = ''
|
||||||
|
if (charset.value.length === 0) {
|
||||||
|
error.value = '请至少选择一种字符集'
|
||||||
|
passwords.value = []
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const list: string[] = []
|
||||||
|
for (let i = 0; i < countNum.value; i++) {
|
||||||
|
let pw = ''
|
||||||
|
for (let j = 0; j < lengthNum.value; j++) {
|
||||||
|
pw += charset.value[randomInt(charset.value.length)]
|
||||||
|
}
|
||||||
|
list.push(pw)
|
||||||
|
}
|
||||||
|
passwords.value = list
|
||||||
|
}
|
||||||
|
|
||||||
|
const allText = computed(() => passwords.value.join('\n'))
|
||||||
|
|
||||||
|
function copyAll() {
|
||||||
|
void navigator.clipboard.writeText(allText.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(generate)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<div class="flex items-center gap-6 flex-wrap">
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">长度(4-128)</Label>
|
||||||
|
<Input v-model="length" type="number" min="4" max="128" class="w-24 font-mono text-sm" />
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">数量(1-100)</Label>
|
||||||
|
<Input v-model="count" type="number" min="1" max="100" class="w-24 font-mono text-sm" />
|
||||||
|
</div>
|
||||||
|
<Button size="sm" class="gap-1 self-end" @click="generate">
|
||||||
|
<RefreshCw class="size-3.5" />
|
||||||
|
重新生成
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex items-center gap-4 flex-wrap">
|
||||||
|
<label class="flex items-center gap-2 text-xs cursor-pointer">
|
||||||
|
<Switch v-model="useLower" /> 小写 a-z
|
||||||
|
</label>
|
||||||
|
<label class="flex items-center gap-2 text-xs cursor-pointer">
|
||||||
|
<Switch v-model="useUpper" /> 大写 A-Z
|
||||||
|
</label>
|
||||||
|
<label class="flex items-center gap-2 text-xs cursor-pointer">
|
||||||
|
<Switch v-model="useDigits" /> 数字 0-9
|
||||||
|
</label>
|
||||||
|
<label class="flex items-center gap-2 text-xs cursor-pointer">
|
||||||
|
<Switch v-model="useSymbols" /> 符号 !@#$%
|
||||||
|
</label>
|
||||||
|
<label class="flex items-center gap-2 text-xs cursor-pointer">
|
||||||
|
<Switch v-model="excludeAmbiguous" /> 排除易混淆字符
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p v-if="error" class="text-xs text-destructive">{{ error }}</p>
|
||||||
|
|
||||||
|
<template v-if="passwords.length">
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<Label class="text-xs">生成结果</Label>
|
||||||
|
<span class="text-xs" :class="strength.class">熵约 {{ entropy }} bit · {{ strength.label }}</span>
|
||||||
|
</div>
|
||||||
|
<Textarea
|
||||||
|
readonly
|
||||||
|
:model-value="allText"
|
||||||
|
class="min-h-[120px] font-mono text-xs resize-y"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button size="sm" variant="outline" class="gap-1 w-fit" @click="copyAll">
|
||||||
|
<Copy class="size-3.5" />
|
||||||
|
复制全部({{ passwords.length }} 个)
|
||||||
|
</Button>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import ResultArea from '../components/ResultArea.vue'
|
||||||
|
|
||||||
|
const pattern = ref('')
|
||||||
|
const testText = ref('')
|
||||||
|
const flags = ref({ g: true, i: false, m: false, s: false, u: false })
|
||||||
|
|
||||||
|
interface MatchInfo {
|
||||||
|
index: number
|
||||||
|
full: string
|
||||||
|
groups: string[]
|
||||||
|
groupsLabel: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const raw = computed<{ matches: MatchInfo[]; error: string }>(() => {
|
||||||
|
if (!pattern.value) return { matches: [], error: '' }
|
||||||
|
// 防卡 UI:同步 exec 无超时保护,超长文本截断测试(灾难性回溯正则仍可能慢,限制输入规模是主要防线)
|
||||||
|
const MAX_TEXT = 200_000
|
||||||
|
const text = testText.value.length > MAX_TEXT ? testText.value.slice(0, MAX_TEXT) : testText.value
|
||||||
|
const truncated = testText.value.length > MAX_TEXT
|
||||||
|
let fl = ''
|
||||||
|
const f = flags.value
|
||||||
|
if (f.g) fl += 'g'
|
||||||
|
if (f.i) fl += 'i'
|
||||||
|
if (f.m) fl += 'm'
|
||||||
|
if (f.s) fl += 's'
|
||||||
|
if (f.u) fl += 'u'
|
||||||
|
try {
|
||||||
|
const re = new RegExp(pattern.value, fl)
|
||||||
|
const list: MatchInfo[] = []
|
||||||
|
let m: RegExpExecArray | null
|
||||||
|
let guard = 0
|
||||||
|
while ((m = re.exec(text)) !== null) {
|
||||||
|
const groups = m.slice(1)
|
||||||
|
list.push({
|
||||||
|
index: m.index,
|
||||||
|
full: m[0],
|
||||||
|
groups,
|
||||||
|
groupsLabel: groups && groups.length > 0
|
||||||
|
? groups.map((g, i) => `$${i + 1}=${g === undefined ? '∅' : g}`).join(', ')
|
||||||
|
: ''
|
||||||
|
})
|
||||||
|
if (!f.g) break
|
||||||
|
if (list.length >= 5000) break // 匹配数上限,防止大文本 + 极宽正则刷爆列表
|
||||||
|
if (m[0] === '') {
|
||||||
|
if (++guard > 100000) break
|
||||||
|
re.lastIndex++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (list.length >= 5000) {
|
||||||
|
const extra = truncated ? `(文本超过 ${MAX_TEXT} 字符,仅测试前 ${MAX_TEXT} 字符)` : ''
|
||||||
|
return { matches: list, error: `匹配数已达 5000 上限,已停止${extra}` }
|
||||||
|
}
|
||||||
|
return { matches: list, error: '' }
|
||||||
|
} catch (e) {
|
||||||
|
return { matches: [], error: '正则语法错误:' + String(e) }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const matches = computed(() => raw.value.matches)
|
||||||
|
const error = computed(() => raw.value.error)
|
||||||
|
const isValidPattern = computed(() => {
|
||||||
|
if (!pattern.value) return null
|
||||||
|
try {
|
||||||
|
new RegExp(pattern.value, flags.value.g ? 'g' : '')
|
||||||
|
return true
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const matchesText = computed(() => {
|
||||||
|
if (matches.value.length === 0) return ''
|
||||||
|
return matches.value
|
||||||
|
.map((m, i) => `[${i}] @${m.index}: ${m.full}` + (m.groupsLabel ? ` (${m.groupsLabel})` : ''))
|
||||||
|
.join('\n')
|
||||||
|
})
|
||||||
|
|
||||||
|
const flagDefs = [
|
||||||
|
{ key: 'g' as const, label: 'g', title: '全局' },
|
||||||
|
{ key: 'i' as const, label: 'i', title: '忽略大小写' },
|
||||||
|
{ key: 'm' as const, label: 'm', title: '多行' },
|
||||||
|
{ key: 's' as const, label: 's', title: '点匹配换行' },
|
||||||
|
{ key: 'u' as const, label: 'u', title: 'Unicode' }
|
||||||
|
]
|
||||||
|
|
||||||
|
// ===== 替换预览 =====
|
||||||
|
const showReplace = ref(false)
|
||||||
|
const replacement = ref('')
|
||||||
|
const replaceError = computed(() => {
|
||||||
|
if (!showReplace.value || !pattern.value) return ''
|
||||||
|
try {
|
||||||
|
new RegExp(pattern.value, flags.value.g ? 'g' : '')
|
||||||
|
return ''
|
||||||
|
} catch (e) {
|
||||||
|
return '正则语法错误:' + String(e)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const replacedText = computed<{ text: string; count: number }>(() => {
|
||||||
|
if (!showReplace.value || !pattern.value || !testText.value) return { text: '', count: 0 }
|
||||||
|
const text = testText.value.length > 200_000 ? testText.value.slice(0, 200_000) : testText.value
|
||||||
|
try {
|
||||||
|
const fl = (flags.value.g ? 'g' : '') + (flags.value.i ? 'i' : '') + (flags.value.m ? 'm' : '') + (flags.value.s ? 's' : '') + (flags.value.u ? 'u' : '')
|
||||||
|
const re = new RegExp(pattern.value, fl)
|
||||||
|
const all = (text.match(new RegExp(pattern.value, fl.includes('g') ? fl : fl + 'g')) ?? []).length
|
||||||
|
return { text: text.replace(re, replacement.value), count: flags.value.g ? all : Math.min(all, 1) }
|
||||||
|
} catch {
|
||||||
|
return { text: '', count: 0 }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">正则表达式</Label>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<span class="text-muted-foreground font-mono text-sm">/</span>
|
||||||
|
<Input v-model="pattern" placeholder="如 \b\w+@\w+\.\w+\b" class="font-mono text-sm flex-1" :class="{ 'border-destructive': isValidPattern === false }" />
|
||||||
|
<span class="text-muted-foreground font-mono text-sm">/</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-1 flex-wrap">
|
||||||
|
<button
|
||||||
|
v-for="fd in flagDefs"
|
||||||
|
:key="fd.key"
|
||||||
|
type="button"
|
||||||
|
class="h-6 px-2 rounded font-mono text-xs border transition-colors cursor-pointer"
|
||||||
|
:class="flags[fd.key] ? 'border-primary text-primary bg-primary/10' : 'border-border text-muted-foreground hover:text-foreground'"
|
||||||
|
:title="fd.title"
|
||||||
|
@click="flags[fd.key] = !flags[fd.key]"
|
||||||
|
>
|
||||||
|
{{ fd.label }}
|
||||||
|
</button>
|
||||||
|
<span v-if="matches.length" class="ml-auto text-xs text-muted-foreground">匹配 {{ matches.length }} 处</span>
|
||||||
|
<span v-else-if="pattern && testText && !error" class="ml-auto text-xs text-muted-foreground">无匹配</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">测试文本</Label>
|
||||||
|
<Textarea v-model="testText" placeholder="在此输入文本..." class="min-h-[120px] font-mono text-xs resize-y" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">匹配结果</Label>
|
||||||
|
<div class="rounded-md border border-border max-h-56 overflow-y-auto divide-y divide-border">
|
||||||
|
<div v-if="matches.length === 0 && !error" class="p-3 text-xs text-muted-foreground">输入正则与文本查看匹配。</div>
|
||||||
|
<div v-for="(m, i) in matches" :key="i" class="flex items-start gap-2 p-2 text-xs font-mono">
|
||||||
|
<Badge variant="outline" class="shrink-0 py-0 px-1.5 text-[10px]">@{{ m.index }}</Badge>
|
||||||
|
<span class="break-all min-w-0">{{ m.full }}</span>
|
||||||
|
<span v-if="m.groupsLabel" class="text-muted-foreground break-all ml-auto pl-2">{{ m.groupsLabel }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ResultArea :text="matchesText" label="匹配列表(可复制)" placeholder="匹配列表" />
|
||||||
|
|
||||||
|
<!-- 替换预览 -->
|
||||||
|
<div class="rounded-md border border-border">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="w-full flex items-center justify-between px-3 py-2 text-xs font-medium cursor-pointer hover:bg-muted/40 transition-colors"
|
||||||
|
@click="showReplace = !showReplace"
|
||||||
|
>
|
||||||
|
<span>替换预览(支持 $1、$<name> 引用分组)</span>
|
||||||
|
<span class="text-muted-foreground">{{ showReplace ? '收起' : '展开' }}</span>
|
||||||
|
</button>
|
||||||
|
<div v-if="showReplace" class="flex flex-col gap-3 p-3 border-t border-border">
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">替换为</Label>
|
||||||
|
<Input v-model="replacement" placeholder="如 [$1](留空则删除匹配内容)" class="font-mono text-sm" />
|
||||||
|
</div>
|
||||||
|
<ResultArea
|
||||||
|
v-if="replacedText.text"
|
||||||
|
:text="replacedText.text"
|
||||||
|
:label="`替换结果(已替换 ${replacedText.count} 处)`"
|
||||||
|
placeholder="替换结果"
|
||||||
|
/>
|
||||||
|
<p v-else-if="replacement" class="text-xs text-muted-foreground">替换后无内容或无匹配。</p>
|
||||||
|
<p v-if="replaceError" class="text-xs text-destructive">{{ replaceError }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p v-if="error" class="text-xs text-destructive">{{ error }}</p>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Switch } from '@/components/ui/switch'
|
||||||
|
import ResultArea from '../components/ResultArea.vue'
|
||||||
|
|
||||||
|
const input = ref('')
|
||||||
|
const find = ref('')
|
||||||
|
const replacement = ref('')
|
||||||
|
const useRegex = ref(false)
|
||||||
|
const caseInsensitive = ref(false)
|
||||||
|
const multiline = ref(false)
|
||||||
|
|
||||||
|
const result = computed<{ text: string; count: number; error: string }>(() => {
|
||||||
|
const v = input.value
|
||||||
|
if (!v || !find.value) return { text: '', count: 0, error: '' }
|
||||||
|
try {
|
||||||
|
let re: RegExp
|
||||||
|
let replacementText: string
|
||||||
|
if (useRegex.value) {
|
||||||
|
const flags = 'g' + (caseInsensitive.value ? 'i' : '') + (multiline.value ? 'm' : '')
|
||||||
|
re = new RegExp(find.value, flags)
|
||||||
|
// 正则模式:原生支持 $1、$<name> 等引用
|
||||||
|
replacementText = replacement.value
|
||||||
|
} else {
|
||||||
|
// 纯文本模式:查找与替换都按字面处理,需转义正则元字符与替换串中的 $
|
||||||
|
const esc = find.value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||||
|
re = new RegExp(esc, 'g' + (caseInsensitive.value ? 'i' : ''))
|
||||||
|
replacementText = replacement.value.replace(/\$/g, '$$$$')
|
||||||
|
}
|
||||||
|
const count = (v.match(re) ?? []).length
|
||||||
|
return { text: v.replace(re, replacementText), count, error: '' }
|
||||||
|
} catch (e) {
|
||||||
|
return { text: '', count: 0, error: '正则语法错误:' + String(e) }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">原文</Label>
|
||||||
|
<Textarea v-model="input" placeholder="在此输入文本..." class="min-h-[140px] font-mono text-xs resize-y" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid grid-cols-2 gap-3">
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">查找</Label>
|
||||||
|
<Input v-model="find" :placeholder="useRegex ? '正则表达式' : '纯文本'" class="font-mono text-sm" />
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">替换为(留空删除匹配)</Label>
|
||||||
|
<Input v-model="replacement" :placeholder="useRegex ? '支持 $1、$<name>' : '纯文本'" class="font-mono text-sm" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex items-center gap-4 flex-wrap">
|
||||||
|
<label class="flex items-center gap-2 text-xs cursor-pointer">
|
||||||
|
<Switch v-model="useRegex" /> 正则模式
|
||||||
|
</label>
|
||||||
|
<label class="flex items-center gap-2 text-xs cursor-pointer">
|
||||||
|
<Switch v-model="caseInsensitive" /> 忽略大小写
|
||||||
|
</label>
|
||||||
|
<label class="flex items-center gap-2 text-xs cursor-pointer" :class="{ 'opacity-50': !useRegex }">
|
||||||
|
<Switch v-model="multiline" :disabled="!useRegex" /> 多行模式(^$ 匹配行首尾)
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p v-if="result.error" class="text-xs text-destructive">{{ result.error }}</p>
|
||||||
|
|
||||||
|
<ResultArea
|
||||||
|
v-if="result.text"
|
||||||
|
:text="result.text"
|
||||||
|
:label="`替换结果(已替换 ${result.count} 处)`"
|
||||||
|
placeholder="替换结果"
|
||||||
|
/>
|
||||||
|
<p v-else-if="input && find" class="text-xs text-muted-foreground">无匹配或替换后为空。</p>
|
||||||
|
<p v-else class="text-xs text-muted-foreground">输入原文与查找内容,实时预览替换结果。</p>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onUnmounted, ref } from 'vue'
|
||||||
|
import { Clock } from '@lucide/vue'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Separator } from '@/components/ui/separator'
|
||||||
|
import Segmented from '../components/Segmented.vue'
|
||||||
|
import ResultArea from '../components/ResultArea.vue'
|
||||||
|
|
||||||
|
type Unit = 'auto' | 's' | 'ms'
|
||||||
|
|
||||||
|
const unit = ref<Unit>('auto')
|
||||||
|
const numberInput = ref('')
|
||||||
|
const dateInput = ref('')
|
||||||
|
|
||||||
|
const toNumber = (v: string): number | null => {
|
||||||
|
const n = Number(v.trim())
|
||||||
|
return Number.isFinite(n) ? n : null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 自动识别:13 位(>1e11)视为毫秒,10 位(>1e8)视为秒,其他按数值范围推断 */
|
||||||
|
function resolveUnit(n: number): 's' | 'ms' {
|
||||||
|
if (unit.value !== 'auto') return unit.value
|
||||||
|
if (Math.abs(n) >= 1e11) return 'ms'
|
||||||
|
return 's'
|
||||||
|
}
|
||||||
|
|
||||||
|
const unixToDate = (n: number, u: 's' | 'ms'): Date =>
|
||||||
|
new Date(u === 's' ? n * 1000 : n)
|
||||||
|
|
||||||
|
const formatLocal = (d: Date): string => {
|
||||||
|
const pad = (x: number) => String(x).padStart(2, '0')
|
||||||
|
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatUtc = (d: Date): string => {
|
||||||
|
const pad = (x: number) => String(x).padStart(2, '0')
|
||||||
|
return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())} UTC`
|
||||||
|
}
|
||||||
|
|
||||||
|
const fromNumber = computed<{ local: string; utc: string; iso: string; ts: string; unitUsed: 's' | 'ms' } | null>(() => {
|
||||||
|
const n = toNumber(numberInput.value)
|
||||||
|
if (n === null) return null
|
||||||
|
const u = resolveUnit(n)
|
||||||
|
const d = unixToDate(n, u)
|
||||||
|
if (Number.isNaN(d.getTime())) return null
|
||||||
|
return {
|
||||||
|
local: formatLocal(d),
|
||||||
|
utc: formatUtc(d),
|
||||||
|
iso: d.toISOString(),
|
||||||
|
ts: String(n),
|
||||||
|
unitUsed: u
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const fromDate = computed<string>(() => {
|
||||||
|
if (!dateInput.value) return ''
|
||||||
|
const d = new Date(dateInput.value)
|
||||||
|
if (Number.isNaN(d.getTime())) return ''
|
||||||
|
// 日期输入统一同时给出秒与毫秒
|
||||||
|
return `${Math.floor(d.getTime() / 1000)}(秒)\n${d.getTime()}(毫秒)`
|
||||||
|
})
|
||||||
|
|
||||||
|
// ===== 当前时间戳 =====
|
||||||
|
const nowTick = ref(0)
|
||||||
|
const timer = window.setInterval(() => (nowTick.value++), 1000)
|
||||||
|
onUnmounted(() => window.clearInterval(timer))
|
||||||
|
|
||||||
|
const now = computed(() => {
|
||||||
|
void nowTick.value
|
||||||
|
const d = new Date()
|
||||||
|
return {
|
||||||
|
s: String(Math.floor(d.getTime() / 1000)),
|
||||||
|
ms: String(d.getTime()),
|
||||||
|
local: formatLocal(d)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
function copy(text: string) {
|
||||||
|
void navigator.clipboard.writeText(text)
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<Segmented
|
||||||
|
v-model="unit"
|
||||||
|
label="单位"
|
||||||
|
:options="[
|
||||||
|
{ value: 'auto', label: '自动' },
|
||||||
|
{ value: 's', label: '秒' },
|
||||||
|
{ value: 'ms', label: '毫秒' }
|
||||||
|
]"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<!-- 时间戳 → 时间 -->
|
||||||
|
<div class="flex flex-col gap-3">
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">Unix 时间戳 → 日期时间</Label>
|
||||||
|
<Input v-model="numberInput" placeholder="例如 1757419200 或 1757419200000" class="font-mono text-sm" />
|
||||||
|
</div>
|
||||||
|
<template v-if="fromNumber">
|
||||||
|
<ResultArea :text="fromNumber.local" label="本地时间" placeholder="本地时间" />
|
||||||
|
<ResultArea :text="fromNumber.utc" label="UTC 时间" placeholder="UTC 时间" />
|
||||||
|
<ResultArea :text="fromNumber.iso" label="ISO 8601" placeholder="ISO 8601" />
|
||||||
|
<p class="text-xs text-muted-foreground">已识别为{{ fromNumber.unitUsed === 's' ? '秒级' : '毫秒级' }}时间戳</p>
|
||||||
|
</template>
|
||||||
|
<p v-else-if="numberInput" class="text-xs text-destructive">请输入有效的数字时间戳</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Separator />
|
||||||
|
|
||||||
|
<!-- 时间 → 时间戳 -->
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">日期时间 → Unix 时间戳</Label>
|
||||||
|
<Input v-model="dateInput" type="datetime-local" class="font-mono text-sm" />
|
||||||
|
<ResultArea v-if="fromDate" :text="fromDate" label="结果" placeholder="结果" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Separator />
|
||||||
|
|
||||||
|
<!-- 当前时间戳 -->
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<Label class="text-xs">当前时间({{ now.local }})</Label>
|
||||||
|
<div class="flex items-center gap-2 flex-wrap">
|
||||||
|
<Button size="sm" variant="outline" class="h-8 font-mono text-xs gap-1.5" @click="copy(now.s)">
|
||||||
|
<Clock class="size-3.5" />
|
||||||
|
{{ now.s }}(秒,点击复制)
|
||||||
|
</Button>
|
||||||
|
<Button size="sm" variant="outline" class="h-8 font-mono text-xs gap-1.5" @click="copy(now.ms)">
|
||||||
|
<Clock class="size-3.5" />
|
||||||
|
{{ now.ms }}(毫秒,点击复制)
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,187 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { ArrowDownUp } from '@lucide/vue'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Switch } from '@/components/ui/switch'
|
||||||
|
import Segmented from '../components/Segmented.vue'
|
||||||
|
import ResultArea from '../components/ResultArea.vue'
|
||||||
|
|
||||||
|
type Tab = 'convert' | 'parse'
|
||||||
|
|
||||||
|
const tab = ref<Tab>('convert')
|
||||||
|
const mode = ref<'encode' | 'decode'>('encode')
|
||||||
|
const usePlus = ref(false)
|
||||||
|
const input = ref('')
|
||||||
|
|
||||||
|
// ===== 编解码 =====
|
||||||
|
const output = computed<{ text: string; error: string }>(() => {
|
||||||
|
const v = input.value
|
||||||
|
if (!v) return { text: '', error: '' }
|
||||||
|
if (mode.value === 'encode') {
|
||||||
|
const enc = encodeURIComponent(v)
|
||||||
|
return { text: usePlus.value ? enc.replace(/%20/g, '+') : enc, error: '' }
|
||||||
|
}
|
||||||
|
// decode:先处理 + 与 %20 两种形式
|
||||||
|
const normalized = usePlus.value ? v.replace(/\+/g, ' ') : v
|
||||||
|
try {
|
||||||
|
return { text: decodeURIComponent(normalized), error: '' }
|
||||||
|
} catch (e) {
|
||||||
|
return { text: '', error: '解码失败(存在非法百分号序列):' + String(e) }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const swap = () => {
|
||||||
|
if (output.value.text) {
|
||||||
|
input.value = output.value.text
|
||||||
|
mode.value = mode.value === 'encode' ? 'decode' : 'encode'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== URL 解析 =====
|
||||||
|
const parseInput = ref('https://user:pass@example.com:8080/path/to/page?a=1&b=hello%20world&c=3#section')
|
||||||
|
|
||||||
|
interface ParsedUrl {
|
||||||
|
href: string
|
||||||
|
protocol: string
|
||||||
|
username: string
|
||||||
|
password: string
|
||||||
|
host: string
|
||||||
|
hostname: string
|
||||||
|
port: string
|
||||||
|
pathname: string
|
||||||
|
search: string
|
||||||
|
hash: string
|
||||||
|
origin: string
|
||||||
|
params: Array<[string, string]>
|
||||||
|
paramError: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsedUrl = computed<{ url: ParsedUrl | null; error: string }>(() => {
|
||||||
|
const v = parseInput.value.trim()
|
||||||
|
if (!v) return { url: null, error: '' }
|
||||||
|
let u: URL
|
||||||
|
try {
|
||||||
|
u = new URL(v)
|
||||||
|
} catch {
|
||||||
|
// 无协议时尝试补 http:// 再解析
|
||||||
|
try {
|
||||||
|
u = new URL('http://' + v)
|
||||||
|
} catch (e) {
|
||||||
|
return { url: null, error: 'URL 解析失败:' + String(e) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const params: Array<[string, string]> = []
|
||||||
|
let paramError = ''
|
||||||
|
try {
|
||||||
|
u.searchParams.forEach((value, key) => params.push([key, value]))
|
||||||
|
} catch (e) {
|
||||||
|
paramError = String(e)
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
url: {
|
||||||
|
href: u.href,
|
||||||
|
protocol: u.protocol,
|
||||||
|
username: u.username,
|
||||||
|
password: u.password,
|
||||||
|
host: u.host,
|
||||||
|
hostname: u.hostname,
|
||||||
|
port: u.port,
|
||||||
|
pathname: u.pathname,
|
||||||
|
search: u.search,
|
||||||
|
hash: u.hash,
|
||||||
|
origin: u.origin,
|
||||||
|
params,
|
||||||
|
paramError
|
||||||
|
},
|
||||||
|
error: ''
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const FIELDS: Array<{ key: keyof ParsedUrl; label: string }> = [
|
||||||
|
{ key: 'protocol', label: '协议' },
|
||||||
|
{ key: 'username', label: '用户名' },
|
||||||
|
{ key: 'password', label: '密码' },
|
||||||
|
{ key: 'hostname', label: '主机名' },
|
||||||
|
{ key: 'port', label: '端口' },
|
||||||
|
{ key: 'pathname', label: '路径' },
|
||||||
|
{ key: 'search', label: '查询串' },
|
||||||
|
{ key: 'hash', label: '锚点' },
|
||||||
|
{ key: 'origin', label: 'Origin' }
|
||||||
|
]
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<Segmented
|
||||||
|
v-model="tab"
|
||||||
|
:options="[
|
||||||
|
{ value: 'convert', label: '编解码' },
|
||||||
|
{ value: 'parse', label: 'URL 解析' }
|
||||||
|
]"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<!-- 编解码 -->
|
||||||
|
<template v-if="tab === 'convert'">
|
||||||
|
<div class="flex items-center justify-between flex-wrap gap-3">
|
||||||
|
<Segmented
|
||||||
|
v-model="mode"
|
||||||
|
label="操作"
|
||||||
|
:options="[
|
||||||
|
{ value: 'encode', label: '编码' },
|
||||||
|
{ value: 'decode', label: '解码' }
|
||||||
|
]"
|
||||||
|
/>
|
||||||
|
<label class="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
|
||||||
|
空格用
|
||||||
|
<Switch v-model="usePlus" />
|
||||||
|
<span class="font-mono">{{ usePlus ? '+(表单)' : '%20' }}</span>
|
||||||
|
</label>
|
||||||
|
<Button size="sm" variant="outline" class="h-8 text-sm gap-1" :disabled="!output.text" @click="swap">
|
||||||
|
<ArrowDownUp class="size-3.5" />
|
||||||
|
结果回填
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">{{ mode === 'encode' ? '待编码文本' : '待解码字符串' }}</Label>
|
||||||
|
<Textarea v-model="input" placeholder="在此输入..." class="min-h-[120px] font-mono text-xs resize-y" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ResultArea :text="output.text" placeholder="结果" />
|
||||||
|
<p v-if="output.error" class="text-xs text-destructive">{{ output.error }}</p>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- URL 解析 -->
|
||||||
|
<template v-else>
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">URL</Label>
|
||||||
|
<Textarea v-model="parseInput" placeholder="https://example.com/path?a=1#hash" class="min-h-[70px] font-mono text-xs resize-y" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-if="parsedUrl.url">
|
||||||
|
<div class="rounded-md border border-border divide-y divide-border text-xs">
|
||||||
|
<div v-for="f in FIELDS" :key="f.key" class="flex gap-3 px-3 py-1.5">
|
||||||
|
<span class="w-16 shrink-0 text-muted-foreground">{{ f.label }}</span>
|
||||||
|
<span class="font-mono break-all">{{ (parsedUrl.url[f.key] as string) || '—' }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="parsedUrl.url.params.length > 0" class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">查询参数({{ parsedUrl.url.params.length }} 个)</Label>
|
||||||
|
<div class="rounded-md border border-border divide-y divide-border text-xs">
|
||||||
|
<div v-for="([k, v], i) in parsedUrl.url.params" :key="i" class="flex gap-3 px-3 py-1.5">
|
||||||
|
<span class="font-mono text-primary break-all">{{ k }}</span>
|
||||||
|
<span class="font-mono break-all">{{ v }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p v-if="parsedUrl.url.paramError" class="text-xs text-destructive">{{ parsedUrl.url.paramError }}</p>
|
||||||
|
<p v-else-if="parsedUrl.url.params.length === 0" class="text-xs text-muted-foreground">无查询参数。</p>
|
||||||
|
</template>
|
||||||
|
<p v-else-if="!parseInput" class="text-xs text-muted-foreground">输入 URL 查看解析结果。</p>
|
||||||
|
<p v-else class="text-xs text-destructive">{{ parsedUrl.error }}</p>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, ref, watch } from 'vue'
|
||||||
|
import { RefreshCw, Copy } from '@lucide/vue'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Switch } from '@/components/ui/switch'
|
||||||
|
import Segmented from '../components/Segmented.vue'
|
||||||
|
import ResultArea from '../components/ResultArea.vue'
|
||||||
|
|
||||||
|
const count = ref('5')
|
||||||
|
const version = ref<'v4' | 'v7'>('v4')
|
||||||
|
const uppercase = ref(false)
|
||||||
|
const noDashes = ref(false)
|
||||||
|
// 原始随机 UUID 与格式化后的展示
|
||||||
|
const baseUuids = ref<string[]>([])
|
||||||
|
|
||||||
|
const batchCount = computed(() => {
|
||||||
|
const n = Math.floor(Number(count.value))
|
||||||
|
if (!Number.isFinite(n)) return 5
|
||||||
|
return Math.min(Math.max(n || 0, 1), 100)
|
||||||
|
})
|
||||||
|
|
||||||
|
function formatUuid(u: string): string {
|
||||||
|
let out = uppercase.value ? u.toUpperCase() : u
|
||||||
|
if (noDashes.value) out = out.replace(/-/g, '')
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
const uuids = computed(() => baseUuids.value.map(formatUuid))
|
||||||
|
|
||||||
|
/** UUID v4:纯随机 */
|
||||||
|
function uuidv4(): string {
|
||||||
|
return crypto.randomUUID()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** UUID v7:毫秒时间戳前缀(48 bit)+ 随机,时间有序、适合数据库索引 */
|
||||||
|
function uuidv7(): string {
|
||||||
|
const ts = BigInt(Date.now())
|
||||||
|
const b = crypto.getRandomValues(new Uint8Array(16))
|
||||||
|
b[0] = Number((ts >> 40n) & 0xffn)
|
||||||
|
b[1] = Number((ts >> 32n) & 0xffn)
|
||||||
|
b[2] = Number((ts >> 24n) & 0xffn)
|
||||||
|
b[3] = Number((ts >> 16n) & 0xffn)
|
||||||
|
b[4] = Number((ts >> 8n) & 0xffn)
|
||||||
|
b[5] = Number(ts & 0xffn)
|
||||||
|
b[6] = (b[6] & 0x0f) | 0x70 // version 7
|
||||||
|
b[8] = (b[8] & 0x3f) | 0x80 // variant 10xx
|
||||||
|
const hex = Array.from(b, x => x.toString(16).padStart(2, '0')).join('')
|
||||||
|
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function generate() {
|
||||||
|
const gen = version.value === 'v4' ? uuidv4 : uuidv7
|
||||||
|
baseUuids.value = Array.from({ length: batchCount.value }, gen)
|
||||||
|
}
|
||||||
|
|
||||||
|
const allText = computed(() => uuids.value.join('\n'))
|
||||||
|
|
||||||
|
function copyAll() {
|
||||||
|
try {
|
||||||
|
void navigator.clipboard.writeText(allText.value)
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 切换版本时立即重新生成
|
||||||
|
watch(version, generate)
|
||||||
|
|
||||||
|
onMounted(generate)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<div class="flex items-center justify-between flex-wrap gap-3">
|
||||||
|
<div class="flex items-center gap-4 flex-wrap">
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">生成数量(1-100)</Label>
|
||||||
|
<Input v-model="count" type="number" min="1" max="100" class="w-24 font-mono text-sm" />
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">版本</Label>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<Segmented
|
||||||
|
v-model="version"
|
||||||
|
:options="[
|
||||||
|
{ value: 'v4', label: 'v4 随机' },
|
||||||
|
{ value: 'v7', label: 'v7 时间有序' }
|
||||||
|
]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-4">
|
||||||
|
<label class="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
|
||||||
|
大写
|
||||||
|
<Switch v-model="uppercase" />
|
||||||
|
</label>
|
||||||
|
<label class="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
|
||||||
|
去除连字符
|
||||||
|
<Switch v-model="noDashes" />
|
||||||
|
</label>
|
||||||
|
<Button size="sm" class="gap-1" @click="generate">
|
||||||
|
<RefreshCw class="size-3.5" />
|
||||||
|
重新生成
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ResultArea :text="allText" label="UUID 列表" placeholder="点击重新生成" />
|
||||||
|
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<Button size="sm" variant="outline" class="gap-1" :disabled="!allText" @click="copyAll">
|
||||||
|
<Copy class="size-3.5" />
|
||||||
|
复制全部({{ uuids.length }} 个)
|
||||||
|
</Button>
|
||||||
|
<span class="text-xs text-muted-foreground">{{ version === 'v4' ? 'UUID v4(纯随机)' : 'UUID v7(毫秒时间戳前缀,适合数据库主键索引)' }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import Segmented from '../../components/Segmented.vue'
|
||||||
|
import ResultArea from '../../components/ResultArea.vue'
|
||||||
|
|
||||||
|
type Radix = '2' | '8' | '10' | '16'
|
||||||
|
|
||||||
|
const bases: { value: Radix; label: string }[] = [
|
||||||
|
{ value: '2', label: '二进制(2)' },
|
||||||
|
{ value: '8', label: '八进制(8)' },
|
||||||
|
{ value: '10', label: '十进制(10)' },
|
||||||
|
{ value: '16', label: '十六进制(16)' }
|
||||||
|
]
|
||||||
|
|
||||||
|
const from = ref<Radix>('10')
|
||||||
|
const to = ref<Radix>('16')
|
||||||
|
const input = ref('')
|
||||||
|
const error = ref('')
|
||||||
|
|
||||||
|
const RADIX_MAP: Record<Radix, number> = { '2': 2, '8': 8, '10': 10, '16': 16 }
|
||||||
|
|
||||||
|
/** 按进制精确解析为 BigInt(大数字不丢精度),非法输入抛错 */
|
||||||
|
function parseBigInt(s: string, radix: number): bigint {
|
||||||
|
const digits = '0123456789abcdef'
|
||||||
|
const trimmed = s.trim().toLowerCase()
|
||||||
|
const negative = trimmed.startsWith('-')
|
||||||
|
const body = trimmed.replace(/^[+-]/, '')
|
||||||
|
if (!body) throw new Error('empty')
|
||||||
|
let n = 0n
|
||||||
|
for (const ch of body) {
|
||||||
|
const d = digits.indexOf(ch)
|
||||||
|
if (d === -1 || d >= radix) throw new Error('invalid digit')
|
||||||
|
n = n * BigInt(radix) + BigInt(d)
|
||||||
|
}
|
||||||
|
return negative ? -n : n
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = computed(() => {
|
||||||
|
error.value = ''
|
||||||
|
const v = input.value.trim()
|
||||||
|
if (!v) return { dec: null, output: '', outputUppercase: '' }
|
||||||
|
try {
|
||||||
|
const parsed = parseBigInt(v, RADIX_MAP[from.value])
|
||||||
|
const out = parsed.toString(RADIX_MAP[to.value])
|
||||||
|
return {
|
||||||
|
dec: parsed,
|
||||||
|
output: out,
|
||||||
|
outputUppercase: to.value === '16' ? out.toUpperCase() : out
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
error.value = '输入不合法,请确认数字与当前进制匹配(如十六进制仅含 0-9a-f)'
|
||||||
|
return { dec: null, output: '', outputUppercase: '' }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<div class="flex items-center gap-3 flex-wrap">
|
||||||
|
<Segmented v-model="from" label="从" :options="bases" />
|
||||||
|
<span class="text-xs text-muted-foreground">→</span>
|
||||||
|
<Segmented v-model="to" label="到" :options="bases" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Label class="text-xs">输入({{ from === '2' ? '二进制' : from === '8' ? '八进制' : from === '10' ? '十进制' : '十六进制' }})</Label>
|
||||||
|
<Input v-model="input" placeholder="输入数字" class="font-mono text-sm" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ResultArea :text="result.output" label="结果" placeholder="结果" />
|
||||||
|
<ResultArea v-if="to === '16' && result.outputUppercase !== result.output" :text="result.outputUppercase" label="大写形式" placeholder="大写形式" />
|
||||||
|
<div v-if="result.dec !== null" class="text-xs text-muted-foreground">十进制值:{{ result.dec.toString() }}</div>
|
||||||
|
<p v-if="error" class="text-xs text-destructive">{{ error }}</p>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
import type { Component } from 'vue'
|
||||||
|
import { defineAsyncComponent } from 'vue'
|
||||||
|
import {
|
||||||
|
FileJson, Binary, Link, Clock, MoveHorizontal, Fingerprint,
|
||||||
|
Wand2, KeyRound, CaseSensitive, Hash, Code, GitCompare, Shield,
|
||||||
|
Palette, Lock, CalendarClock, Network, Sigma, Replace, Globe
|
||||||
|
} from '@lucide/vue'
|
||||||
|
import { registerTool, type DevTool } from '../registry'
|
||||||
|
|
||||||
|
/** 工具元数据(与组件解耦,供模块配置生成搜索项) */
|
||||||
|
export const TOOLS_META: Array<Omit<DevTool, 'component' | 'icon'>> = [
|
||||||
|
{
|
||||||
|
id: 'json', name: 'JSON 格式化', category: 'transform',
|
||||||
|
description: '格式化 / 压缩 / 校验,支持键排序',
|
||||||
|
keywords: ['json', '格式化', '美化', '压缩', '校验', '排序']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'timestamp', name: '时间戳转换', category: 'transform',
|
||||||
|
description: 'Unix 时间戳与日期时间互转,自动识别秒 / 毫秒',
|
||||||
|
keywords: ['时间戳', 'timestamp', 'unix', '日期', '时间', '转换', '现在']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'base', name: '进制转换', category: 'transform',
|
||||||
|
description: '二进制 / 八进制 / 十进制 / 十六进制互转',
|
||||||
|
keywords: ['进制', '二进制', '十六进制', 'hex', 'bin', 'oct', 'dec', 'base']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'color', name: '颜色转换器', category: 'transform',
|
||||||
|
description: 'HEX / RGB / HSL / HSV / CMYK 互转,明暗梯度',
|
||||||
|
keywords: ['颜色', 'color', 'hex', 'rgb', 'hsl', 'hsv', 'cmyk', '调色', '取色']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'ip', name: 'IP / CIDR 计算', category: 'transform',
|
||||||
|
description: '子网划分、掩码换算、IP 与整数互转',
|
||||||
|
keywords: ['ip', 'cidr', '子网', '掩码', '网段', '广播', '网络', 'subnet', 'mask']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'cron', name: 'Cron 表达式', category: 'transform',
|
||||||
|
description: '解析 Cron 表达式,预览接下来 6 次执行时间',
|
||||||
|
keywords: ['cron', 'crontab', '定时', '计划任务', '表达式', 'schedule']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'base64', name: 'Base64 转换', category: 'encoding',
|
||||||
|
description: '文本与 Base64 互转(支持中文),文件转 Base64 / Data URL',
|
||||||
|
keywords: ['base64', '编码', '解码', 'encode', 'decode', 'dataurl', '文件']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'url', name: 'URL 编解码', category: 'encoding',
|
||||||
|
description: 'URL 编码 / 解码,URL 结构解析',
|
||||||
|
keywords: ['url', 'encode', 'decode', '编码', '解码', '链接', '解析', '参数', 'query']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'jwt', name: 'JWT 解码', category: 'encoding',
|
||||||
|
description: '本地解析 JWT 的 Header 与 Payload,含过期时间提示',
|
||||||
|
keywords: ['jwt', 'token', '解码', 'header', 'payload', '过期', 'exp']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'escape', name: '转义 / 反转义', category: 'encoding',
|
||||||
|
description: 'HTML 实体与 JSON 字符串转义、反转义',
|
||||||
|
keywords: ['转义', '反转义', 'html', 'entity', 'json', 'escape']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'case', name: '大小写 / 命名转换', category: 'text',
|
||||||
|
description: 'camel / Pascal / snake / kebab 等命名转换',
|
||||||
|
keywords: ['大小写', '命名', 'camel', 'snake', 'kebab', 'pascal', '转换']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'regex', name: '正则测试', category: 'text',
|
||||||
|
description: '在线测试正则表达式,实时匹配、分组查看与替换预览',
|
||||||
|
keywords: ['正则', 'regex', '匹配', 'test', 're', '替换']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'diff', name: '文本对比', category: 'text',
|
||||||
|
description: '两段文本逐行差异对比',
|
||||||
|
keywords: ['对比', '差异', 'diff', '比较', 'compare']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'eol', name: '行尾符转换', category: 'text',
|
||||||
|
description: 'CRLF / LF / CR 行尾符统一',
|
||||||
|
keywords: ['行尾', '换行', 'crlf', 'lf', 'cr', 'eol', '转行']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'replace', name: '批量查找替换', category: 'text',
|
||||||
|
description: '纯文本 / 正则批量替换,支持分组引用',
|
||||||
|
keywords: ['替换', '查找', 'replace', '批量', '正则替换']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'charcount', name: '字符统计', category: 'text',
|
||||||
|
description: '字符 / 字节 / 词数 / 行数统计与高频分析',
|
||||||
|
keywords: ['统计', '字数', '字符数', '词频', 'count', 'words', '字节数']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'uuid', name: 'UUID 生成', category: 'generate',
|
||||||
|
description: '批量生成 UUID v4 / v7,支持大写与去连字符',
|
||||||
|
keywords: ['uuid', 'guid', '生成', '随机', 'id', 'v4', 'v7']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'hash', name: '哈希计算', category: 'generate',
|
||||||
|
description: 'MD5 / SHA-1 / SHA-256 / SHA-384 / SHA-512 与 HMAC,支持文件',
|
||||||
|
keywords: ['哈希', 'hash', 'sha', '摘要', 'md5', 'hmac', '文件', '校验']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'password', name: '密码生成', category: 'generate',
|
||||||
|
description: '随机密码批量生成,字符集可选,附熵值评估',
|
||||||
|
keywords: ['密码', 'password', '随机', '生成', '安全', 'entropy']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'httpstatus', name: 'HTTP 速查', category: 'reference',
|
||||||
|
description: 'HTTP 状态码与常用 MIME 类型速查',
|
||||||
|
keywords: ['http', '状态码', 'status', 'mime', 'content-type', '速查', '429', '404']
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
/** 图标映射(按工具 id) */
|
||||||
|
const TOOL_ICONS: Record<string, Component> = {
|
||||||
|
json: FileJson,
|
||||||
|
timestamp: Clock,
|
||||||
|
base: Hash,
|
||||||
|
color: Palette,
|
||||||
|
ip: Network,
|
||||||
|
cron: CalendarClock,
|
||||||
|
base64: Binary,
|
||||||
|
url: Link,
|
||||||
|
jwt: KeyRound,
|
||||||
|
escape: Code,
|
||||||
|
case: CaseSensitive,
|
||||||
|
regex: Wand2,
|
||||||
|
diff: GitCompare,
|
||||||
|
eol: MoveHorizontal,
|
||||||
|
replace: Replace,
|
||||||
|
charcount: Sigma,
|
||||||
|
uuid: Fingerprint,
|
||||||
|
hash: Shield,
|
||||||
|
password: Lock,
|
||||||
|
httpstatus: Globe
|
||||||
|
}
|
||||||
|
|
||||||
|
// 工具组件(懒加载路径映射)
|
||||||
|
const TOOL_COMPONENTS: Record<string, () => Promise<{ default: Component }>> = {
|
||||||
|
json: () => import('./JsonTools.vue'),
|
||||||
|
timestamp: () => import('./TimestampTools.vue'),
|
||||||
|
base: () => import('./base/BaseTools.vue'),
|
||||||
|
color: () => import('./ColorTools.vue'),
|
||||||
|
ip: () => import('./IpTools.vue'),
|
||||||
|
cron: () => import('./CronTools.vue'),
|
||||||
|
base64: () => import('./Base64Tools.vue'),
|
||||||
|
url: () => import('./UrlTools.vue'),
|
||||||
|
jwt: () => import('./JwtTools.vue'),
|
||||||
|
escape: () => import('./EscapeTools.vue'),
|
||||||
|
case: () => import('./CaseTools.vue'),
|
||||||
|
regex: () => import('./RegexTools.vue'),
|
||||||
|
diff: () => import('./DiffTools.vue'),
|
||||||
|
eol: () => import('./EolTools.vue'),
|
||||||
|
replace: () => import('./ReplaceTools.vue'),
|
||||||
|
charcount: () => import('./CharCountTools.vue'),
|
||||||
|
uuid: () => import('./UuidTools.vue'),
|
||||||
|
hash: () => import('./HashTools.vue'),
|
||||||
|
password: () => import('./PasswordTools.vue'),
|
||||||
|
httpstatus: () => import('./HttpStatusTools.vue')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 将所有工具注册进注册表(幂等) */
|
||||||
|
export function registerAllTools(): void {
|
||||||
|
for (const meta of TOOLS_META) {
|
||||||
|
registerTool({
|
||||||
|
...meta,
|
||||||
|
icon: TOOL_ICONS[meta.id],
|
||||||
|
component: defineAsyncComponent(TOOL_COMPONENTS[meta.id])
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,7 +6,9 @@ import {
|
|||||||
Camera,
|
Camera,
|
||||||
Activity,
|
Activity,
|
||||||
Download,
|
Download,
|
||||||
Command
|
Command,
|
||||||
|
Wrench,
|
||||||
|
Music
|
||||||
} from '@lucide/vue'
|
} from '@lucide/vue'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -23,7 +25,9 @@ export const moduleIconMap: Record<string, Component> = {
|
|||||||
screenshot: Camera,
|
screenshot: Camera,
|
||||||
monitor: Activity,
|
monitor: Activity,
|
||||||
downloader: Download,
|
downloader: Download,
|
||||||
quickpanel: Command
|
quickpanel: Command,
|
||||||
|
devtools: Wrench,
|
||||||
|
music: Music
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 获取模块图标组件,未找到时回退到 Settings 图标 */
|
/** 获取模块图标组件,未找到时回退到 Settings 图标 */
|
||||||
|
|||||||
@@ -8,7 +8,9 @@ import { moduleConfig as screenshot } from './screenshot'
|
|||||||
import { moduleConfig as monitor } from './monitor'
|
import { moduleConfig as monitor } from './monitor'
|
||||||
import { moduleConfig as downloader } from './downloader'
|
import { moduleConfig as downloader } from './downloader'
|
||||||
import { moduleConfig as quickpanel } from './quickpanel'
|
import { moduleConfig as quickpanel } from './quickpanel'
|
||||||
|
import { moduleConfig as devtools } from './devtools'
|
||||||
import { moduleConfig as settings } from './settings'
|
import { moduleConfig as settings } from './settings'
|
||||||
|
import { moduleConfig as music } from './music'
|
||||||
|
|
||||||
const allModules: ModuleConfig[] = [
|
const allModules: ModuleConfig[] = [
|
||||||
proxy,
|
proxy,
|
||||||
@@ -17,7 +19,9 @@ const allModules: ModuleConfig[] = [
|
|||||||
monitor,
|
monitor,
|
||||||
downloader,
|
downloader,
|
||||||
quickpanel,
|
quickpanel,
|
||||||
settings
|
devtools,
|
||||||
|
settings,
|
||||||
|
music
|
||||||
]
|
]
|
||||||
|
|
||||||
// 启动时注册所有模块
|
// 启动时注册所有模块
|
||||||
|
|||||||
@@ -279,6 +279,7 @@ function fmtFixedValue(v: number | null, item: OsdItem): string {
|
|||||||
case 'temperature':
|
case 'temperature':
|
||||||
return padNum(Math.round(v).toString(), 3) // 0-150 → 3 字符
|
return padNum(Math.round(v).toString(), 3) // 0-150 → 3 字符
|
||||||
case 'power':
|
case 'power':
|
||||||
|
return padNum(v.toFixed(2), 6) // 12.34 / 123.45 → 6 字符(支持三位数功耗)
|
||||||
case 'voltage':
|
case 'voltage':
|
||||||
return padNum(v.toFixed(2), 5) // 12.34 → 5 字符
|
return padNum(v.toFixed(2), 5) // 12.34 → 5 字符
|
||||||
case 'clock':
|
case 'clock':
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,70 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { ChevronDown } from '@lucide/vue'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Checkbox } from '@/components/ui/checkbox'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||||
|
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||||
|
import { sourceName } from './sources'
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
modelValue: string[]
|
||||||
|
/** 可选源(客户端名)列表 */
|
||||||
|
options: string[]
|
||||||
|
}>()
|
||||||
|
const emit = defineEmits<{ 'update:model-value': [string[]] }>()
|
||||||
|
|
||||||
|
const open = ref(false)
|
||||||
|
|
||||||
|
const checked = computed(() => new Set(props.modelValue))
|
||||||
|
|
||||||
|
const toggle = (code: string) => {
|
||||||
|
const next = new Set(checked.value)
|
||||||
|
if (next.has(code)) next.delete(code)
|
||||||
|
else next.add(code)
|
||||||
|
emit('update:model-value', [...next])
|
||||||
|
}
|
||||||
|
|
||||||
|
const label = computed(() => {
|
||||||
|
if (props.modelValue.length === 0) return '未选择'
|
||||||
|
if (props.modelValue.length === 1) return sourceName(props.modelValue[0])
|
||||||
|
return `已选 ${props.modelValue.length} 个源`
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Popover v-model:open="open">
|
||||||
|
<PopoverTrigger as-child>
|
||||||
|
<Button variant="outline" class="justify-between font-normal" size="sm">
|
||||||
|
<span class="truncate">{{ label }}</span>
|
||||||
|
<ChevronDown class="size-3.5 opacity-50 shrink-0" />
|
||||||
|
</Button>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent class="w-64 p-2" align="start">
|
||||||
|
<!-- ScrollArea 的 viewport h-full 需要 root 有确定高度才滚动;max-h 不生效,用固定 h-72 -->
|
||||||
|
<ScrollArea class="h-72">
|
||||||
|
<div class="space-y-0.5 pr-2">
|
||||||
|
<label
|
||||||
|
v-for="code in options"
|
||||||
|
:key="code"
|
||||||
|
class="flex items-center gap-2 rounded-md px-2 py-1.5 cursor-pointer hover:bg-muted/50"
|
||||||
|
>
|
||||||
|
<Checkbox
|
||||||
|
:model-value="checked.has(code)"
|
||||||
|
@update:model-value="toggle(code)"
|
||||||
|
/>
|
||||||
|
<Label class="text-sm cursor-pointer truncate">{{ sourceName(code) }}</Label>
|
||||||
|
</label>
|
||||||
|
<p v-if="options.length === 0" class="px-2 py-3 text-xs text-muted-foreground">
|
||||||
|
未获取到可用源,请先安装环境
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</ScrollArea>
|
||||||
|
<div class="mt-1 border-t pt-1.5 px-1 flex items-center justify-between">
|
||||||
|
<span class="text-xs text-muted-foreground">{{ options.length }} 个可选源</span>
|
||||||
|
<span class="text-xs text-muted-foreground">已选 {{ props.modelValue.length }}</span>
|
||||||
|
</div>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,269 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, ref } from 'vue'
|
||||||
|
import { toast } from 'vue-sonner'
|
||||||
|
import { FolderOpen, Loader2, Music2, Plus, RefreshCw, Trash2 } from '@lucide/vue'
|
||||||
|
import { useFeiniuStore, type Playlist } from '@/stores/feiniuStore'
|
||||||
|
import TrackItem from './TrackItem.vue'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Empty } from '@/components/ui/empty'
|
||||||
|
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||||
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||||
|
|
||||||
|
const store = useFeiniuStore()
|
||||||
|
|
||||||
|
type SubTab = 'feiniu' | 'local' | 'playlists'
|
||||||
|
const subTab = ref<SubTab>('feiniu')
|
||||||
|
|
||||||
|
// 未登录(无激活连接且未登录)
|
||||||
|
const needsLogin = computed(() => !store.config.loggedIn && !store.activeConn)
|
||||||
|
|
||||||
|
const keywordInput = ref('')
|
||||||
|
let searchTimer: ReturnType<typeof setTimeout> | undefined
|
||||||
|
|
||||||
|
function onSearchInput() {
|
||||||
|
clearTimeout(searchTimer)
|
||||||
|
searchTimer = setTimeout(() => {
|
||||||
|
store.loadTracks(1).catch((e) => toast.error(String(e)))
|
||||||
|
}, 400)
|
||||||
|
}
|
||||||
|
|
||||||
|
function refreshFeiniu() {
|
||||||
|
store.loadTracks(store.page).catch((e) => toast.error(String(e)))
|
||||||
|
}
|
||||||
|
|
||||||
|
function refreshLocal() {
|
||||||
|
store.scanLocal().catch((e) => toast.error(String(e)))
|
||||||
|
}
|
||||||
|
|
||||||
|
function playAll() {
|
||||||
|
const list =
|
||||||
|
subTab.value === 'feiniu' ? store.tracks : subTab.value === 'local' ? store.localTracks : []
|
||||||
|
if (list.length) store.playQueue(list, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 歌单 =====
|
||||||
|
const playlistName = ref('')
|
||||||
|
const createOpen = ref(false)
|
||||||
|
const activePlaylistId = ref('')
|
||||||
|
const activePlaylist = computed<Playlist | null>(
|
||||||
|
() => store.playlists.find((p) => p.id === activePlaylistId.value) || null
|
||||||
|
)
|
||||||
|
|
||||||
|
function createPlaylist() {
|
||||||
|
if (!playlistName.value.trim()) {
|
||||||
|
toast.error('请输入歌单名称')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const id = store.createPlaylist(playlistName.value.trim())
|
||||||
|
activePlaylistId.value = id
|
||||||
|
playlistName.value = ''
|
||||||
|
createOpen.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
await store.init()
|
||||||
|
if (store.config.loggedIn) {
|
||||||
|
store.loadTracks(1).catch(() => {})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<ScrollArea class="h-full pr-3">
|
||||||
|
<div class="flex flex-col gap-4 px-1 pt-1 pb-4 min-w-0">
|
||||||
|
<!-- 未登录态:引导配置连接 -->
|
||||||
|
<div v-if="needsLogin" class="flex flex-col items-center gap-3 py-16 text-center">
|
||||||
|
<Music2 class="size-10 text-muted-foreground" />
|
||||||
|
<p class="text-sm text-muted-foreground">
|
||||||
|
还没有可用的飞牛音乐连接。请到「设置 → 飞牛音乐连接」添加并登录,
|
||||||
|
<br />
|
||||||
|
或先到「发现音乐」下载歌曲到本地曲库。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-else>
|
||||||
|
<!-- 页头 + 子导航 -->
|
||||||
|
<div class="flex flex-col gap-3">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div class="flex items-center gap-1 rounded-lg border bg-card p-1">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="rounded-md px-3 py-1 text-sm transition-colors"
|
||||||
|
:class="subTab === 'feiniu' ? 'bg-primary text-primary-foreground' : 'text-muted-foreground hover:text-foreground'"
|
||||||
|
@click="subTab = 'feiniu'"
|
||||||
|
>
|
||||||
|
飞牛曲库
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="rounded-md px-3 py-1 text-sm transition-colors"
|
||||||
|
:class="subTab === 'local' ? 'bg-primary text-primary-foreground' : 'text-muted-foreground hover:text-foreground'"
|
||||||
|
@click="subTab = 'local'"
|
||||||
|
>
|
||||||
|
本地曲库
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="rounded-md px-3 py-1 text-sm transition-colors"
|
||||||
|
:class="subTab === 'playlists' ? 'bg-primary text-primary-foreground' : 'text-muted-foreground hover:text-foreground'"
|
||||||
|
@click="subTab = 'playlists'"
|
||||||
|
>
|
||||||
|
我的歌单
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<Button v-if="store.config.loggedIn" variant="outline" size="sm" @click="playAll">
|
||||||
|
▶ 播放全部
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ===== 飞牛曲库 ===== -->
|
||||||
|
<template v-if="subTab === 'feiniu'">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<div class="flex-1">
|
||||||
|
<Input v-model="keywordInput" placeholder="搜索飞牛曲库(歌名 / 歌手)" @input="onSearchInput" @keydown.enter="onSearchInput" />
|
||||||
|
</div>
|
||||||
|
<Button variant="outline" size="icon" :disabled="store.loading" @click="refreshFeiniu">
|
||||||
|
<RefreshCw :class="store.loading ? 'size-4 animate-spin' : 'size-4'" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<div v-if="store.loading" class="flex items-center justify-center gap-2 py-10 text-sm text-muted-foreground">
|
||||||
|
<Loader2 class="size-4 animate-spin" /> 加载曲库…
|
||||||
|
</div>
|
||||||
|
<Empty v-else-if="!store.tracks.length" class="min-h-40">
|
||||||
|
<Music2 class="size-10 text-muted-foreground" />
|
||||||
|
<p class="text-sm text-muted-foreground">
|
||||||
|
{{ store.config.loggedIn ? '曲库为空或未匹配到结果' : '请先在设置中登录飞牛音乐连接' }}
|
||||||
|
</p>
|
||||||
|
</Empty>
|
||||||
|
<template v-else>
|
||||||
|
<TrackItem
|
||||||
|
v-for="(t, i) in store.tracks"
|
||||||
|
:key="t.guid || i"
|
||||||
|
:item="t"
|
||||||
|
:active="store.current?.guid === t.guid"
|
||||||
|
@dblclick="store.playQueue(store.tracks, i)"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- ===== 本地曲库 ===== -->
|
||||||
|
<template v-else-if="subTab === 'local'">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<Button variant="outline" size="sm" :disabled="store.localScanBusy" @click="refreshLocal">
|
||||||
|
<Loader2 v-if="store.localScanBusy" class="size-4 animate-spin" />
|
||||||
|
<FolderOpen v-else class="size-4" />
|
||||||
|
扫描本地
|
||||||
|
</Button>
|
||||||
|
<span class="text-xs text-muted-foreground">{{ store.localTracks.length }} 首(目录:音乐下载目录 + 自定义)</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<Empty v-if="!store.localTracks.length && !store.localScanBusy" class="min-h-40">
|
||||||
|
<FolderOpen class="size-10 text-muted-foreground" />
|
||||||
|
<p class="text-sm text-muted-foreground">暂无本地音乐,点击「扫描本地」或先到发现音乐下载</p>
|
||||||
|
</Empty>
|
||||||
|
<template v-else>
|
||||||
|
<TrackItem
|
||||||
|
v-for="(t, i) in store.localTracks"
|
||||||
|
:key="t.guid || i"
|
||||||
|
:item="t"
|
||||||
|
:active="store.current?.guid === t.guid"
|
||||||
|
@dblclick="store.playQueue(store.localTracks, i)"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- ===== 我的歌单 ===== -->
|
||||||
|
<template v-else>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<Button variant="outline" size="sm" @click="createOpen = true">
|
||||||
|
<Plus class="size-4" /> 新建歌单
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 歌单列表(左) + 详情(右) -->
|
||||||
|
<div class="grid grid-cols-1 gap-4 md:grid-cols-[220px_1fr]">
|
||||||
|
<div class="flex flex-col gap-1 rounded-lg border bg-card p-2">
|
||||||
|
<button
|
||||||
|
v-for="p in store.playlists"
|
||||||
|
:key="p.id"
|
||||||
|
type="button"
|
||||||
|
class="flex items-center justify-between rounded-md px-3 py-2 text-sm transition-colors"
|
||||||
|
:class="activePlaylistId === p.id ? 'bg-primary/10 text-foreground' : 'text-muted-foreground hover:bg-muted/40'"
|
||||||
|
@click="activePlaylistId = p.id"
|
||||||
|
>
|
||||||
|
<span class="truncate">{{ p.name }}</span>
|
||||||
|
<span class="text-xs">{{ p.items.length }}</span>
|
||||||
|
</button>
|
||||||
|
<Empty v-if="!store.playlists.length" class="min-h-32">
|
||||||
|
<p class="text-sm text-muted-foreground">还没有歌单</p>
|
||||||
|
</Empty>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<div v-if="activePlaylist" class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<div class="text-base font-semibold">{{ activePlaylist.name }}</div>
|
||||||
|
<div class="text-xs text-muted-foreground">{{ activePlaylist.items.length }} 首</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<Button variant="outline" size="sm" :disabled="!activePlaylist.items.length" @click="store.playQueue(activePlaylist.items, 0)">
|
||||||
|
▶ 播放全部
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
class="size-8 text-destructive"
|
||||||
|
@click="store.deletePlaylist(activePlaylist.id); activePlaylistId = ''"
|
||||||
|
>
|
||||||
|
<Trash2 class="size-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div v-if="activePlaylist" class="flex flex-col gap-1.5">
|
||||||
|
<TrackItem
|
||||||
|
v-for="(t, i) in activePlaylist.items"
|
||||||
|
:key="`${t.source}-${t.guid}-${i}`"
|
||||||
|
:item="t"
|
||||||
|
:active="store.current?.guid === t.guid"
|
||||||
|
/>
|
||||||
|
<div class="mt-1 flex justify-end">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
class="text-xs text-muted-foreground"
|
||||||
|
@click="store.removeFromPlaylist(activePlaylist.id, activePlaylist.items.length - 1)"
|
||||||
|
>
|
||||||
|
移除最后一首
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Empty v-else class="min-h-40">
|
||||||
|
<p class="text-sm text-muted-foreground">选择左侧歌单查看内容</p>
|
||||||
|
</Empty>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</ScrollArea>
|
||||||
|
|
||||||
|
<!-- 新建歌单弹窗 -->
|
||||||
|
<Dialog v-model:open="createOpen">
|
||||||
|
<DialogContent class="sm:max-w-sm">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>新建歌单</DialogTitle>
|
||||||
|
<DialogDescription>歌单保存在本机,可混合飞牛 NAS 与本地曲目。</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<Input v-model="playlistName" placeholder="歌单名称" @keydown.enter="createPlaylist" />
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" @click="createOpen = false">取消</Button>
|
||||||
|
<Button @click="createPlaylist">创建</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue'
|
||||||
|
import { ListMusic, Maximize2, Music2, Pause, Play, Repeat, Repeat1, Shuffle, SkipBack, SkipForward, Volume2 } from '@lucide/vue'
|
||||||
|
import { useFeiniuStore } from '@/stores/feiniuStore'
|
||||||
|
import { Slider } from '@/components/ui/slider'
|
||||||
|
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
|
||||||
|
|
||||||
|
const store = useFeiniuStore()
|
||||||
|
|
||||||
|
const coverUrl = computed(() => {
|
||||||
|
const t = store.current
|
||||||
|
if (t?.source === 'feiniu' && t.coverId && store.mediaPrefix) {
|
||||||
|
return `${store.mediaPrefix}/cover?coverId=${encodeURIComponent(t.coverId)}&size=96`
|
||||||
|
}
|
||||||
|
return ''
|
||||||
|
})
|
||||||
|
|
||||||
|
function onProgress(v: number[] | undefined) {
|
||||||
|
store.seek(((v?.[0] ?? 0) / 100) * store.duration)
|
||||||
|
}
|
||||||
|
|
||||||
|
function onVolume(v: number[] | undefined) {
|
||||||
|
store.setVolume((v?.[0] ?? 0) / 100)
|
||||||
|
}
|
||||||
|
|
||||||
|
const modeIcon = computed(() => {
|
||||||
|
if (store.playMode === 'loopOne') return Repeat1
|
||||||
|
if (store.playMode === 'shuffle') return Shuffle
|
||||||
|
return Repeat
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
class="flex items-center gap-3 border-t bg-background/80 px-4 py-2.5 backdrop-blur"
|
||||||
|
data-slot="player-bar"
|
||||||
|
>
|
||||||
|
<!-- 封面 + 信息(点击开 Now-Playing) -->
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex min-w-0 items-center gap-3 text-left"
|
||||||
|
@click="store.nowPlayingOpen = true"
|
||||||
|
>
|
||||||
|
<img
|
||||||
|
v-if="coverUrl"
|
||||||
|
:src="coverUrl"
|
||||||
|
class="size-11 shrink-0 rounded-md object-cover shadow"
|
||||||
|
alt=""
|
||||||
|
@error="($event.target as HTMLImageElement).style.display = 'none'"
|
||||||
|
/>
|
||||||
|
<div v-else class="flex size-11 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground">
|
||||||
|
<Music2 class="size-5" />
|
||||||
|
</div>
|
||||||
|
<div class="min-w-0 max-w-44">
|
||||||
|
<div class="truncate text-sm font-medium">{{ store.current?.title || '未播放' }}</div>
|
||||||
|
<div class="truncate text-xs text-muted-foreground">{{ store.current?.artistNames || '选择一首歌曲开始播放' }}</div>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<!-- 控制区 -->
|
||||||
|
<div class="flex flex-1 flex-col items-center gap-1">
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger as-child>
|
||||||
|
<button type="button" class="text-muted-foreground transition-colors hover:text-foreground" @click="store.togglePlayMode()">
|
||||||
|
<component :is="modeIcon" class="size-4" />
|
||||||
|
</button>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent>
|
||||||
|
{{ store.playMode === 'loopAll' ? '列表循环' : store.playMode === 'loopOne' ? '单曲循环' : '随机播放' }}
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
<button type="button" class="text-muted-foreground transition-colors hover:text-foreground" @click="store.prev()">
|
||||||
|
<SkipBack class="size-5" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex size-10 items-center justify-center rounded-full bg-primary text-primary-foreground transition-opacity hover:opacity-90"
|
||||||
|
:disabled="!store.current"
|
||||||
|
@click="store.toggle()"
|
||||||
|
>
|
||||||
|
<Pause v-if="store.playing" class="size-5" />
|
||||||
|
<Play v-else class="size-5 translate-x-[1px]" />
|
||||||
|
</button>
|
||||||
|
<button type="button" class="text-muted-foreground transition-colors hover:text-foreground" @click="store.next()">
|
||||||
|
<SkipForward class="size-5" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="relative text-muted-foreground transition-colors hover:text-foreground"
|
||||||
|
@click="store.queueVisible = !store.queueVisible"
|
||||||
|
>
|
||||||
|
<ListMusic class="size-4" />
|
||||||
|
<span
|
||||||
|
v-if="store.queue.length"
|
||||||
|
class="absolute -right-1.5 -top-1 flex size-3.5 items-center justify-center rounded-full bg-primary text-[8px] font-medium text-primary-foreground"
|
||||||
|
>
|
||||||
|
{{ store.queue.length }}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="flex w-full max-w-lg items-center gap-2">
|
||||||
|
<span class="w-10 text-right text-[10px] tabular-nums text-muted-foreground">{{ store.fmtDuration(store.position) }}</span>
|
||||||
|
<Slider
|
||||||
|
:model-value="[store.progress]"
|
||||||
|
class="flex-1"
|
||||||
|
:max="100"
|
||||||
|
:step="0.5"
|
||||||
|
@update:model-value="onProgress"
|
||||||
|
/>
|
||||||
|
<span class="w-10 text-[10px] tabular-nums text-muted-foreground">{{ store.fmtDuration(store.duration) }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 音量 + 歌词 + 最大化 -->
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<Volume2 class="size-4 text-muted-foreground" />
|
||||||
|
<Slider
|
||||||
|
:model-value="[store.volume * 100]"
|
||||||
|
class="w-20"
|
||||||
|
:max="100"
|
||||||
|
:step="1"
|
||||||
|
@update:model-value="onVolume"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="text-muted-foreground transition-colors hover:text-foreground"
|
||||||
|
:class="{ 'text-primary': store.lyricVisible }"
|
||||||
|
@click="store.lyricVisible = !store.lyricVisible"
|
||||||
|
>
|
||||||
|
词
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="text-muted-foreground transition-colors hover:text-foreground"
|
||||||
|
@click="store.nowPlayingOpen = true"
|
||||||
|
>
|
||||||
|
<Maximize2 class="size-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref, watchEffect } from 'vue'
|
||||||
|
import { ListMusic, Music2, Pause, Play, Repeat, Repeat1, Shuffle, SkipBack, SkipForward, X } from '@lucide/vue'
|
||||||
|
import { useFeiniuStore } from '@/stores/feiniuStore'
|
||||||
|
import { Slider } from '@/components/ui/slider'
|
||||||
|
import { Dialog, DialogContent, DialogClose } from '@/components/ui/dialog'
|
||||||
|
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||||
|
|
||||||
|
const store = useFeiniuStore()
|
||||||
|
|
||||||
|
const coverUrl = computed(() => {
|
||||||
|
const t = store.current
|
||||||
|
if (t?.source === 'feiniu' && t.coverId && store.mediaPrefix) {
|
||||||
|
return `${store.mediaPrefix}/cover?coverId=${encodeURIComponent(t.coverId)}&size=400`
|
||||||
|
}
|
||||||
|
return ''
|
||||||
|
})
|
||||||
|
|
||||||
|
const currentLineIdx = computed(() => store.currentLine())
|
||||||
|
|
||||||
|
function onProgress(v: number[] | undefined) {
|
||||||
|
store.seek(((v?.[0] ?? 0) / 100) * store.duration)
|
||||||
|
}
|
||||||
|
|
||||||
|
const modeIcon = computed(() => {
|
||||||
|
if (store.playMode === 'loopOne') return Repeat1
|
||||||
|
if (store.playMode === 'shuffle') return Shuffle
|
||||||
|
return Repeat
|
||||||
|
})
|
||||||
|
|
||||||
|
// 歌词滚动跟随
|
||||||
|
const lyricScrollEl = ref<HTMLElement | null>(null)
|
||||||
|
watchEffect(() => {
|
||||||
|
const idx = currentLineIdx.value
|
||||||
|
if (idx < 0 || !lyricScrollEl.value) return
|
||||||
|
const nodes = lyricScrollEl.value.querySelectorAll<HTMLElement>('[data-line]')
|
||||||
|
const node = nodes[idx]
|
||||||
|
if (node) node.scrollIntoView({ block: 'center', behavior: 'smooth' })
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Dialog v-model:open="store.nowPlayingOpen">
|
||||||
|
<DialogContent
|
||||||
|
class="max-w-4xl overflow-hidden border-0 p-0 sm:max-w-5xl"
|
||||||
|
:show-close-button="false"
|
||||||
|
>
|
||||||
|
<div class="relative flex min-h-[70vh] flex-col">
|
||||||
|
<!-- 背景渐变 -->
|
||||||
|
<div class="pointer-events-none absolute inset-0">
|
||||||
|
<img v-if="coverUrl" :src="coverUrl" class="h-full w-full scale-110 object-cover blur-2xl opacity-30" alt="" />
|
||||||
|
<div class="absolute inset-0 bg-gradient-to-b from-background/60 via-background/85 to-background" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="relative flex min-h-0 flex-1">
|
||||||
|
<!-- 左:封面 + 控制 -->
|
||||||
|
<div class="flex w-1/2 flex-col items-center justify-center gap-5 p-8">
|
||||||
|
<img
|
||||||
|
v-if="coverUrl"
|
||||||
|
:src="coverUrl"
|
||||||
|
class="size-64 rounded-xl object-cover shadow-2xl ring-1 ring-border"
|
||||||
|
alt=""
|
||||||
|
/>
|
||||||
|
<div v-else class="flex size-64 items-center justify-center rounded-xl bg-muted/40 text-muted-foreground shadow-2xl">
|
||||||
|
<Music2 class="size-20" />
|
||||||
|
</div>
|
||||||
|
<div class="text-center">
|
||||||
|
<div class="truncate text-2xl font-semibold">{{ store.current?.title || '未播放' }}</div>
|
||||||
|
<div class="mt-1 truncate text-sm text-muted-foreground">
|
||||||
|
{{ store.current?.artistNames || '—' }}<template v-if="store.current?.album"> · {{ store.current.album }}</template>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex w-full max-w-sm flex-col gap-2">
|
||||||
|
<Slider
|
||||||
|
:model-value="[store.progress]"
|
||||||
|
:max="100"
|
||||||
|
:step="0.5"
|
||||||
|
@update:model-value="onProgress"
|
||||||
|
/>
|
||||||
|
<div class="flex justify-between text-[11px] tabular-nums text-muted-foreground">
|
||||||
|
<span>{{ store.fmtDuration(store.position) }}</span>
|
||||||
|
<span>{{ store.fmtDuration(store.duration) }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="mt-1 flex items-center justify-center gap-6">
|
||||||
|
<button type="button" class="text-muted-foreground hover:text-foreground" @click="store.togglePlayMode()">
|
||||||
|
<component :is="modeIcon" class="size-5" />
|
||||||
|
</button>
|
||||||
|
<button type="button" class="text-muted-foreground hover:text-foreground" @click="store.prev()">
|
||||||
|
<SkipBack class="size-7" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex size-16 items-center justify-center rounded-full bg-primary text-primary-foreground transition-opacity hover:opacity-90"
|
||||||
|
:disabled="!store.current"
|
||||||
|
@click="store.toggle()"
|
||||||
|
>
|
||||||
|
<Pause v-if="store.playing" class="size-8" />
|
||||||
|
<Play v-else class="size-8 translate-x-[1px]" />
|
||||||
|
</button>
|
||||||
|
<button type="button" class="text-muted-foreground hover:text-foreground" @click="store.next()">
|
||||||
|
<SkipForward class="size-7" />
|
||||||
|
</button>
|
||||||
|
<button type="button" class="text-muted-foreground hover:text-foreground" @click="store.queueVisible = true">
|
||||||
|
<ListMusic class="size-5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 右:歌词 / 队列 -->
|
||||||
|
<div class="flex w-1/2 flex-col border-l border-white/10 p-6">
|
||||||
|
<div class="mb-3 flex items-center justify-between">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="text-sm"
|
||||||
|
:class="!store.queueVisible ? 'font-semibold text-foreground' : 'text-muted-foreground'"
|
||||||
|
@click="store.queueVisible = false"
|
||||||
|
>
|
||||||
|
歌词
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="text-sm"
|
||||||
|
:class="store.queueVisible ? 'font-semibold text-foreground' : 'text-muted-foreground'"
|
||||||
|
@click="store.queueVisible = true"
|
||||||
|
>
|
||||||
|
队列({{ store.queue.length }})
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<ScrollArea class="min-h-0 flex-1 pr-3">
|
||||||
|
<div v-if="!store.queueVisible" ref="lyricScrollEl" class="flex flex-col gap-1 py-2">
|
||||||
|
<p v-if="!store.lyricLines.length" class="text-sm text-muted-foreground/60">
|
||||||
|
{{ store.current?.source === 'local' ? '本地文件无歌词' : '暂无歌词' }}
|
||||||
|
</p>
|
||||||
|
<p
|
||||||
|
v-for="(line, idx) in store.lyricLines"
|
||||||
|
:key="idx"
|
||||||
|
data-line
|
||||||
|
class="cursor-pointer py-1 text-[15px] leading-7 transition-colors"
|
||||||
|
:class="idx === currentLineIdx ? 'font-medium text-foreground' : 'text-muted-foreground/60'"
|
||||||
|
@click="store.seek(line.t)"
|
||||||
|
>
|
||||||
|
{{ line.text }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div v-else class="flex flex-col gap-1.5 py-1">
|
||||||
|
<p v-if="!store.queue.length" class="text-sm text-muted-foreground/60">队列为空</p>
|
||||||
|
<button
|
||||||
|
v-for="(q, i) in store.queue"
|
||||||
|
:key="i"
|
||||||
|
type="button"
|
||||||
|
class="flex items-center gap-3 rounded-md px-2 py-1.5 text-left transition-colors"
|
||||||
|
:class="i === store.queueIndex ? 'bg-primary/10' : 'hover:bg-muted/40'"
|
||||||
|
@click="store.queueIndex = i; store.playItem(q)"
|
||||||
|
>
|
||||||
|
<span class="w-5 text-right text-xs tabular-nums text-muted-foreground">{{ i + 1 }}</span>
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<div class="truncate text-sm" :class="i === store.queueIndex ? 'font-medium' : ''">{{ q.title }}</div>
|
||||||
|
<div class="truncate text-xs text-muted-foreground">{{ q.artistNames }}</div>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</ScrollArea>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogClose as-child>
|
||||||
|
<button type="button" class="absolute right-4 top-4 z-10 rounded-md p-1.5 text-muted-foreground hover:bg-muted/40 hover:text-foreground">
|
||||||
|
<X class="size-5" />
|
||||||
|
</button>
|
||||||
|
</DialogClose>
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue'
|
||||||
|
import { toast } from 'vue-sonner'
|
||||||
|
import { Cloud, Music2, MoreHorizontal, Play, Plus } from '@lucide/vue'
|
||||||
|
import type { PlayableItem } from '@/stores/feiniuStore'
|
||||||
|
import { useFeiniuStore } from '@/stores/feiniuStore'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuLabel,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuSub,
|
||||||
|
DropdownMenuSubContent,
|
||||||
|
DropdownMenuSubTrigger,
|
||||||
|
DropdownMenuTrigger
|
||||||
|
} from '@/components/ui/dropdown-menu'
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
item: PlayableItem
|
||||||
|
active?: boolean
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const store = useFeiniuStore()
|
||||||
|
|
||||||
|
const coverUrl = computed(() => {
|
||||||
|
if (props.item.source === 'feiniu' && props.item.coverId && store.mediaPrefix) {
|
||||||
|
return `${store.mediaPrefix}/cover?coverId=${encodeURIComponent(props.item.coverId)}&size=64`
|
||||||
|
}
|
||||||
|
return ''
|
||||||
|
})
|
||||||
|
|
||||||
|
const durationText = computed(() => store.fmtDuration(props.item.durationMs ? props.item.durationMs / 1000 : undefined))
|
||||||
|
|
||||||
|
function addToPlaylist(playlistId: string) {
|
||||||
|
store.addToPlaylist(playlistId, [props.item])
|
||||||
|
toast.success('已加入歌单')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function uploadToFeiniu() {
|
||||||
|
try {
|
||||||
|
await store.uploadLocalTrack(props.item)
|
||||||
|
toast.success('已上传到飞牛曲库')
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(String(e))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
class="group flex items-center gap-3 rounded-lg border px-3 py-2 transition-colors"
|
||||||
|
:class="active ? 'border-primary bg-primary/10' : 'border-border hover:bg-muted/40'"
|
||||||
|
>
|
||||||
|
<img
|
||||||
|
v-if="coverUrl"
|
||||||
|
:src="coverUrl"
|
||||||
|
class="size-10 shrink-0 rounded-md object-cover"
|
||||||
|
alt=""
|
||||||
|
loading="lazy"
|
||||||
|
@error="($event.target as HTMLImageElement).style.display = 'none'"
|
||||||
|
/>
|
||||||
|
<div v-else class="flex size-10 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground">
|
||||||
|
<Music2 class="size-4" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex size-10 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground opacity-0 transition-opacity group-hover:opacity-100"
|
||||||
|
:disabled="store.playing && store.current?.guid === item.guid"
|
||||||
|
@click="store.playItem(item)"
|
||||||
|
>
|
||||||
|
<Play class="size-4 translate-x-[1px]" />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<div class="truncate text-sm font-medium">{{ item.title }}</div>
|
||||||
|
<div class="truncate text-xs text-muted-foreground">
|
||||||
|
{{ item.artistNames }}<template v-if="item.artistNames && item.album"> · </template>{{ item.album }}
|
||||||
|
<span v-if="item.source === 'local'" class="ml-1 rounded bg-muted px-1 text-[10px]">本地</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<span class="shrink-0 text-xs tabular-nums text-muted-foreground">{{ durationText }}</span>
|
||||||
|
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger as-child>
|
||||||
|
<Button size="icon" variant="ghost" class="size-8">
|
||||||
|
<MoreHorizontal class="size-4" />
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end" class="w-48">
|
||||||
|
<DropdownMenuLabel>{{ item.title }}</DropdownMenuLabel>
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
<DropdownMenuItem @click="store.playItem(item)">
|
||||||
|
<Play class="size-4" /> 播放
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem
|
||||||
|
v-if="item.source === 'local' && store.fnosLoggedIn && store.libraryNasPath"
|
||||||
|
:disabled="store.uploading"
|
||||||
|
@click="uploadToFeiniu"
|
||||||
|
>
|
||||||
|
<Cloud class="size-4" /> 上传到飞牛曲库
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuSub>
|
||||||
|
<DropdownMenuSubTrigger>
|
||||||
|
<Plus class="size-4" /> 加入歌单
|
||||||
|
</DropdownMenuSubTrigger>
|
||||||
|
<DropdownMenuSubContent class="w-48 max-h-64 overflow-y-auto">
|
||||||
|
<DropdownMenuItem v-if="store.playlists.length === 0" disabled>还没有歌单</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem v-for="p in store.playlists" :key="p.id" @click="addToPlaylist(p.id)">
|
||||||
|
{{ p.name }}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuSubContent>
|
||||||
|
</DropdownMenuSub>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { onMounted, ref } from 'vue'
|
||||||
|
import { toast } from 'vue-sonner'
|
||||||
|
import { HardDriveDownload, Trash2 } from '@lucide/vue'
|
||||||
|
import { useFeiniuStore } from '@/stores/feiniuStore'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Switch } from '@/components/ui/switch'
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||||
|
|
||||||
|
const store = useFeiniuStore()
|
||||||
|
|
||||||
|
const cacheMax = ref(5)
|
||||||
|
const cacheEnabled = ref(false)
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
await store.init()
|
||||||
|
cacheMode.value = store.cacheMode
|
||||||
|
cacheMax.value = 5
|
||||||
|
})
|
||||||
|
|
||||||
|
// 本地持久化缓存设置(后端 cache_fetch 用 settings.feiniu_cache_max_gb;这里给个默认)
|
||||||
|
const cacheMode = ref<'stream' | 'cache'>(store.cacheMode)
|
||||||
|
|
||||||
|
function setMode(v: unknown) {
|
||||||
|
const mode = v === 'cache' ? 'cache' : 'stream'
|
||||||
|
cacheMode.value = mode
|
||||||
|
store.setCacheMode(mode)
|
||||||
|
toast.success(mode === 'cache' ? '已开启缓存后播放' : '已切换为直连流式播放')
|
||||||
|
}
|
||||||
|
|
||||||
|
function setEnabled(v: boolean) {
|
||||||
|
cacheEnabled.value = v
|
||||||
|
if (!v) store.setCacheMode('stream')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function clearAll() {
|
||||||
|
await store.clearCache()
|
||||||
|
toast.success('缓存已清空')
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="space-y-4">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<HardDriveDownload class="size-4 text-muted-foreground" />
|
||||||
|
<Label class="font-medium">播放缓存</Label>
|
||||||
|
</div>
|
||||||
|
<p class="mt-1 text-xs text-muted-foreground">
|
||||||
|
缓存后播放:把 NAS 音频缓存到本机({{ store.cacheStatus.usedMb }} MB / {{ store.cacheStatus.count }} 首),
|
||||||
|
超出上限自动按 LRU 淘汰。直连流式则每次在线拉取。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Switch v-model:model-value="cacheEnabled" @update:model-value="setEnabled" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-if="cacheEnabled">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<Label class="text-muted-foreground">播放模式</Label>
|
||||||
|
<Select :model-value="cacheMode" @update:model-value="setMode">
|
||||||
|
<SelectTrigger class="w-44">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="stream">直连流式</SelectItem>
|
||||||
|
<SelectItem value="cache">缓存后播放</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<Label class="text-muted-foreground">当前占用</Label>
|
||||||
|
<span class="text-sm tabular-nums">{{ store.cacheStatus.usedMb }} MB({{ store.cacheStatus.count }} 首)</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button variant="outline" size="sm" class="text-destructive" @click="clearAll">
|
||||||
|
<Trash2 class="size-4" /> 清空缓存
|
||||||
|
</Button>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,257 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { onMounted, ref } from 'vue'
|
||||||
|
import { toast } from 'vue-sonner'
|
||||||
|
import { Check, Cloud, Loader2, Pencil, Plus, Power, Trash2 } from '@lucide/vue'
|
||||||
|
import { useFeiniuStore, type FeiniuConnection } from '@/stores/feiniuStore'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Switch } from '@/components/ui/switch'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle
|
||||||
|
} from '@/components/ui/dialog'
|
||||||
|
|
||||||
|
const store = useFeiniuStore()
|
||||||
|
|
||||||
|
const editing = ref<Partial<FeiniuConnection> | null>(null)
|
||||||
|
const editOpen = ref(false)
|
||||||
|
const password = ref('')
|
||||||
|
const testing = ref(false)
|
||||||
|
const fnosPassword = ref('')
|
||||||
|
const fnosFormOpen = ref(false)
|
||||||
|
/** 目标 fnOS 登录连接 */
|
||||||
|
const fnosTarget = ref<FeiniuConnection | null>(null)
|
||||||
|
|
||||||
|
function newForm() {
|
||||||
|
editing.value = { name: '', kind: 'lan', baseUrl: '', username: '', accessCode: '', insecure: false, fnId: '' }
|
||||||
|
password.value = ''
|
||||||
|
editOpen.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function editForm(c: FeiniuConnection) {
|
||||||
|
editing.value = { ...c }
|
||||||
|
password.value = ''
|
||||||
|
editOpen.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function openFnosLogin(c: FeiniuConnection) {
|
||||||
|
fnosTarget.value = c
|
||||||
|
fnosPassword.value = ''
|
||||||
|
fnosFormOpen.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
if (!editing.value) return
|
||||||
|
if (!editing.value.name?.trim() || !editing.value.baseUrl?.trim()) {
|
||||||
|
toast.error('请填写名称与服务器地址')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const id = await store.saveConnection({
|
||||||
|
id: editing.value.id || '',
|
||||||
|
name: editing.value.name.trim(),
|
||||||
|
kind: editing.value.kind || 'lan',
|
||||||
|
baseUrl: editing.value.baseUrl.trim(),
|
||||||
|
username: editing.value.username || '',
|
||||||
|
accessCode: editing.value.accessCode || '',
|
||||||
|
insecure: !!editing.value.insecure,
|
||||||
|
fnId: editing.value.fnId || ''
|
||||||
|
})
|
||||||
|
if (password.value) {
|
||||||
|
await store.login(id, editing.value.username || '', password.value)
|
||||||
|
}
|
||||||
|
editOpen.value = false
|
||||||
|
toast.success('已保存')
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(String(e))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function test(c: FeiniuConnection) {
|
||||||
|
if (!password.value) {
|
||||||
|
toast.error('请输入密码再测试')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
testing.value = true
|
||||||
|
try {
|
||||||
|
await store.testConnection(c.id, c.username, password.value)
|
||||||
|
toast.success('连接成功')
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(String(e))
|
||||||
|
} finally {
|
||||||
|
testing.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function activate(c: FeiniuConnection) {
|
||||||
|
await store.activateConnection(c.id)
|
||||||
|
toast.success('已切换为激活连接')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function logout(c: FeiniuConnection) {
|
||||||
|
await store.logout(c.id)
|
||||||
|
toast.success('已登出')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove(c: FeiniuConnection) {
|
||||||
|
await store.deleteConnection(c.id)
|
||||||
|
toast.success('已删除')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fnosLogin() {
|
||||||
|
if (!fnosTarget.value) return
|
||||||
|
if (!fnosPassword.value) {
|
||||||
|
toast.error('请输入 NAS 密码')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await store.fnosLogin(fnosTarget.value.username, fnosPassword.value)
|
||||||
|
fnosFormOpen.value = false
|
||||||
|
toast.success('NAS 文件服务已连接')
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(String(e))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function kindLabel(k: string) {
|
||||||
|
return k === 'lan' ? '局域网' : k === 'frp' ? 'frp 域名' : 'FnConnect'
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => store.refreshConnections())
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="space-y-3">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<Label class="text-muted-foreground">飞牛音乐连接</Label>
|
||||||
|
<Button variant="outline" size="sm" @click="newForm">
|
||||||
|
<Plus class="size-4" /> 新建
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<div
|
||||||
|
v-for="c in store.connections"
|
||||||
|
:key="c.id"
|
||||||
|
class="flex items-center gap-3 rounded-lg border bg-card px-3 py-2"
|
||||||
|
>
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<span class="truncate text-sm font-medium">{{ c.name }}</span>
|
||||||
|
<Badge variant="secondary" class="text-[10px]">{{ kindLabel(c.kind) }}</Badge>
|
||||||
|
<Badge v-if="store.activeId === c.id" variant="default" class="text-[10px]">激活</Badge>
|
||||||
|
</div>
|
||||||
|
<div class="truncate text-xs text-muted-foreground">
|
||||||
|
{{ c.baseUrl }}<template v-if="c.username"> · {{ c.username }}</template>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex shrink-0 items-center gap-1">
|
||||||
|
<span v-if="c.loggedIn" class="mr-1 flex items-center gap-1 text-xs text-emerald-600">
|
||||||
|
<Check class="size-3.5" /> 已登录
|
||||||
|
</span>
|
||||||
|
<Button v-if="store.activeId !== c.id" variant="ghost" size="icon" class="size-8" @click="activate(c)">
|
||||||
|
<Power class="size-4" />
|
||||||
|
</Button>
|
||||||
|
<Button v-if="store.activeId === c.id && !store.fnosLoggedIn" variant="ghost" size="icon" class="size-8" :title="`连接 NAS 文件服务(${c.username})`" @click="openFnosLogin(c)">
|
||||||
|
<Cloud class="size-4" />
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" size="icon" class="size-8" @click="editForm(c)">
|
||||||
|
<Pencil class="size-4" />
|
||||||
|
</Button>
|
||||||
|
<Button v-if="c.loggedIn" variant="ghost" size="icon" class="size-8" @click="logout(c)">
|
||||||
|
<Power class="size-4" />
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" size="icon" class="size-8 text-destructive" @click="remove(c)">
|
||||||
|
<Trash2 class="size-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p v-if="!store.connections.length" class="text-xs text-muted-foreground">
|
||||||
|
还没有连接。新建一个并填写 NAS 地址(局域网 http://192.168.x.x:5666、frp 域名或 FnConnect fnId)。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Dialog v-model:open="editOpen">
|
||||||
|
<DialogContent class="sm:max-w-md">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{{ editing?.id ? '编辑连接' : '新建连接' }}</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
<div class="flex flex-col gap-3">
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<Label>名称</Label>
|
||||||
|
<Input v-model="editing!.name" placeholder="如:家里 NAS / frp 远程 / FnConnect" />
|
||||||
|
</div>
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<Label>类型</Label>
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<Button
|
||||||
|
v-for="k in (['lan', 'frp', 'fnconnect'] as const)"
|
||||||
|
:key="k"
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
:variant="editing!.kind === k ? 'default' : 'outline'"
|
||||||
|
@click="editing!.kind = k"
|
||||||
|
>
|
||||||
|
{{ kindLabel(k) }}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div v-if="editing!.kind === 'fnconnect'" class="space-y-1.5">
|
||||||
|
<Label>FnConnect fnId(fnos.net/xxx 或裸 id)</Label>
|
||||||
|
<Input v-model="editing!.fnId" placeholder="fnos.net/zy2060537" />
|
||||||
|
<p class="text-xs text-muted-foreground">
|
||||||
|
保存后点登录会自动解析到可达地址;服务器地址会回填。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div v-else class="space-y-1.5">
|
||||||
|
<Label>服务器地址</Label>
|
||||||
|
<Input v-model="editing!.baseUrl" placeholder="http://192.168.1.10:5666 或 https://xxx.xxx.com" />
|
||||||
|
</div>
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<Label>账号</Label>
|
||||||
|
<Input v-model="editing!.username" placeholder="飞牛音乐账号" />
|
||||||
|
</div>
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<Label>密码{{ password ? '' : '(留空则保留已存 token)' }}</Label>
|
||||||
|
<Input v-model="password" type="password" placeholder="登录密码" />
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<Label class="text-muted-foreground">忽略 HTTPS 证书校验(自签证书时勾选)</Label>
|
||||||
|
<Switch v-model:model-value="editing!.insecure" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<DialogFooter class="gap-2">
|
||||||
|
<Button variant="outline" :disabled="testing" @click="test(editing as unknown as FeiniuConnection)">
|
||||||
|
<Loader2 v-if="testing" class="size-4 animate-spin" /> 测试
|
||||||
|
</Button>
|
||||||
|
<Button @click="save">保存</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
<!-- fnOS 文件服务登录(上传到飞牛用) -->
|
||||||
|
<Dialog v-model:open="fnosFormOpen">
|
||||||
|
<DialogContent class="sm:max-w-sm">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>连接 NAS 文件服务</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
<p class="text-xs text-muted-foreground">
|
||||||
|
账号:{{ fnosTarget?.username }}。连接后即可把本地音乐上传到飞牛曲库目录、从曲库删除音乐。
|
||||||
|
</p>
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<Label>NAS 密码</Label>
|
||||||
|
<Input v-model="fnosPassword" type="password" placeholder="NAS 登录密码" @keydown.enter="fnosLogin" />
|
||||||
|
</div>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" @click="fnosFormOpen = false">取消</Button>
|
||||||
|
<Button @click="fnosLogin">连接</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import type { ModuleConfig } from '@/types/module'
|
||||||
|
import type { SearchIndexItem } from '@/stores/searchIndex'
|
||||||
|
|
||||||
|
const searchItems: SearchIndexItem[] = [
|
||||||
|
{
|
||||||
|
title: '我的音乐',
|
||||||
|
description: '飞牛 NAS 曲库 / 本地曲库 / 自定义歌单与内嵌播放器',
|
||||||
|
keywords: ['音乐', 'music', '飞牛', 'NAS', '曲库', '歌单', '播放', '本地'],
|
||||||
|
tab: 'mymusic'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '发现音乐',
|
||||||
|
description: '多平台搜索歌曲并下载(本地 / 飞牛曲库)',
|
||||||
|
keywords: ['发现音乐', '搜索', '下载', '聚合', '在线', '网易云', 'qq', '酷狗'],
|
||||||
|
tab: 'discover'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '音乐设置',
|
||||||
|
description: '飞牛连接、播放缓存、下载目录与 Python 环境检查',
|
||||||
|
keywords: ['音乐设置', '飞牛连接', '缓存', '下载目录', '环境', 'python', 'musicdl'],
|
||||||
|
tab: 'settings'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
export const moduleConfig: ModuleConfig = {
|
||||||
|
id: 'music',
|
||||||
|
name: '音乐',
|
||||||
|
icon: 'music',
|
||||||
|
description: '飞牛音乐客户端(NAS 曲库 + 本地曲库 + 发现添加)',
|
||||||
|
category: 'media',
|
||||||
|
defaultEnabled: true,
|
||||||
|
loader: () => import('./MusicModule.vue'),
|
||||||
|
searchItems,
|
||||||
|
lifecycle: {
|
||||||
|
onEnable: async () => {
|
||||||
|
// 桥接进程按需拉起(首次搜索/环境检测时自动启动),此处无需预启动
|
||||||
|
},
|
||||||
|
onDisable: () => {
|
||||||
|
// 禁用模块时停止桥接进程,释放 Python 进程
|
||||||
|
// 直接 invoke 避免模块 index.ts 导入 store 造成循环依赖
|
||||||
|
import('@tauri-apps/api/core')
|
||||||
|
.then(({ invoke }) => invoke('music_stop_bridge'))
|
||||||
|
.catch(() => {})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
order: 55
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
/**
|
||||||
|
* 音乐源(musicdl MusicClient 名)→ 中文展示名映射。
|
||||||
|
* 未收录的源回退显示原始客户端名。
|
||||||
|
*/
|
||||||
|
export const SOURCE_NAMES: Record<string, string> = {
|
||||||
|
NeteaseMusicClient: '网易云',
|
||||||
|
QQMusicClient: 'QQ音乐',
|
||||||
|
KugouMusicClient: '酷狗',
|
||||||
|
KuwoMusicClient: '酷我',
|
||||||
|
MiguMusicClient: '咪咕',
|
||||||
|
QianqianMusicClient: '千千',
|
||||||
|
BilibiliMusicClient: 'B站音乐',
|
||||||
|
SodaMusicClient: '汽水音乐',
|
||||||
|
StreetVoiceMusicClient: '街声',
|
||||||
|
FiveSingMusicClient: '5SING',
|
||||||
|
BodianMusicClient: '波点音乐',
|
||||||
|
JooxMusicClient: 'JOOX',
|
||||||
|
MyFreeMP3MusicClient: 'MyFreeMP3',
|
||||||
|
XiaoBaiMusicClient: '小白音乐',
|
||||||
|
JBSouMusicClient: '煎饼搜',
|
||||||
|
TuneHubMusicClient: 'TuneHub',
|
||||||
|
MituMusicClient: '米兔音乐',
|
||||||
|
GequbaoMusicClient: '歌曲宝',
|
||||||
|
GequhaiMusicClient: '歌曲海',
|
||||||
|
KkwsMusicClient: '开开无损',
|
||||||
|
LivePOOMusicClient: '力音',
|
||||||
|
LiziYYMusicClient: '梨子音乐',
|
||||||
|
MGMP3MusicClient: '木瓜音乐',
|
||||||
|
SgogoMusicClient: '搜歌网',
|
||||||
|
TwoT58MusicClient: '爱听音乐',
|
||||||
|
XiagebaMusicClient: '下歌吧',
|
||||||
|
YinyuedaoMusicClient: '音乐岛',
|
||||||
|
ZhuolinMusicClient: '音乐解析',
|
||||||
|
FiveSongMusicClient: '5Song',
|
||||||
|
HTQYYMusicClient: '好听轻音乐',
|
||||||
|
ITingWaMusicClient: '听蛙纯音乐',
|
||||||
|
XimalayaMusicClient: '喜马拉雅',
|
||||||
|
QingtingMusicClient: '蜻蜓FM',
|
||||||
|
LizhiMusicClient: '荔枝FM',
|
||||||
|
LRTSMusicClient: '懒人听书',
|
||||||
|
AppleMusicClient: '苹果音乐',
|
||||||
|
ITunesMusicClient: '苹果播客',
|
||||||
|
DeezerMusicClient: 'Deezer',
|
||||||
|
QobuzMusicClient: 'Qobuz',
|
||||||
|
TIDALMusicClient: 'TIDAL',
|
||||||
|
SpotifyMusicClient: 'Spotify',
|
||||||
|
SoundCloudMusicClient: 'SoundCloud',
|
||||||
|
YouTubeMusicClient: '油管音乐',
|
||||||
|
SunoMusicClient: 'Suno',
|
||||||
|
MOOVMusicClient: '摩音符',
|
||||||
|
JamendoMusicClient: '简音乐',
|
||||||
|
FMAMusicClient: 'FMA',
|
||||||
|
JioSaavnMusicClient: 'JioSaavn',
|
||||||
|
OpenGameArtMusicClient: '开源游戏素材',
|
||||||
|
WikimediaCommonsMusicClient: '维基共享',
|
||||||
|
AudiusMusicClient: 'Audius',
|
||||||
|
CCMixterMusicClient: 'ccMixter'
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sourceName(code: string): string {
|
||||||
|
return SOURCE_NAMES[code] ?? code.replace(/MusicClient$/, '')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 搜索页/设置页展示的常用源(中文平台为主,与已注册源求交后展示) */
|
||||||
|
export const PICKER_SOURCES: string[] = [
|
||||||
|
'NeteaseMusicClient',
|
||||||
|
'QQMusicClient',
|
||||||
|
'KugouMusicClient',
|
||||||
|
'KuwoMusicClient',
|
||||||
|
'MiguMusicClient',
|
||||||
|
'QianqianMusicClient',
|
||||||
|
'BilibiliMusicClient',
|
||||||
|
'SodaMusicClient',
|
||||||
|
'StreetVoiceMusicClient',
|
||||||
|
'FiveSingMusicClient',
|
||||||
|
'BodianMusicClient',
|
||||||
|
'MyFreeMP3MusicClient',
|
||||||
|
'XiaoBaiMusicClient',
|
||||||
|
'JBSouMusicClient',
|
||||||
|
'TuneHubMusicClient'
|
||||||
|
]
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
|
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
|
||||||
import type { Component } from 'vue'
|
|
||||||
import { getCurrentWindow, currentMonitor } from '@tauri-apps/api/window'
|
import { getCurrentWindow, currentMonitor } from '@tauri-apps/api/window'
|
||||||
import { LogicalSize } from '@tauri-apps/api/dpi'
|
import { LogicalSize } from '@tauri-apps/api/dpi'
|
||||||
import { emit, listen, type UnlistenFn } from '@tauri-apps/api/event'
|
import { emit, listen, type UnlistenFn } from '@tauri-apps/api/event'
|
||||||
@@ -11,7 +10,6 @@ import { commands } from '@/lib/bindings'
|
|||||||
import { save } from '@tauri-apps/plugin-dialog'
|
import { save } from '@tauri-apps/plugin-dialog'
|
||||||
import { toast } from 'vue-sonner'
|
import { toast } from 'vue-sonner'
|
||||||
import {
|
import {
|
||||||
Square, Circle, MoveUpRight, ListOrdered, Pencil, Type, Grid3x3, Highlighter,
|
|
||||||
Eraser, Undo2, Redo2, Trash2, Copy, Save, X, Image as ImageIcon,
|
Eraser, Undo2, Redo2, Trash2, Copy, Save, X, Image as ImageIcon,
|
||||||
} from '@lucide/vue'
|
} from '@lucide/vue'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
@@ -20,43 +18,21 @@ import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover
|
|||||||
import { Slider } from '@/components/ui/slider'
|
import { Slider } from '@/components/ui/slider'
|
||||||
import { ScrollBar } from '@/components/ui/scroll-area'
|
import { ScrollBar } from '@/components/ui/scroll-area'
|
||||||
import { ScrollAreaCorner, ScrollAreaRoot, ScrollAreaViewport } from 'reka-ui'
|
import { ScrollAreaCorner, ScrollAreaRoot, ScrollAreaViewport } from 'reka-ui'
|
||||||
import { TOOL_KEYS, type CaptureData } from './types'
|
import {
|
||||||
|
TOOLS, TOOL_KEYS, COLORS, BLOCK_SIZES, ALPHAS, HANDLES,
|
||||||
|
type ToolType, type Annotation, type DrawableAnnotation, type Point,
|
||||||
|
type RectAnno, type EllipseAnno, type ArrowAnno, type PenAnno, type TextAnno,
|
||||||
|
type MosaicAnno, type HighlightAnno, type NumberAnno, type HandleDir,
|
||||||
|
type CaptureData,
|
||||||
|
} from './types'
|
||||||
|
import {
|
||||||
|
annoHasColor, annoHasLineWidth, annoBBox, hitTestAnno, hitTestTextZone,
|
||||||
|
isAnnoResizable, cloneAnno, applyMove, applyResize, drawSelectionBox,
|
||||||
|
} from './annotations'
|
||||||
|
|
||||||
// ===== 标注数据结构 =====
|
// ===== 标注类型(types.ts 共享,与覆盖层一致) =====
|
||||||
type ToolType = 'rect' | 'ellipse' | 'arrow' | 'number' | 'pen' | 'text' | 'mosaic' | 'highlight'
|
|
||||||
|
|
||||||
interface Point { x: number; y: number }
|
// ===== 工具与选项(types.ts 共享 TOOLS/COLORS 等,与普通截图编辑栏一致) =====
|
||||||
|
|
||||||
interface RectAnno { type: 'rect'; x1: number; y1: number; x2: number; y2: number; color: string; lineWidth: number }
|
|
||||||
interface EllipseAnno { type: 'ellipse'; x1: number; y1: number; x2: number; y2: number; color: string; lineWidth: number }
|
|
||||||
interface ArrowAnno { type: 'arrow'; x1: number; y1: number; x2: number; y2: number; color: string; lineWidth: number }
|
|
||||||
interface NumberAnno { type: 'number'; x: number; y: number; n: number; color: string; fontSize: number }
|
|
||||||
interface PenAnno { type: 'pen'; points: Point[]; color: string; lineWidth: number }
|
|
||||||
interface TextAnno { type: 'text'; x: number; y: number; text: string; color: string; fontSize: number }
|
|
||||||
interface MosaicAnno { type: 'mosaic'; x1: number; y1: number; x2: number; y2: number; blockSize: number }
|
|
||||||
interface HighlightAnno { type: 'highlight'; x1: number; y1: number; x2: number; y2: number; color: string; alpha: number }
|
|
||||||
|
|
||||||
type Annotation = RectAnno | EllipseAnno | ArrowAnno | NumberAnno | PenAnno | TextAnno | MosaicAnno | HighlightAnno
|
|
||||||
|
|
||||||
/** 可拖拽绘制的标注(不含文字/序号,文字与序号通过点击放置) */
|
|
||||||
type DrawableAnnotation = RectAnno | EllipseAnno | ArrowAnno | PenAnno | MosaicAnno | HighlightAnno
|
|
||||||
|
|
||||||
// ===== 工具与选项(与普通截图编辑栏一致) =====
|
|
||||||
const TOOLS: { value: ToolType; icon: Component; label: string }[] = [
|
|
||||||
{ value: 'rect', icon: Square, label: '矩形' },
|
|
||||||
{ value: 'ellipse', icon: Circle, label: '椭圆' },
|
|
||||||
{ value: 'arrow', icon: MoveUpRight, label: '箭头' },
|
|
||||||
{ value: 'number', icon: ListOrdered, label: '序号' },
|
|
||||||
{ value: 'pen', icon: Pencil, label: '画笔' },
|
|
||||||
{ value: 'text', icon: Type, label: '文字' },
|
|
||||||
{ value: 'mosaic', icon: Grid3x3, label: '马赛克' },
|
|
||||||
{ value: 'highlight', icon: Highlighter, label: '高亮' },
|
|
||||||
]
|
|
||||||
|
|
||||||
/** 与普通截图一致的颜色预设 */
|
|
||||||
const COLORS = ['#ef4444', '#f97316', '#eab308', '#22c55e', '#3b82f6', '#a855f7', '#000000', '#ffffff'] as const
|
|
||||||
const BLOCK_SIZES = [8, 10, 14] as const
|
|
||||||
const ALPHAS = [0.2, 0.4, 0.6] as const
|
|
||||||
|
|
||||||
// ===== 状态 =====
|
// ===== 状态 =====
|
||||||
const canvasRef = ref<HTMLCanvasElement | null>(null)
|
const canvasRef = ref<HTMLCanvasElement | null>(null)
|
||||||
@@ -89,6 +65,19 @@ let loadUnlisten: UnlistenFn | null = null
|
|||||||
/** 马赛克结果缓存:标注参数不变时跳过重复像素化(长图上拖动其他标注不再卡顿) */
|
/** 马赛克结果缓存:标注参数不变时跳过重复像素化(长图上拖动其他标注不再卡顿) */
|
||||||
let mosaicCache: { key: string; canvas: HTMLCanvasElement } | null = null
|
let mosaicCache: { key: string; canvas: HTMLCanvasElement } | null = null
|
||||||
|
|
||||||
|
/** Canvas 分层:静态层缓存底图 + 已提交标注,动态层只画 draft + 选中框 + 裁剪遮罩。
|
||||||
|
* 拖拽/调整标注时每帧只需 drawImage(静态层) + 少量动态元素,长图(数万像素高)不卡顿。 */
|
||||||
|
let staticCanvas: HTMLCanvasElement | null = null
|
||||||
|
let staticDirty = true
|
||||||
|
|
||||||
|
// 标注选中 / 拖拽 / 调整大小状态(与覆盖层一致)
|
||||||
|
const selectedAnnoIdx = ref(-1)
|
||||||
|
const draggingAnno = ref(false)
|
||||||
|
const resizingAnno = ref(false)
|
||||||
|
const annoResizeDir = ref<HandleDir | null>(null)
|
||||||
|
const annoDragStart = ref<{ p: Point; orig: Annotation } | null>(null)
|
||||||
|
const annoResizeStart = ref<{ p: Point; orig: Annotation } | null>(null)
|
||||||
|
|
||||||
// ===== 上下边界裁剪(长图场景,如滚动截图) =====
|
// ===== 上下边界裁剪(长图场景,如滚动截图) =====
|
||||||
/** 保留区上边界(像素,相对图片顶部) */
|
/** 保留区上边界(像素,相对图片顶部) */
|
||||||
const trimTop = ref(0)
|
const trimTop = ref(0)
|
||||||
@@ -97,32 +86,157 @@ const trimBottom = ref(0)
|
|||||||
/** 正在拖动的裁剪手柄 */
|
/** 正在拖动的裁剪手柄 */
|
||||||
const trimming = ref<'top' | 'bottom' | null>(null)
|
const trimming = ref<'top' | 'bottom' | null>(null)
|
||||||
|
|
||||||
// 文字输入浮层
|
// 文字输入浮层(textarea 支持多行)
|
||||||
const textInputPos = ref<Point | null>(null)
|
const textInputPos = ref<Point | null>(null)
|
||||||
const textInputValue = ref('')
|
const textInputValue = ref('')
|
||||||
const textInputEl = ref<HTMLInputElement | null>(null)
|
const textInputEl = ref<HTMLTextAreaElement | null>(null)
|
||||||
|
/** 编辑已有文字标注时的索引(-1 = 新建) */
|
||||||
|
const editingTextAnnoIdx = ref(-1)
|
||||||
|
|
||||||
const fontSizePx = computed(() => currentLineWidth.value * 3 + 14)
|
const fontSizePx = computed(() => currentLineWidth.value * 3 + 14)
|
||||||
const canUndo = computed(() => annotations.value.length > 0)
|
const canUndo = computed(() => annotations.value.length > 0)
|
||||||
const canRedo = computed(() => redoStack.value.length > 0)
|
const canRedo = computed(() => redoStack.value.length > 0)
|
||||||
|
|
||||||
// ===== 画布重绘 =====
|
/** 颜色控件:双用途——选中标注时反映并修改其颜色,否则设置新标注默认色 */
|
||||||
|
const effectiveColor = computed<string>({
|
||||||
|
get() {
|
||||||
|
const i = selectedAnnoIdx.value
|
||||||
|
if (i >= 0 && i < annotations.value.length) {
|
||||||
|
const a = annotations.value[i]
|
||||||
|
if (annoHasColor(a)) return (a as { color: string }).color
|
||||||
|
}
|
||||||
|
return currentColor.value
|
||||||
|
},
|
||||||
|
set(v: string) {
|
||||||
|
currentColor.value = v
|
||||||
|
const i = selectedAnnoIdx.value
|
||||||
|
if (i >= 0 && i < annotations.value.length) {
|
||||||
|
const a = annotations.value[i]
|
||||||
|
if (annoHasColor(a)) {
|
||||||
|
(a as { color: string }).color = v
|
||||||
|
markDirtyRedraw()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
/** 粗细控件:双用途——选中标注时反映并修改其 lineWidth,否则设置新标注默认粗细 */
|
||||||
|
const effectiveLineWidth = computed<number>({
|
||||||
|
get() {
|
||||||
|
const i = selectedAnnoIdx.value
|
||||||
|
if (i >= 0 && i < annotations.value.length) {
|
||||||
|
const a = annotations.value[i]
|
||||||
|
if (annoHasLineWidth(a)) return (a as { lineWidth: number }).lineWidth
|
||||||
|
}
|
||||||
|
return currentLineWidth.value
|
||||||
|
},
|
||||||
|
set(v: number) {
|
||||||
|
currentLineWidth.value = v
|
||||||
|
const i = selectedAnnoIdx.value
|
||||||
|
if (i >= 0 && i < annotations.value.length) {
|
||||||
|
const a = annotations.value[i]
|
||||||
|
if (annoHasLineWidth(a)) {
|
||||||
|
(a as { lineWidth: number }).lineWidth = v
|
||||||
|
markDirtyRedraw()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
/** 控件是否可用(颜色/粗细),选中不支持该属性的标注时禁用 */
|
||||||
|
const colorEnabled = computed(() => {
|
||||||
|
const i = selectedAnnoIdx.value
|
||||||
|
if (i < 0 || i >= annotations.value.length) return true
|
||||||
|
return annoHasColor(annotations.value[i])
|
||||||
|
})
|
||||||
|
const lineWidthEnabled = computed(() => {
|
||||||
|
const i = selectedAnnoIdx.value
|
||||||
|
if (i < 0 || i >= annotations.value.length) return true
|
||||||
|
return annoHasLineWidth(annotations.value[i])
|
||||||
|
})
|
||||||
|
/** 选中标注的 bounding box(画布 1:1 物理坐标,用于手柄定位) */
|
||||||
|
const selectedAnnoBBox = computed(() => {
|
||||||
|
const i = selectedAnnoIdx.value
|
||||||
|
if (i < 0 || i >= annotations.value.length) return null
|
||||||
|
return annoBBox(annotations.value[i])
|
||||||
|
})
|
||||||
|
/** 选中标注是否可调整大小(pen/text/number 仅支持移动) */
|
||||||
|
const selectedAnnoResizable = computed(() => {
|
||||||
|
const i = selectedAnnoIdx.value
|
||||||
|
if (i < 0 || i >= annotations.value.length) return false
|
||||||
|
return isAnnoResizable(annotations.value[i])
|
||||||
|
})
|
||||||
|
/** 文字输入浮层样式(编辑已有文字时用原标注颜色和字号) */
|
||||||
|
const textInputStyle = computed(() => {
|
||||||
|
const p = textInputPos.value
|
||||||
|
if (!p) return {}
|
||||||
|
const ei = editingTextAnnoIdx.value
|
||||||
|
const anno = ei >= 0 ? annotations.value[ei] : null
|
||||||
|
const color = anno && anno.type === 'text' ? anno.color : currentColor.value
|
||||||
|
const fs = anno && anno.type === 'text' ? anno.fontSize : fontSizePx.value
|
||||||
|
return {
|
||||||
|
left: p.x + 'px',
|
||||||
|
top: p.y + 'px',
|
||||||
|
color,
|
||||||
|
fontSize: fs + 'px',
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// ===== 画布重绘(静态层 + 动态层) =====
|
||||||
|
/** rAF 节流重绘:鼠标移动事件频率远高于 60fps,合并到下一帧统一重绘 */
|
||||||
|
let redrawRaf = 0
|
||||||
|
function scheduleRedraw() {
|
||||||
|
if (!redrawRaf) {
|
||||||
|
redrawRaf = requestAnimationFrame(() => {
|
||||||
|
redrawRaf = 0
|
||||||
|
redraw()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 标记静态层脏 + rAF 节流重绘(annotations 增删/修改后调用) */
|
||||||
|
function markDirtyRedraw() {
|
||||||
|
staticDirty = true
|
||||||
|
scheduleRedraw()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 重绘静态层(底图 + 已提交标注缓存)。annotations 增删/修改时标记脏。 */
|
||||||
|
function redrawStatic() {
|
||||||
|
const img = baseImage.value
|
||||||
|
if (!img) return
|
||||||
|
const canvas = canvasRef.value
|
||||||
|
if (!canvas) return
|
||||||
|
if (!staticCanvas) staticCanvas = document.createElement('canvas')
|
||||||
|
if (staticCanvas.width !== canvas.width || staticCanvas.height !== canvas.height) {
|
||||||
|
staticCanvas.width = canvas.width
|
||||||
|
staticCanvas.height = canvas.height
|
||||||
|
}
|
||||||
|
const sctx = staticCanvas.getContext('2d')
|
||||||
|
if (!sctx) return
|
||||||
|
sctx.clearRect(0, 0, staticCanvas.width, staticCanvas.height)
|
||||||
|
// 底图画在静态层:拖动标注时底图零成本复用
|
||||||
|
sctx.drawImage(img, 0, 0)
|
||||||
|
for (let i = 0; i < annotations.value.length; i++) {
|
||||||
|
// 正在编辑的文字标注由 textarea 显示,跳过绘制避免重影
|
||||||
|
if (i === editingTextAnnoIdx.value) continue
|
||||||
|
drawAnnotation(sctx, annotations.value[i])
|
||||||
|
}
|
||||||
|
staticDirty = false
|
||||||
|
}
|
||||||
|
|
||||||
function redraw() {
|
function redraw() {
|
||||||
const canvas = canvasRef.value
|
const canvas = canvasRef.value
|
||||||
const img = baseImage.value
|
const img = baseImage.value
|
||||||
if (!canvas || !img) return
|
if (!canvas || !img) return
|
||||||
const ctx = canvas.getContext('2d')
|
const ctx = canvas.getContext('2d')
|
||||||
if (!ctx) return
|
if (!ctx) return
|
||||||
|
if (staticDirty) redrawStatic()
|
||||||
ctx.clearRect(0, 0, canvas.width, canvas.height)
|
ctx.clearRect(0, 0, canvas.width, canvas.height)
|
||||||
// 白色背景填充透明区
|
// 白色背景填充透明区
|
||||||
ctx.fillStyle = '#ffffff'
|
ctx.fillStyle = '#ffffff'
|
||||||
ctx.fillRect(0, 0, canvas.width, canvas.height)
|
ctx.fillRect(0, 0, canvas.width, canvas.height)
|
||||||
// 底图
|
// 静态层合成(O(1) drawImage,跳过遍历所有标注)
|
||||||
ctx.drawImage(img, 0, 0)
|
if (staticCanvas) ctx.drawImage(staticCanvas, 0, 0)
|
||||||
// 已提交标注
|
|
||||||
for (const anno of annotations.value) {
|
|
||||||
drawAnnotation(ctx, anno)
|
|
||||||
}
|
|
||||||
// 进行中的草稿
|
// 进行中的草稿
|
||||||
if (draft.value) {
|
if (draft.value) {
|
||||||
if (draft.value.type === 'mosaic') {
|
if (draft.value.type === 'mosaic') {
|
||||||
@@ -139,6 +253,11 @@ function redraw() {
|
|||||||
if (top > 0) ctx.fillRect(0, 0, canvas.width, top)
|
if (top > 0) ctx.fillRect(0, 0, canvas.width, top)
|
||||||
if (bottom < canvas.height) ctx.fillRect(0, bottom, canvas.width, canvas.height - bottom)
|
if (bottom < canvas.height) ctx.fillRect(0, bottom, canvas.width, canvas.height - bottom)
|
||||||
}
|
}
|
||||||
|
// 选中标注:绘制虚线边框(手柄用 CSS DOM 定位,便于点击)
|
||||||
|
const si = selectedAnnoIdx.value
|
||||||
|
if (si >= 0 && si < annotations.value.length) {
|
||||||
|
drawSelectionBox(ctx, annoBBox(annotations.value[si]))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function drawAnnotation(ctx: CanvasRenderingContext2D, anno: Annotation) {
|
function drawAnnotation(ctx: CanvasRenderingContext2D, anno: Annotation) {
|
||||||
@@ -230,7 +349,10 @@ function drawText(ctx: CanvasRenderingContext2D, a: TextAnno) {
|
|||||||
ctx.font = `${a.fontSize}px sans-serif`
|
ctx.font = `${a.fontSize}px sans-serif`
|
||||||
ctx.fillStyle = a.color
|
ctx.fillStyle = a.color
|
||||||
ctx.textBaseline = 'top'
|
ctx.textBaseline = 'top'
|
||||||
ctx.fillText(a.text, a.x, a.y)
|
const lines = a.text.split('\n')
|
||||||
|
lines.forEach((line, i) => {
|
||||||
|
ctx.fillText(line, a.x, a.y + i * a.fontSize)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
function drawHighlight(ctx: CanvasRenderingContext2D, a: HighlightAnno) {
|
function drawHighlight(ctx: CanvasRenderingContext2D, a: HighlightAnno) {
|
||||||
@@ -240,36 +362,54 @@ function drawHighlight(ctx: CanvasRenderingContext2D, a: HighlightAnno) {
|
|||||||
ctx.globalAlpha = 1
|
ctx.globalAlpha = 1
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 对区域做像素化(马赛克):取块平均色填回。
|
/** 马赛克 tmp 画布(复用,避免拖拽中反复创建) */
|
||||||
* 缓存:同一标注参数(位置/尺寸/块大小)重复 redraw 时直接 drawImage 复用,
|
let mosaicTmp: HTMLCanvasElement | null = null
|
||||||
* 避免长图上每次重绘都重新 getImageData + 像素化。 */
|
function getMosaicTmp(): HTMLCanvasElement {
|
||||||
|
if (!mosaicTmp) mosaicTmp = document.createElement('canvas')
|
||||||
|
return mosaicTmp
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 马赛克:从**底图**取区域像素做块平均(与覆盖层一致)。
|
||||||
|
* 从底图而非画布取:画布上已绘制的其他标注不会被二次像素化;
|
||||||
|
* 且缓存命中时拖动其他标注零像素化开销(长图不卡顿)。
|
||||||
|
*/
|
||||||
function applyMosaic(ctx: CanvasRenderingContext2D, a: MosaicAnno) {
|
function applyMosaic(ctx: CanvasRenderingContext2D, a: MosaicAnno) {
|
||||||
const canvas = ctx.canvas
|
const img = baseImage.value
|
||||||
|
if (!img) return
|
||||||
const block = Math.max(1, a.blockSize)
|
const block = Math.max(1, a.blockSize)
|
||||||
const sx = Math.max(0, Math.floor(Math.min(a.x1, a.x2)))
|
const x1 = Math.min(a.x1, a.x2)
|
||||||
const sy = Math.max(0, Math.floor(Math.min(a.y1, a.y2)))
|
const y1 = Math.min(a.y1, a.y2)
|
||||||
const sw = Math.min(canvas.width - sx, Math.floor(Math.abs(a.x2 - a.x1)))
|
const w = Math.abs(a.x2 - a.x1)
|
||||||
const sh = Math.min(canvas.height - sy, Math.floor(Math.abs(a.y2 - a.y1)))
|
const h = Math.abs(a.y2 - a.y1)
|
||||||
if (sw <= 0 || sh <= 0) return
|
if (w < 1 || h < 1) return
|
||||||
const cacheKey = `${sx},${sy},${sw},${sh},${block}`
|
const cw = Math.min(Math.ceil(w), img.naturalWidth - Math.floor(x1))
|
||||||
|
const ch = Math.min(Math.ceil(h), img.naturalHeight - Math.floor(y1))
|
||||||
|
if (cw < 1 || ch < 1) return
|
||||||
|
const cacheKey = `${a.x1},${a.y1},${a.x2},${a.y2},${block}`
|
||||||
if (mosaicCache?.key === cacheKey) {
|
if (mosaicCache?.key === cacheKey) {
|
||||||
ctx.drawImage(mosaicCache.canvas, sx, sy)
|
ctx.drawImage(mosaicCache.canvas, Math.floor(x1), Math.floor(y1))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const imageData = ctx.getImageData(sx, sy, sw, sh)
|
const tmp = getMosaicTmp()
|
||||||
|
tmp.width = cw
|
||||||
|
tmp.height = ch
|
||||||
|
const tctx = tmp.getContext('2d')
|
||||||
|
if (!tctx) return
|
||||||
|
tctx.drawImage(img, Math.floor(x1), Math.floor(y1), cw, ch, 0, 0, cw, ch)
|
||||||
|
const imageData = tctx.getImageData(0, 0, cw, ch)
|
||||||
const data = imageData.data
|
const data = imageData.data
|
||||||
for (let by = 0; by < sh; by += block) {
|
for (let by = 0; by < ch; by += block) {
|
||||||
for (let bx = 0; bx < sw; bx += block) {
|
for (let bx = 0; bx < cw; bx += block) {
|
||||||
let r = 0, g = 0, b = 0, alpha = 0, count = 0
|
let r = 0, g = 0, b = 0, count = 0
|
||||||
const maxJ = Math.min(by + block, sh)
|
const maxJ = Math.min(by + block, ch)
|
||||||
const maxI = Math.min(bx + block, sw)
|
const maxI = Math.min(bx + block, cw)
|
||||||
for (let j = by; j < maxJ; j++) {
|
for (let j = by; j < maxJ; j++) {
|
||||||
for (let i = bx; i < maxI; i++) {
|
for (let i = bx; i < maxI; i++) {
|
||||||
const idx = (j * sw + i) * 4
|
const idx = (j * cw + i) * 4
|
||||||
r += data[idx]
|
r += data[idx]
|
||||||
g += data[idx + 1]
|
g += data[idx + 1]
|
||||||
b += data[idx + 2]
|
b += data[idx + 2]
|
||||||
alpha += data[idx + 3]
|
|
||||||
count++
|
count++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -277,25 +417,25 @@ function applyMosaic(ctx: CanvasRenderingContext2D, a: MosaicAnno) {
|
|||||||
r = Math.round(r / count)
|
r = Math.round(r / count)
|
||||||
g = Math.round(g / count)
|
g = Math.round(g / count)
|
||||||
b = Math.round(b / count)
|
b = Math.round(b / count)
|
||||||
alpha = Math.round(alpha / count)
|
|
||||||
for (let j = by; j < maxJ; j++) {
|
for (let j = by; j < maxJ; j++) {
|
||||||
for (let i = bx; i < maxI; i++) {
|
for (let i = bx; i < maxI; i++) {
|
||||||
const idx = (j * sw + i) * 4
|
const idx = (j * cw + i) * 4
|
||||||
data[idx] = r
|
data[idx] = r
|
||||||
data[idx + 1] = g
|
data[idx + 1] = g
|
||||||
data[idx + 2] = b
|
data[idx + 2] = b
|
||||||
data[idx + 3] = alpha
|
data[idx + 3] = 255
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ctx.putImageData(imageData, sx, sy)
|
tctx.putImageData(imageData, 0, 0)
|
||||||
// 缓存像素化结果(undo/redo/清空/新图加载时失效)
|
// 缓存结果(undo/redo/清空/新图加载时失效)
|
||||||
const cached = document.createElement('canvas')
|
const cached = document.createElement('canvas')
|
||||||
cached.width = sw
|
cached.width = cw
|
||||||
cached.height = sh
|
cached.height = ch
|
||||||
cached.getContext('2d')?.putImageData(imageData, 0, 0)
|
cached.getContext('2d')?.drawImage(tmp, 0, 0)
|
||||||
mosaicCache = { key: cacheKey, canvas: cached }
|
mosaicCache = { key: cacheKey, canvas: cached }
|
||||||
|
ctx.drawImage(cached, Math.floor(x1), Math.floor(y1))
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 马赛克拖拽中的虚线框预览(避免每帧像素化开销) */
|
/** 马赛克拖拽中的虚线框预览(避免每帧像素化开销) */
|
||||||
@@ -307,23 +447,88 @@ function drawMosaicDraft(ctx: CanvasRenderingContext2D, a: MosaicAnno) {
|
|||||||
ctx.setLineDash([])
|
ctx.setLineDash([])
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===== 鼠标交互 =====
|
// ===== 鼠标交互(与覆盖层一致:选中 / 拖拽 / 调整大小 / 绘制) =====
|
||||||
function getPoint(e: MouseEvent): Point {
|
function getPoint(e: MouseEvent): Point {
|
||||||
const canvas = canvasRef.value!
|
const canvas = canvasRef.value!
|
||||||
const rect = canvas.getBoundingClientRect()
|
const rect = canvas.getBoundingClientRect()
|
||||||
const scaleX = canvas.width / rect.width
|
const scaleX = canvas.width / rect.width
|
||||||
const scaleY = canvas.height / rect.height
|
const scaleY = canvas.height / rect.height
|
||||||
return { x: (e.clientX - rect.left) * scaleX, y: (e.clientY - rect.top) * scaleY }
|
return {
|
||||||
|
x: Math.min(canvas.width, Math.max(0, (e.clientX - rect.left) * scaleX)),
|
||||||
|
y: Math.min(canvas.height, Math.max(0, (e.clientY - rect.top) * scaleY)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 标注手柄位置(画布 1:1,物理坐标 = CSS 偏移) */
|
||||||
|
function annoHandleStyle(dir: HandleDir) {
|
||||||
|
const bb = selectedAnnoBBox.value
|
||||||
|
if (!bb) return { display: 'none' }
|
||||||
|
let cx = 0
|
||||||
|
let cy = 0
|
||||||
|
switch (dir) {
|
||||||
|
case 'nw': cx = bb.x; cy = bb.y; break
|
||||||
|
case 'n': cx = bb.x + bb.w / 2; cy = bb.y; break
|
||||||
|
case 'ne': cx = bb.x + bb.w; cy = bb.y; break
|
||||||
|
case 'e': cx = bb.x + bb.w; cy = bb.y + bb.h / 2; break
|
||||||
|
case 'se': cx = bb.x + bb.w; cy = bb.y + bb.h; break
|
||||||
|
case 's': cx = bb.x + bb.w / 2; cy = bb.y + bb.h; break
|
||||||
|
case 'sw': cx = bb.x; cy = bb.y + bb.h; break
|
||||||
|
case 'w': cx = bb.x; cy = bb.y + bb.h / 2; break
|
||||||
|
}
|
||||||
|
return { left: cx + 'px', top: cy + 'px' }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 标注手柄按下:进入调整大小模式 */
|
||||||
|
function onAnnoHandleMouseDown(dir: HandleDir, e: MouseEvent) {
|
||||||
|
if (selectedAnnoIdx.value < 0) return
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
const p = getPoint(e)
|
||||||
|
const cur = annotations.value[selectedAnnoIdx.value]
|
||||||
|
if (!cur) return
|
||||||
|
resizingAnno.value = true
|
||||||
|
annoResizeDir.value = dir
|
||||||
|
annoResizeStart.value = { p: { ...p }, orig: cloneAnno(cur) }
|
||||||
}
|
}
|
||||||
|
|
||||||
function onMouseDown(e: MouseEvent) {
|
function onMouseDown(e: MouseEvent) {
|
||||||
if (!baseImage.value || !loaded.value) return
|
if (!baseImage.value || !loaded.value) return
|
||||||
const p = getPoint(e)
|
// 文字工具:阻止 mousedown 默认行为,防止浏览器抢占焦点导致 textarea 立即失焦
|
||||||
if (currentTool.value === 'text') {
|
if (currentTool.value === 'text') {
|
||||||
startTextInput(p)
|
e.preventDefault()
|
||||||
|
}
|
||||||
|
const p = getPoint(e)
|
||||||
|
// 点击已有标注 → 选中并进入拖拽模式
|
||||||
|
const idx = hitTestAnno(annotations.value, p)
|
||||||
|
if (idx >= 0) {
|
||||||
|
// 先提交未完成的文字输入(点击别处放置/选中时,旧输入框提交)
|
||||||
|
if (textInputPos.value) commitText()
|
||||||
|
// 文字工具 + 点击文字标注:内容区→编辑,边框区→移动
|
||||||
|
if (currentTool.value === 'text' && annotations.value[idx].type === 'text') {
|
||||||
|
const zone = hitTestTextZone(annotations.value[idx] as TextAnno, p)
|
||||||
|
if (zone === 'core') {
|
||||||
|
openTextInput(p, idx)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// 序号:点击即放置(自增),不进入拖拽
|
// border → 选中并拖拽(移动),继续往下走
|
||||||
|
}
|
||||||
|
selectedAnnoIdx.value = idx
|
||||||
|
draggingAnno.value = true
|
||||||
|
annoDragStart.value = { p: { ...p }, orig: cloneAnno(annotations.value[idx]) }
|
||||||
|
markDirtyRedraw()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// 点击空白处 → 取消选中,开始绘制新标注
|
||||||
|
selectedAnnoIdx.value = -1
|
||||||
|
beginDraft(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
function beginDraft(p: Point) {
|
||||||
|
if (currentTool.value === 'text') {
|
||||||
|
openTextInput(p)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// 序号:点击即放置(自增),不进入拖拽;放置后自动选中便于移动
|
||||||
if (currentTool.value === 'number') {
|
if (currentTool.value === 'number') {
|
||||||
annotations.value.push({
|
annotations.value.push({
|
||||||
type: 'number',
|
type: 'number',
|
||||||
@@ -335,45 +540,61 @@ function onMouseDown(e: MouseEvent) {
|
|||||||
})
|
})
|
||||||
numberSeq.value++
|
numberSeq.value++
|
||||||
redoStack.value = []
|
redoStack.value = []
|
||||||
redraw()
|
selectedAnnoIdx.value = annotations.value.length - 1
|
||||||
|
markDirtyRedraw()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
isDrawing.value = true
|
isDrawing.value = true
|
||||||
|
const color = currentColor.value
|
||||||
|
const lw = currentLineWidth.value
|
||||||
switch (currentTool.value) {
|
switch (currentTool.value) {
|
||||||
case 'rect':
|
case 'rect':
|
||||||
draft.value = { type: 'rect', x1: p.x, y1: p.y, x2: p.x, y2: p.y, color: currentColor.value, lineWidth: currentLineWidth.value }
|
draft.value = { type: 'rect', x1: p.x, y1: p.y, x2: p.x, y2: p.y, color, lineWidth: lw }
|
||||||
break
|
break
|
||||||
case 'ellipse':
|
case 'ellipse':
|
||||||
draft.value = { type: 'ellipse', x1: p.x, y1: p.y, x2: p.x, y2: p.y, color: currentColor.value, lineWidth: currentLineWidth.value }
|
draft.value = { type: 'ellipse', x1: p.x, y1: p.y, x2: p.x, y2: p.y, color, lineWidth: lw }
|
||||||
break
|
break
|
||||||
case 'arrow':
|
case 'arrow':
|
||||||
draft.value = { type: 'arrow', x1: p.x, y1: p.y, x2: p.x, y2: p.y, color: currentColor.value, lineWidth: currentLineWidth.value }
|
draft.value = { type: 'arrow', x1: p.x, y1: p.y, x2: p.x, y2: p.y, color, lineWidth: lw }
|
||||||
break
|
break
|
||||||
case 'pen':
|
case 'pen':
|
||||||
draft.value = { type: 'pen', points: [p], color: currentColor.value, lineWidth: currentLineWidth.value }
|
draft.value = { type: 'pen', points: [p], color, lineWidth: lw }
|
||||||
break
|
break
|
||||||
case 'mosaic':
|
case 'mosaic':
|
||||||
draft.value = { type: 'mosaic', x1: p.x, y1: p.y, x2: p.x, y2: p.y, blockSize: blockSize.value }
|
draft.value = { type: 'mosaic', x1: p.x, y1: p.y, x2: p.x, y2: p.y, blockSize: blockSize.value }
|
||||||
break
|
break
|
||||||
case 'highlight':
|
case 'highlight':
|
||||||
draft.value = { type: 'highlight', x1: p.x, y1: p.y, x2: p.x, y2: p.y, color: currentColor.value, alpha: highlightAlpha.value }
|
draft.value = { type: 'highlight', x1: p.x, y1: p.y, x2: p.x, y2: p.y, color, alpha: highlightAlpha.value }
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
redraw()
|
scheduleRedraw()
|
||||||
}
|
|
||||||
|
|
||||||
// ===== 画布重绘(rAF 节流) =====
|
|
||||||
/** 连续鼠标移动时每帧最多重绘一次,避免 mousemove 高频事件(每帧多次)触发多次全量重绘 */
|
|
||||||
let redrawRaf = 0
|
|
||||||
function scheduleRedraw() {
|
|
||||||
if (redrawRaf) return
|
|
||||||
redrawRaf = requestAnimationFrame(() => {
|
|
||||||
redrawRaf = 0
|
|
||||||
redraw()
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function onMouseMove(e: MouseEvent) {
|
function onMouseMove(e: MouseEvent) {
|
||||||
|
if (resizingAnno.value && annoResizeStart.value) {
|
||||||
|
// 调整选中标注大小
|
||||||
|
const p = getPoint(e)
|
||||||
|
const dx = p.x - annoResizeStart.value.p.x
|
||||||
|
const dy = p.y - annoResizeStart.value.p.y
|
||||||
|
const cur = annotations.value[selectedAnnoIdx.value]
|
||||||
|
if (cur && annoResizeDir.value) {
|
||||||
|
applyResize(cur, annoResizeStart.value.orig, annoResizeDir.value, dx, dy)
|
||||||
|
markDirtyRedraw()
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (draggingAnno.value && annoDragStart.value) {
|
||||||
|
// 移动选中标注
|
||||||
|
const p = getPoint(e)
|
||||||
|
const dx = p.x - annoDragStart.value.p.x
|
||||||
|
const dy = p.y - annoDragStart.value.p.y
|
||||||
|
const cur = annotations.value[selectedAnnoIdx.value]
|
||||||
|
if (cur) {
|
||||||
|
applyMove(cur, annoDragStart.value.orig, dx, dy)
|
||||||
|
markDirtyRedraw()
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
if (!isDrawing.value || !draft.value) return
|
if (!isDrawing.value || !draft.value) return
|
||||||
const p = getPoint(e)
|
const p = getPoint(e)
|
||||||
const d = draft.value
|
const d = draft.value
|
||||||
@@ -387,6 +608,19 @@ function onMouseMove(e: MouseEvent) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function onMouseUp() {
|
function onMouseUp() {
|
||||||
|
if (resizingAnno.value) {
|
||||||
|
// 调整大小结束
|
||||||
|
resizingAnno.value = false
|
||||||
|
annoResizeDir.value = null
|
||||||
|
annoResizeStart.value = null
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (draggingAnno.value) {
|
||||||
|
// 拖拽结束(点击未移动时保持选中)
|
||||||
|
draggingAnno.value = false
|
||||||
|
annoDragStart.value = null
|
||||||
|
return
|
||||||
|
}
|
||||||
if (!isDrawing.value || !draft.value) return
|
if (!isDrawing.value || !draft.value) return
|
||||||
const d = draft.value
|
const d = draft.value
|
||||||
// 过滤无效(空)标注
|
// 过滤无效(空)标注
|
||||||
@@ -399,10 +633,14 @@ function onMouseUp() {
|
|||||||
if (valid) {
|
if (valid) {
|
||||||
annotations.value.push(d)
|
annotations.value.push(d)
|
||||||
redoStack.value = []
|
redoStack.value = []
|
||||||
|
// 自动选中新创建的标注,便于立即调整位置和大小
|
||||||
|
selectedAnnoIdx.value = annotations.value.length - 1
|
||||||
|
} else {
|
||||||
|
selectedAnnoIdx.value = -1
|
||||||
}
|
}
|
||||||
draft.value = null
|
draft.value = null
|
||||||
isDrawing.value = false
|
isDrawing.value = false
|
||||||
redraw()
|
markDirtyRedraw()
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===== 上下边界裁剪拖拽 =====
|
// ===== 上下边界裁剪拖拽 =====
|
||||||
@@ -422,7 +660,7 @@ function onTrimMove(e: MouseEvent) {
|
|||||||
} else {
|
} else {
|
||||||
trimBottom.value = Math.max(trimTop.value + 10, Math.min(Math.round(p.y), h))
|
trimBottom.value = Math.max(trimTop.value + 10, Math.min(Math.round(p.y), h))
|
||||||
}
|
}
|
||||||
redraw()
|
scheduleRedraw()
|
||||||
}
|
}
|
||||||
|
|
||||||
function onTrimUp() {
|
function onTrimUp() {
|
||||||
@@ -431,11 +669,30 @@ function onTrimUp() {
|
|||||||
window.removeEventListener('mouseup', onTrimUp)
|
window.removeEventListener('mouseup', onTrimUp)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===== 文字输入 =====
|
// ===== 文字输入(textarea 多行,与覆盖层一致) =====
|
||||||
function startTextInput(p: Point) {
|
function openTextInput(p: Point, editIdx: number = -1) {
|
||||||
textInputPos.value = { x: p.x, y: p.y }
|
// 先提交当前未完成的文字(点击别处放置新文字时,旧输入框会失焦)
|
||||||
|
commitText()
|
||||||
|
if (editIdx >= 0 && editIdx < annotations.value.length) {
|
||||||
|
const anno = annotations.value[editIdx]
|
||||||
|
if (anno && anno.type === 'text') {
|
||||||
|
editingTextAnnoIdx.value = editIdx
|
||||||
|
textInputPos.value = { x: anno.x, y: anno.y }
|
||||||
|
textInputValue.value = anno.text
|
||||||
|
markDirtyRedraw() // 隐藏原文字,由 textarea 显示
|
||||||
|
nextTick(() => {
|
||||||
|
textInputEl.value?.focus()
|
||||||
|
autoResizeTextarea()
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
textInputPos.value = p
|
||||||
textInputValue.value = ''
|
textInputValue.value = ''
|
||||||
nextTick(() => textInputEl.value?.focus())
|
nextTick(() => {
|
||||||
|
textInputEl.value?.focus()
|
||||||
|
autoResizeTextarea()
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
function commitText() {
|
function commitText() {
|
||||||
@@ -444,6 +701,26 @@ function commitText() {
|
|||||||
textInputPos.value = null
|
textInputPos.value = null
|
||||||
const value = textInputValue.value.trim()
|
const value = textInputValue.value.trim()
|
||||||
textInputValue.value = ''
|
textInputValue.value = ''
|
||||||
|
const editIdx = editingTextAnnoIdx.value
|
||||||
|
editingTextAnnoIdx.value = -1
|
||||||
|
// 编辑已有文字标注
|
||||||
|
if (editIdx >= 0 && editIdx < annotations.value.length) {
|
||||||
|
const anno = annotations.value[editIdx]
|
||||||
|
if (anno && anno.type === 'text') {
|
||||||
|
if (value) {
|
||||||
|
anno.text = value
|
||||||
|
selectedAnnoIdx.value = editIdx
|
||||||
|
} else {
|
||||||
|
// 空文字 → 删除
|
||||||
|
annotations.value.splice(editIdx, 1)
|
||||||
|
selectedAnnoIdx.value = -1
|
||||||
|
redoStack.value = []
|
||||||
|
}
|
||||||
|
markDirtyRedraw()
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// 新建文字标注
|
||||||
if (value) {
|
if (value) {
|
||||||
annotations.value.push({
|
annotations.value.push({
|
||||||
type: 'text',
|
type: 'text',
|
||||||
@@ -454,13 +731,37 @@ function commitText() {
|
|||||||
fontSize: fontSizePx.value,
|
fontSize: fontSizePx.value,
|
||||||
})
|
})
|
||||||
redoStack.value = []
|
redoStack.value = []
|
||||||
redraw()
|
// 自动选中新创建的文字
|
||||||
|
selectedAnnoIdx.value = annotations.value.length - 1
|
||||||
|
markDirtyRedraw()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function cancelText() {
|
function cancelText() {
|
||||||
textInputPos.value = null
|
textInputPos.value = null
|
||||||
textInputValue.value = ''
|
textInputValue.value = ''
|
||||||
|
editingTextAnnoIdx.value = -1
|
||||||
|
markDirtyRedraw() // 恢复显示原文字标注
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 自动调整 textarea 高度以适应内容 */
|
||||||
|
function autoResizeTextarea() {
|
||||||
|
const el = textInputEl.value
|
||||||
|
if (!el) return
|
||||||
|
el.style.height = 'auto'
|
||||||
|
el.style.height = el.scrollHeight + 'px'
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 删除选中标注 =====
|
||||||
|
function deleteSelectedAnno() {
|
||||||
|
const i = selectedAnnoIdx.value
|
||||||
|
if (i < 0 || i >= annotations.value.length) return
|
||||||
|
const a = annotations.value[i]
|
||||||
|
if (a.type === 'number') numberSeq.value = Math.max(1, numberSeq.value - 1)
|
||||||
|
annotations.value.splice(i, 1)
|
||||||
|
selectedAnnoIdx.value = -1
|
||||||
|
redoStack.value = []
|
||||||
|
markDirtyRedraw()
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===== 撤销 / 重做 / 清空 =====
|
// ===== 撤销 / 重做 / 清空 =====
|
||||||
@@ -470,8 +771,10 @@ function undo() {
|
|||||||
redoStack.value.push(last)
|
redoStack.value.push(last)
|
||||||
// 撤销序号标注后回退序号,避免后续新增序号跳号
|
// 撤销序号标注后回退序号,避免后续新增序号跳号
|
||||||
if (last.type === 'number') numberSeq.value = Math.max(1, numberSeq.value - 1)
|
if (last.type === 'number') numberSeq.value = Math.max(1, numberSeq.value - 1)
|
||||||
|
// 撤销后选中可能失效,重置
|
||||||
|
if (selectedAnnoIdx.value >= annotations.value.length) selectedAnnoIdx.value = -1
|
||||||
mosaicCache = null
|
mosaicCache = null
|
||||||
redraw()
|
markDirtyRedraw()
|
||||||
}
|
}
|
||||||
|
|
||||||
function redo() {
|
function redo() {
|
||||||
@@ -479,16 +782,18 @@ function redo() {
|
|||||||
const a = redoStack.value.pop()!
|
const a = redoStack.value.pop()!
|
||||||
annotations.value.push(a)
|
annotations.value.push(a)
|
||||||
if (a.type === 'number') numberSeq.value = a.n + 1
|
if (a.type === 'number') numberSeq.value = a.n + 1
|
||||||
|
selectedAnnoIdx.value = -1
|
||||||
mosaicCache = null
|
mosaicCache = null
|
||||||
redraw()
|
markDirtyRedraw()
|
||||||
}
|
}
|
||||||
|
|
||||||
function clearAll() {
|
function clearAll() {
|
||||||
annotations.value = []
|
annotations.value = []
|
||||||
redoStack.value = []
|
redoStack.value = []
|
||||||
numberSeq.value = 1
|
numberSeq.value = 1
|
||||||
|
selectedAnnoIdx.value = -1
|
||||||
mosaicCache = null
|
mosaicCache = null
|
||||||
redraw()
|
markDirtyRedraw()
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===== 导出 =====
|
// ===== 导出 =====
|
||||||
@@ -589,7 +894,16 @@ async function closeWindow() {
|
|||||||
isDrawing.value = false
|
isDrawing.value = false
|
||||||
annotations.value = []
|
annotations.value = []
|
||||||
redoStack.value = []
|
redoStack.value = []
|
||||||
|
selectedAnnoIdx.value = -1
|
||||||
|
draggingAnno.value = false
|
||||||
|
resizingAnno.value = false
|
||||||
|
annoDragStart.value = null
|
||||||
|
annoResizeStart.value = null
|
||||||
|
editingTextAnnoIdx.value = -1
|
||||||
|
textInputPos.value = null
|
||||||
mosaicCache = null
|
mosaicCache = null
|
||||||
|
mosaicTmp = null
|
||||||
|
staticDirty = true
|
||||||
if (objectUrl) {
|
if (objectUrl) {
|
||||||
URL.revokeObjectURL(objectUrl)
|
URL.revokeObjectURL(objectUrl)
|
||||||
objectUrl = ''
|
objectUrl = ''
|
||||||
@@ -623,10 +937,10 @@ function onStorageChange(e: StorageEvent) {
|
|||||||
if (e.key === STORAGE_KEYS.appSettings) applyTheme()
|
if (e.key === STORAGE_KEYS.appSettings) applyTheme()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 自定义颜色选择:更新 customColor 并设为当前颜色 */
|
/** 自定义颜色选择:更新 customColor 并设为当前颜色/选中标注颜色 */
|
||||||
function onCustomColorPick(color: string) {
|
function onCustomColorPick(color: string) {
|
||||||
customColor.value = color
|
customColor.value = color
|
||||||
currentColor.value = color
|
effectiveColor.value = color
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -657,6 +971,17 @@ function onKeyDown(e: KeyboardEvent) {
|
|||||||
// 输入控件(文字标注 / 取色器 / 滑杆)聚焦时不响应快捷键
|
// 输入控件(文字标注 / 取色器 / 滑杆)聚焦时不响应快捷键
|
||||||
const t = e.target as HTMLElement | null
|
const t = e.target as HTMLElement | null
|
||||||
if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return
|
if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return
|
||||||
|
// 文字输入浮层激活时:Ctrl+Enter 提交,Esc 取消(普通 Enter 留给 textarea 换行)
|
||||||
|
if (textInputPos.value) {
|
||||||
|
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
|
||||||
|
e.preventDefault()
|
||||||
|
commitText()
|
||||||
|
} else if (e.key === 'Escape') {
|
||||||
|
e.stopPropagation()
|
||||||
|
cancelText()
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
const k = e.key.toLowerCase()
|
const k = e.key.toLowerCase()
|
||||||
const mod = e.ctrlKey || e.metaKey
|
const mod = e.ctrlKey || e.metaKey
|
||||||
if (mod && !e.shiftKey && k === 'z') {
|
if (mod && !e.shiftKey && k === 'z') {
|
||||||
@@ -679,6 +1004,12 @@ function onKeyDown(e: KeyboardEvent) {
|
|||||||
void saveToFile()
|
void saveToFile()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// Delete/Backspace 删除选中的标注
|
||||||
|
if ((e.key === 'Delete' || e.key === 'Backspace') && selectedAnnoIdx.value >= 0) {
|
||||||
|
e.preventDefault()
|
||||||
|
deleteSelectedAnno()
|
||||||
|
return
|
||||||
|
}
|
||||||
if (k === 'enter') {
|
if (k === 'enter') {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
void copyAndClose()
|
void copyAndClose()
|
||||||
@@ -686,7 +1017,13 @@ function onKeyDown(e: KeyboardEvent) {
|
|||||||
}
|
}
|
||||||
if (k === 'escape') {
|
if (k === 'escape') {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
|
// 选中状态下 Esc 先取消选中,再次按才关闭窗口(与覆盖层一致)
|
||||||
|
if (selectedAnnoIdx.value >= 0) {
|
||||||
|
selectedAnnoIdx.value = -1
|
||||||
|
markDirtyRedraw()
|
||||||
|
} else {
|
||||||
void closeWindow()
|
void closeWindow()
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (!mod && !e.altKey) {
|
if (!mod && !e.altKey) {
|
||||||
@@ -723,6 +1060,14 @@ async function loadPendingImage() {
|
|||||||
isDrawing.value = false
|
isDrawing.value = false
|
||||||
numberSeq.value = 1
|
numberSeq.value = 1
|
||||||
mosaicCache = null
|
mosaicCache = null
|
||||||
|
staticDirty = true
|
||||||
|
selectedAnnoIdx.value = -1
|
||||||
|
draggingAnno.value = false
|
||||||
|
resizingAnno.value = false
|
||||||
|
annoDragStart.value = null
|
||||||
|
annoResizeStart.value = null
|
||||||
|
editingTextAnnoIdx.value = -1
|
||||||
|
textInputPos.value = null
|
||||||
loadError.value = false
|
loadError.value = false
|
||||||
trimTop.value = 0
|
trimTop.value = 0
|
||||||
trimBottom.value = img.naturalHeight
|
trimBottom.value = img.naturalHeight
|
||||||
@@ -825,13 +1170,15 @@ onUnmounted(() => {
|
|||||||
|
|
||||||
<div class="h-6 w-px bg-border" />
|
<div class="h-6 w-px bg-border" />
|
||||||
|
|
||||||
<!-- 颜色:当前色 badge + 弹层(自定义取色 + 默认色板),与普通截图一致 -->
|
<!-- 颜色:当前色 badge + 弹层(双用途:选中标注时修改其颜色),与普通截图一致 -->
|
||||||
<Popover v-model:open="colorPickerOpen">
|
<Popover v-model:open="colorPickerOpen">
|
||||||
<PopoverTrigger as-child>
|
<PopoverTrigger as-child>
|
||||||
<button
|
<button
|
||||||
class="color-badge"
|
class="color-badge"
|
||||||
:style="{ '--swatch-color': currentColor }"
|
:class="{ disabled: !colorEnabled }"
|
||||||
:aria-label="'当前颜色 ' + currentColor"
|
:style="{ '--swatch-color': effectiveColor }"
|
||||||
|
:aria-label="'当前颜色 ' + effectiveColor"
|
||||||
|
:disabled="!colorEnabled"
|
||||||
/>
|
/>
|
||||||
</PopoverTrigger>
|
</PopoverTrigger>
|
||||||
<PopoverContent class="w-auto p-3" align="start">
|
<PopoverContent class="w-auto p-3" align="start">
|
||||||
@@ -847,9 +1194,9 @@ onUnmounted(() => {
|
|||||||
<TooltipTrigger as-child>
|
<TooltipTrigger as-child>
|
||||||
<button
|
<button
|
||||||
class="color-swatch-mini"
|
class="color-swatch-mini"
|
||||||
:class="{ active: currentColor === c }"
|
:class="{ active: effectiveColor === c }"
|
||||||
:style="{ backgroundColor: c }"
|
:style="{ backgroundColor: c }"
|
||||||
@click="currentColor = c"
|
@click="effectiveColor = c"
|
||||||
/>
|
/>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
<TooltipContent>{{ c }}</TooltipContent>
|
<TooltipContent>{{ c }}</TooltipContent>
|
||||||
@@ -859,24 +1206,25 @@ onUnmounted(() => {
|
|||||||
</PopoverContent>
|
</PopoverContent>
|
||||||
</Popover>
|
</Popover>
|
||||||
|
|
||||||
<!-- 粗细 badge + 弹层(Slider),与普通截图一致 -->
|
<!-- 粗细 badge + 弹层(双用途:选中标注时修改其粗细),与普通截图一致 -->
|
||||||
<Popover v-model:open="widthPickerOpen">
|
<Popover v-model:open="widthPickerOpen">
|
||||||
<PopoverTrigger as-child>
|
<PopoverTrigger as-child>
|
||||||
<button class="width-badge">{{ currentLineWidth }}</button>
|
<button class="width-badge" :class="{ disabled: !lineWidthEnabled }" :disabled="!lineWidthEnabled">{{ effectiveLineWidth }}</button>
|
||||||
</PopoverTrigger>
|
</PopoverTrigger>
|
||||||
<PopoverContent class="w-auto p-3" align="start">
|
<PopoverContent class="w-auto p-3" align="start">
|
||||||
<div class="width-popover">
|
<div class="width-popover">
|
||||||
<div class="width-popover-header">
|
<div class="width-popover-header">
|
||||||
<span>粗细</span>
|
<span>粗细</span>
|
||||||
<span class="width-popover-value">{{ currentLineWidth }}</span>
|
<span class="width-popover-value">{{ effectiveLineWidth }}</span>
|
||||||
</div>
|
</div>
|
||||||
<Slider
|
<Slider
|
||||||
:model-value="[currentLineWidth]"
|
:model-value="[effectiveLineWidth]"
|
||||||
:min="1"
|
:min="1"
|
||||||
:max="16"
|
:max="16"
|
||||||
:step="1"
|
:step="1"
|
||||||
|
:disabled="!lineWidthEnabled"
|
||||||
class="width-slider"
|
class="width-slider"
|
||||||
@update:model-value="(v: number[] | undefined) => { if (v && v.length) currentLineWidth = v[0] }"
|
@update:model-value="(v: number[] | undefined) => { if (v && v.length) effectiveLineWidth = v[0] }"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</PopoverContent>
|
</PopoverContent>
|
||||||
@@ -1009,7 +1357,7 @@ onUnmounted(() => {
|
|||||||
<canvas
|
<canvas
|
||||||
ref="canvasRef"
|
ref="canvasRef"
|
||||||
class="block max-w-none select-none"
|
class="block max-w-none select-none"
|
||||||
:style="{ cursor: currentTool === 'text' ? 'text' : 'crosshair' }"
|
:style="{ cursor: draggingAnno || resizingAnno ? 'move' : currentTool === 'text' ? 'text' : 'crosshair' }"
|
||||||
@mousedown="onMouseDown"
|
@mousedown="onMouseDown"
|
||||||
/>
|
/>
|
||||||
<!-- 上下边界裁剪手柄(拖动调整保留区,导出按此裁切) -->
|
<!-- 上下边界裁剪手柄(拖动调整保留区,导出按此裁切) -->
|
||||||
@@ -1027,25 +1375,31 @@ onUnmounted(() => {
|
|||||||
>
|
>
|
||||||
<span class="trim-grip">下 {{ Math.round(trimBottom) }}</span>
|
<span class="trim-grip">下 {{ Math.round(trimBottom) }}</span>
|
||||||
</div>
|
</div>
|
||||||
<input
|
<!-- 选中标注的调整手柄(画布 1:1,物理坐标直接定位;pen/text/number 仅移动不显示) -->
|
||||||
|
<template v-if="selectedAnnoIdx >= 0 && selectedAnnoResizable">
|
||||||
|
<div
|
||||||
|
v-for="dir in HANDLES"
|
||||||
|
:key="'anno-h-' + dir"
|
||||||
|
class="anno-handle"
|
||||||
|
:class="'handle-' + dir"
|
||||||
|
:style="annoHandleStyle(dir)"
|
||||||
|
@mousedown.stop.prevent="onAnnoHandleMouseDown(dir, $event)"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
<!-- 文字输入浮层:textarea 支持多行,Ctrl+Enter 提交 / Esc 取消 / blur 提交 -->
|
||||||
|
<textarea
|
||||||
v-if="textInputPos"
|
v-if="textInputPos"
|
||||||
|
id="screenshot-editor-text-input"
|
||||||
ref="textInputEl"
|
ref="textInputEl"
|
||||||
v-model="textInputValue"
|
v-model="textInputValue"
|
||||||
class="absolute z-10 bg-transparent outline-none"
|
class="absolute z-10 bg-transparent outline-none resize-none overflow-hidden"
|
||||||
:style="{
|
:style="textInputStyle"
|
||||||
left: textInputPos.x + 'px',
|
placeholder="输入文字 (Ctrl+Enter 完成)"
|
||||||
top: textInputPos.y + 'px',
|
rows="1"
|
||||||
color: currentColor,
|
@keydown.enter.ctrl.prevent="commitText"
|
||||||
fontSize: fontSizePx + 'px',
|
@keydown.esc.stop.prevent="cancelText"
|
||||||
fontFamily: 'sans-serif',
|
|
||||||
lineHeight: '1',
|
|
||||||
padding: '0 2px',
|
|
||||||
border: '1px dashed ' + currentColor,
|
|
||||||
}"
|
|
||||||
placeholder="输入文字"
|
|
||||||
@keydown.enter.prevent="commitText"
|
|
||||||
@keydown.esc.prevent="cancelText"
|
|
||||||
@blur="commitText"
|
@blur="commitText"
|
||||||
|
@input="autoResizeTextarea"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -1074,6 +1428,48 @@ onUnmounted(() => {
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
/* 文字输入浮层:textarea 多行(与覆盖层 .text-input 一致) */
|
||||||
|
#screenshot-editor-text-input {
|
||||||
|
position: absolute;
|
||||||
|
z-index: 10;
|
||||||
|
background: transparent;
|
||||||
|
outline: none;
|
||||||
|
border: 1px dashed currentColor;
|
||||||
|
font-family: sans-serif;
|
||||||
|
line-height: 1;
|
||||||
|
padding: 0 2px;
|
||||||
|
min-width: 20px;
|
||||||
|
resize: none;
|
||||||
|
overflow: hidden;
|
||||||
|
white-space: pre;
|
||||||
|
word-break: keep-all;
|
||||||
|
box-sizing: border-box;
|
||||||
|
height: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 标注调整手柄(与覆盖层 .handle 一致;画布 1:1,物理坐标直接定位) */
|
||||||
|
.anno-handle {
|
||||||
|
position: absolute;
|
||||||
|
width: 9px;
|
||||||
|
height: 9px;
|
||||||
|
background: #fff;
|
||||||
|
border: 2px solid #3b82f6;
|
||||||
|
border-radius: 2px;
|
||||||
|
transform: translate(-50%, -50%);
|
||||||
|
z-index: 15;
|
||||||
|
}
|
||||||
|
.handle-nw, .handle-se { cursor: nwse-resize; }
|
||||||
|
.handle-ne, .handle-sw { cursor: nesw-resize; }
|
||||||
|
.handle-n, .handle-s { cursor: ns-resize; }
|
||||||
|
.handle-e, .handle-w { cursor: ew-resize; }
|
||||||
|
|
||||||
|
/* badge 禁用态(选中不支持该属性的标注时) */
|
||||||
|
.color-badge.disabled, .width-badge.disabled {
|
||||||
|
opacity: 0.4;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
.color-badge.disabled:hover { transform: none; }
|
||||||
|
|
||||||
/* 上下边界裁剪手柄:跨画布宽度的可拖拽蓝线 + 居中数值标签 */
|
/* 上下边界裁剪手柄:跨画布宽度的可拖拽蓝线 + 居中数值标签 */
|
||||||
.trim-bar {
|
.trim-bar {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
|
|||||||
@@ -20,6 +20,10 @@ import {
|
|||||||
type MosaicAnno, type HighlightAnno, type NumberAnno,
|
type MosaicAnno, type HighlightAnno, type NumberAnno,
|
||||||
type ScreenshotBeginPayload,
|
type ScreenshotBeginPayload,
|
||||||
} from './types'
|
} from './types'
|
||||||
|
import {
|
||||||
|
annoHasColor, annoHasLineWidth, annoBBox, hitTestAnno, hitTestTextZone,
|
||||||
|
isAnnoResizable, cloneAnno, applyMove, applyResize, drawSelectionBox,
|
||||||
|
} from './annotations'
|
||||||
|
|
||||||
// ===== 窗口 / 底图 =====
|
// ===== 窗口 / 底图 =====
|
||||||
const win = getCurrentWindow()
|
const win = getCurrentWindow()
|
||||||
@@ -129,7 +133,6 @@ const resizingAnno = ref(false)
|
|||||||
const annoResizeDir = ref<HandleDir | null>(null)
|
const annoResizeDir = ref<HandleDir | null>(null)
|
||||||
const annoDragStart = ref<{ p: Point; orig: Annotation } | null>(null)
|
const annoDragStart = ref<{ p: Point; orig: Annotation } | null>(null)
|
||||||
const annoResizeStart = ref<{ p: Point; orig: Annotation } | null>(null)
|
const annoResizeStart = ref<{ p: Point; orig: Annotation } | null>(null)
|
||||||
let measureCtx: CanvasRenderingContext2D | null = null
|
|
||||||
|
|
||||||
/** Canvas 分层:静态层缓存已提交标注,动态层只画 draft + 选中框。
|
/** Canvas 分层:静态层缓存已提交标注,动态层只画 draft + 选中框。
|
||||||
* 绘制 draft(画笔/矩形等)时 annotations 不变,只需 drawImage(静态层) + draft,O(1) 合成。 */
|
* 绘制 draft(画笔/矩形等)时 annotations 不变,只需 drawImage(静态层) + draft,O(1) 合成。 */
|
||||||
@@ -208,18 +211,9 @@ const canUndo = computed(() => annotations.value.length > 0)
|
|||||||
const canRedo = computed(() => redoStack.value.length > 0)
|
const canRedo = computed(() => redoStack.value.length > 0)
|
||||||
const fontSizePx = computed(() => currentLineWidth.value * 3 + 14)
|
const fontSizePx = computed(() => currentLineWidth.value * 3 + 14)
|
||||||
|
|
||||||
/** 选中标注是否有可变颜色属性 */
|
/** 选中标注是否有可变颜色属性 / 粗细概念:见 annotations.ts 共享实现 */
|
||||||
function annoHasColor(a: Annotation): boolean {
|
|
||||||
return a.type !== 'mosaic'
|
|
||||||
}
|
|
||||||
/** 选中标注是否有粗细概念(lineWidth) */
|
|
||||||
function annoHasLineWidth(a: Annotation): boolean {
|
|
||||||
return a.type === 'rect' || a.type === 'ellipse' || a.type === 'arrow' || a.type === 'pen'
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/** 颜色控件:双用途——选中标注时反映并修改其颜色,否则设置新标注默认色 */
|
||||||
* 颜色控件:双用途——选中标注时反映并修改其颜色,否则设置新标注默认色
|
|
||||||
*/
|
|
||||||
const effectiveColor = computed<string>({
|
const effectiveColor = computed<string>({
|
||||||
get() {
|
get() {
|
||||||
const i = selectedAnnoIdx.value
|
const i = selectedAnnoIdx.value
|
||||||
@@ -819,7 +813,7 @@ function onRegionMouseDown(e: MouseEvent) {
|
|||||||
}
|
}
|
||||||
const p = canvasPoint(e)
|
const p = canvasPoint(e)
|
||||||
// 点击已有标注 → 选中并进入拖拽模式
|
// 点击已有标注 → 选中并进入拖拽模式
|
||||||
const idx = hitTestAnno(p)
|
const idx = hitTestAnno(annotations.value, p)
|
||||||
if (idx >= 0) {
|
if (idx >= 0) {
|
||||||
// 先提交未完成的文字输入(点击别处放置/选中时,旧输入框提交)
|
// 先提交未完成的文字输入(点击别处放置/选中时,旧输入框提交)
|
||||||
if (textInputPos.value) commitText()
|
if (textInputPos.value) commitText()
|
||||||
@@ -1333,220 +1327,8 @@ function drawMosaicDraft(ctx: CanvasRenderingContext2D, a: MosaicAnno) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ===== 标注选中 / 编辑 =====
|
// ===== 标注选中 / 编辑 =====
|
||||||
/** 获取文字测量用的 canvas 上下文(惰性创建一次复用) */
|
// 几何 / 命中 / 变换纯函数已抽到 annotations.ts,与编辑器共用,
|
||||||
function getMeasureCtx(): CanvasRenderingContext2D | null {
|
// 保证两处对同一标注数据的选中、拖拽、调整大小行为一致。
|
||||||
if (!measureCtx) {
|
|
||||||
const c = document.createElement('canvas')
|
|
||||||
measureCtx = c.getContext('2d')
|
|
||||||
}
|
|
||||||
return measureCtx
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 估算文字宽高(用 ctx.measureText 测宽,多行取最宽行,高 = 行数 × fontSize)
|
|
||||||
* 结果缓存:相同 text+fontSize 的测量结果不变,避免 hitTest / annoBBox 重复调用开销 */
|
|
||||||
const measureCache = new Map<string, { w: number; h: number }>()
|
|
||||||
function measureText(text: string, fontSize: number): { w: number; h: number } {
|
|
||||||
const key = `${fontSize}\0${text}`
|
|
||||||
const cached = measureCache.get(key)
|
|
||||||
if (cached) return cached
|
|
||||||
const ctx = getMeasureCtx()
|
|
||||||
const lines = text.split('\n')
|
|
||||||
let result: { w: number; h: number }
|
|
||||||
if (!ctx) {
|
|
||||||
const maxLen = Math.max(1, ...lines.map(l => l.length))
|
|
||||||
result = { w: fontSize * maxLen * 0.6, h: fontSize * lines.length }
|
|
||||||
} else {
|
|
||||||
ctx.font = `${fontSize}px sans-serif`
|
|
||||||
let maxW = 0
|
|
||||||
for (const line of lines) {
|
|
||||||
const m = ctx.measureText(line)
|
|
||||||
if (m.width > maxW) maxW = m.width
|
|
||||||
}
|
|
||||||
result = { w: Math.ceil(maxW), h: fontSize * lines.length }
|
|
||||||
}
|
|
||||||
measureCache.set(key, result)
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 标注 bounding box(物理像素坐标) */
|
|
||||||
function annoBBox(anno: Annotation): { x: number; y: number; w: number; h: number } {
|
|
||||||
switch (anno.type) {
|
|
||||||
case 'rect':
|
|
||||||
case 'ellipse':
|
|
||||||
case 'mosaic':
|
|
||||||
case 'highlight':
|
|
||||||
case 'arrow': {
|
|
||||||
const x = Math.min(anno.x1, anno.x2)
|
|
||||||
const y = Math.min(anno.y1, anno.y2)
|
|
||||||
return { x, y, w: Math.abs(anno.x2 - anno.x1), h: Math.abs(anno.y2 - anno.y1) }
|
|
||||||
}
|
|
||||||
case 'pen': {
|
|
||||||
if (anno.points.length === 0) return { x: 0, y: 0, w: 0, h: 0 }
|
|
||||||
let minX = Infinity
|
|
||||||
let minY = Infinity
|
|
||||||
let maxX = -Infinity
|
|
||||||
let maxY = -Infinity
|
|
||||||
for (const pt of anno.points) {
|
|
||||||
if (pt.x < minX) minX = pt.x
|
|
||||||
if (pt.y < minY) minY = pt.y
|
|
||||||
if (pt.x > maxX) maxX = pt.x
|
|
||||||
if (pt.y > maxY) maxY = pt.y
|
|
||||||
}
|
|
||||||
return { x: minX, y: minY, w: maxX - minX, h: maxY - minY }
|
|
||||||
}
|
|
||||||
case 'text': {
|
|
||||||
const { w, h } = measureText(anno.text, anno.fontSize)
|
|
||||||
return { x: anno.x, y: anno.y, w, h }
|
|
||||||
}
|
|
||||||
case 'number': {
|
|
||||||
const r = anno.fontSize / 2
|
|
||||||
return { x: anno.x - r, y: anno.y - r, w: anno.fontSize, h: anno.fontSize }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 点到线段的距离 */
|
|
||||||
function distToSegment(p: Point, a: Point, b: Point): number {
|
|
||||||
const dx = b.x - a.x
|
|
||||||
const dy = b.y - a.y
|
|
||||||
const len2 = dx * dx + dy * dy
|
|
||||||
if (len2 === 0) return Math.hypot(p.x - a.x, p.y - a.y)
|
|
||||||
let t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2
|
|
||||||
t = Math.max(0, Math.min(1, t))
|
|
||||||
const cx = a.x + t * dx
|
|
||||||
const cy = a.y + t * dy
|
|
||||||
return Math.hypot(p.x - cx, p.y - cy)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 文字标注区域检测:core=文字内容区(编辑),border=边框区(移动),null=未命中 */
|
|
||||||
function hitTestTextZone(anno: TextAnno, p: Point): 'core' | 'border' | null {
|
|
||||||
const { w, h } = measureText(anno.text, anno.fontSize)
|
|
||||||
const x1 = anno.x, y1 = anno.y
|
|
||||||
const x2 = anno.x + w, y2 = anno.y + h
|
|
||||||
const pad = 8
|
|
||||||
if (p.x < x1 - pad || p.x > x2 + pad || p.y < y1 - pad || p.y > y2 + pad) return null
|
|
||||||
if (p.x >= x1 && p.x <= x2 && p.y >= y1 && p.y <= y2) return 'core'
|
|
||||||
return 'border'
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 点击测试单个标注 */
|
|
||||||
function hitTestSingle(anno: Annotation, p: Point): boolean {
|
|
||||||
switch (anno.type) {
|
|
||||||
case 'rect':
|
|
||||||
case 'ellipse':
|
|
||||||
case 'mosaic':
|
|
||||||
case 'highlight': {
|
|
||||||
const x1 = Math.min(anno.x1, anno.x2)
|
|
||||||
const y1 = Math.min(anno.y1, anno.y2)
|
|
||||||
const x2 = Math.max(anno.x1, anno.x2)
|
|
||||||
const y2 = Math.max(anno.y1, anno.y2)
|
|
||||||
const pad = Math.max(4, anno.type === 'rect' || anno.type === 'ellipse' ? anno.lineWidth : 2)
|
|
||||||
return p.x >= x1 - pad && p.x <= x2 + pad && p.y >= y1 - pad && p.y <= y2 + pad
|
|
||||||
}
|
|
||||||
case 'arrow':
|
|
||||||
return distToSegment(p, { x: anno.x1, y: anno.y1 }, { x: anno.x2, y: anno.y2 }) <= Math.max(6, anno.lineWidth)
|
|
||||||
case 'pen': {
|
|
||||||
for (let i = 1; i < anno.points.length; i++) {
|
|
||||||
if (distToSegment(p, anno.points[i - 1], anno.points[i]) <= Math.max(6, anno.lineWidth)) return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
case 'text': {
|
|
||||||
return hitTestTextZone(anno, p) !== null
|
|
||||||
}
|
|
||||||
case 'number': {
|
|
||||||
const r = anno.fontSize / 2
|
|
||||||
const dx = p.x - anno.x
|
|
||||||
const dy = p.y - anno.y
|
|
||||||
return dx * dx + dy * dy <= r * r
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 点击测试:返回命中的标注索引(-1 未命中),从后往前测试(后画的在上层) */
|
|
||||||
function hitTestAnno(p: Point): number {
|
|
||||||
for (let i = annotations.value.length - 1; i >= 0; i--) {
|
|
||||||
if (hitTestSingle(annotations.value[i], p)) return i
|
|
||||||
}
|
|
||||||
return -1
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 标注是否可调整大小(pen/text/number 仅支持移动) */
|
|
||||||
function isAnnoResizable(anno: Annotation): boolean {
|
|
||||||
return anno.type === 'rect' || anno.type === 'ellipse' || anno.type === 'arrow' || anno.type === 'mosaic' || anno.type === 'highlight'
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 深拷贝标注(用于拖拽/调整大小时保存原始快照) */
|
|
||||||
function cloneAnno(a: Annotation): Annotation {
|
|
||||||
if (a.type === 'pen') return { ...a, points: a.points.map(pt => ({ ...pt })) }
|
|
||||||
return { ...a }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 移动标注:基于原始快照 + 偏移量更新目标标注坐标 */
|
|
||||||
function applyMove(target: Annotation, orig: Annotation, dx: number, dy: number) {
|
|
||||||
switch (target.type) {
|
|
||||||
case 'rect':
|
|
||||||
case 'ellipse':
|
|
||||||
case 'arrow':
|
|
||||||
case 'mosaic':
|
|
||||||
case 'highlight': {
|
|
||||||
const o = orig as typeof target
|
|
||||||
target.x1 = o.x1 + dx
|
|
||||||
target.y1 = o.y1 + dy
|
|
||||||
target.x2 = o.x2 + dx
|
|
||||||
target.y2 = o.y2 + dy
|
|
||||||
break
|
|
||||||
}
|
|
||||||
case 'pen': {
|
|
||||||
const o = orig as typeof target
|
|
||||||
target.points = o.points.map(pt => ({ x: pt.x + dx, y: pt.y + dy }))
|
|
||||||
break
|
|
||||||
}
|
|
||||||
case 'text':
|
|
||||||
case 'number': {
|
|
||||||
const o = orig as typeof target
|
|
||||||
target.x = o.x + dx
|
|
||||||
target.y = o.y + dy
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 调整标注大小:根据手柄方向更新对应坐标(仅对可调整大小的标注有效) */
|
|
||||||
function applyResize(target: Annotation, orig: Annotation, dir: HandleDir, dx: number, dy: number) {
|
|
||||||
switch (target.type) {
|
|
||||||
case 'rect':
|
|
||||||
case 'ellipse':
|
|
||||||
case 'arrow':
|
|
||||||
case 'mosaic':
|
|
||||||
case 'highlight': {
|
|
||||||
const o = orig as typeof target
|
|
||||||
let x1 = o.x1
|
|
||||||
let y1 = o.y1
|
|
||||||
let x2 = o.x2
|
|
||||||
let y2 = o.y2
|
|
||||||
if (dir.includes('e')) x2 = o.x2 + dx
|
|
||||||
if (dir.includes('s')) y2 = o.y2 + dy
|
|
||||||
if (dir.includes('w')) x1 = o.x1 + dx
|
|
||||||
if (dir.includes('n')) y1 = o.y1 + dy
|
|
||||||
target.x1 = x1
|
|
||||||
target.y1 = y1
|
|
||||||
target.x2 = x2
|
|
||||||
target.y2 = y2
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 绘制选中标注的虚线边框 */
|
|
||||||
function drawSelectionBox(ctx: CanvasRenderingContext2D, bb: { x: number; y: number; w: number; h: number }) {
|
|
||||||
const pad = 2
|
|
||||||
ctx.strokeStyle = '#3b82f6'
|
|
||||||
ctx.lineWidth = 1
|
|
||||||
ctx.setLineDash([4, 4])
|
|
||||||
ctx.strokeRect(bb.x - pad, bb.y - pad, bb.w + pad * 2, bb.h + pad * 2)
|
|
||||||
ctx.setLineDash([])
|
|
||||||
}
|
|
||||||
|
|
||||||
// ===== 标注交互 =====
|
// ===== 标注交互 =====
|
||||||
function beginDraft(e: MouseEvent) {
|
function beginDraft(e: MouseEvent) {
|
||||||
@@ -1952,10 +1734,19 @@ async function startScroll() {
|
|||||||
width: Math.round(sp.w),
|
width: Math.round(sp.w),
|
||||||
height: Math.round(sp.h),
|
height: Math.round(sp.h),
|
||||||
}
|
}
|
||||||
|
// 覆盖层挖孔(先于会话启动):Chromium 系浏览器(Edge/Chrome)的遮挡检测会把
|
||||||
|
// 被完全覆盖的窗口标记为 occluded 并暂停渲染(页面冻结、抓帧静止)。在选区带处
|
||||||
|
// 挖出真孔,目标窗口仅部分被覆盖即可恢复渲染,滚轮与拼接恢复正常。
|
||||||
|
// 先挖孔再启动,保证会话首帧与滚轮都发生在解除遮挡之后。
|
||||||
|
await commands.screenshotSetScrollHole(region).catch((e) => {
|
||||||
|
console.error('[screenshot] 覆盖层挖孔失败', e)
|
||||||
|
})
|
||||||
try {
|
try {
|
||||||
await commands.screenshotScrollStart(hwnd, region, true)
|
await commands.screenshotScrollStart(hwnd, region, true)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('[screenshot] 滚动截图启动失败', e)
|
console.error('[screenshot] 滚动截图启动失败', e)
|
||||||
|
// 启动失败:回滚挖孔,避免残留空洞
|
||||||
|
void commands.screenshotSetScrollHole(null).catch(() => {})
|
||||||
showScrollToast(String(e))
|
showScrollToast(String(e))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -1970,6 +1761,8 @@ async function startScroll() {
|
|||||||
function exitScrollMode() {
|
function exitScrollMode() {
|
||||||
scrollMode.value = false
|
scrollMode.value = false
|
||||||
scrollProgress.value = null
|
scrollProgress.value = null
|
||||||
|
// 复位覆盖层挖孔(区域在窗口上持续有效,不复位会残留空洞)
|
||||||
|
void commands.screenshotSetScrollHole(null).catch(() => {})
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 取消滚动会话并退出滚动模式(会话线程回滚窗口、丢弃画布) */
|
/** 取消滚动会话并退出滚动模式(会话线程回滚窗口、丢弃画布) */
|
||||||
@@ -2102,6 +1895,8 @@ async function beginCapture(payload?: ScreenshotBeginPayload) {
|
|||||||
scrollProgress.value = null
|
scrollProgress.value = null
|
||||||
// 新截图打断进行中的滚动会话 → 取消后台会话(避免残留占用)
|
// 新截图打断进行中的滚动会话 → 取消后台会话(避免残留占用)
|
||||||
if (wasScrolling) void commands.screenshotScrollCancel().catch(() => {})
|
if (wasScrolling) void commands.screenshotScrollCancel().catch(() => {})
|
||||||
|
// 复位覆盖层挖孔(无条件:异常路径也可能残留窗口区域,这里兜底清理)
|
||||||
|
void commands.screenshotSetScrollHole(null).catch(() => {})
|
||||||
winHighlight.value = null
|
winHighlight.value = null
|
||||||
currentHwnd.value = 0
|
currentHwnd.value = 0
|
||||||
sel.value = { x: 0, y: 0, w: 0, h: 0 }
|
sel.value = { x: 0, y: 0, w: 0, h: 0 }
|
||||||
|
|||||||
@@ -0,0 +1,242 @@
|
|||||||
|
/**
|
||||||
|
* 标注几何 / 命中测试 / 变换共享纯函数。
|
||||||
|
* 覆盖层(ScreenshotOverlay)与编辑器(ScreenshotEditor)共用,
|
||||||
|
* 保证两处对同一标注数据的选中、拖拽、调整大小行为严格一致。
|
||||||
|
*/
|
||||||
|
import type { Annotation, HandleDir, Point, TextAnno } from './types'
|
||||||
|
|
||||||
|
// ===== 文字测量 =====
|
||||||
|
|
||||||
|
/** 离屏测量上下文(惰性创建,供 measureText 使用) */
|
||||||
|
let measureCtx: CanvasRenderingContext2D | null = null
|
||||||
|
function getMeasureCtx(): CanvasRenderingContext2D | null {
|
||||||
|
if (!measureCtx) {
|
||||||
|
const c = document.createElement('canvas')
|
||||||
|
c.width = 0
|
||||||
|
c.height = 0
|
||||||
|
measureCtx = c.getContext('2d')
|
||||||
|
}
|
||||||
|
return measureCtx
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 估算文字宽高(ctx.measureText 测宽,多行取最宽行,高 = 行数 × fontSize)。
|
||||||
|
* 结果缓存:相同 text+fontSize 的测量结果不变,避免 hitTest / annoBBox 重复调用开销 */
|
||||||
|
const measureCache = new Map<string, { w: number; h: number }>()
|
||||||
|
export function measureText(text: string, fontSize: number): { w: number; h: number } {
|
||||||
|
const key = `${fontSize}\0${text}`
|
||||||
|
const cached = measureCache.get(key)
|
||||||
|
if (cached) return cached
|
||||||
|
const ctx = getMeasureCtx()
|
||||||
|
const lines = text.split('\n')
|
||||||
|
let result: { w: number; h: number }
|
||||||
|
if (!ctx) {
|
||||||
|
const maxLen = Math.max(1, ...lines.map(l => l.length))
|
||||||
|
result = { w: fontSize * maxLen * 0.6, h: fontSize * lines.length }
|
||||||
|
} else {
|
||||||
|
ctx.font = `${fontSize}px sans-serif`
|
||||||
|
let maxW = 0
|
||||||
|
for (const line of lines) {
|
||||||
|
const m = ctx.measureText(line)
|
||||||
|
if (m.width > maxW) maxW = m.width
|
||||||
|
}
|
||||||
|
result = { w: Math.ceil(maxW), h: fontSize * lines.length }
|
||||||
|
}
|
||||||
|
measureCache.set(key, result)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 几何 =====
|
||||||
|
|
||||||
|
/** 标注 bounding box(画布物理像素坐标) */
|
||||||
|
export function annoBBox(anno: Annotation): { x: number; y: number; w: number; h: number } {
|
||||||
|
switch (anno.type) {
|
||||||
|
case 'rect':
|
||||||
|
case 'ellipse':
|
||||||
|
case 'mosaic':
|
||||||
|
case 'highlight':
|
||||||
|
case 'arrow': {
|
||||||
|
const x = Math.min(anno.x1, anno.x2)
|
||||||
|
const y = Math.min(anno.y1, anno.y2)
|
||||||
|
return { x, y, w: Math.abs(anno.x2 - anno.x1), h: Math.abs(anno.y2 - anno.y1) }
|
||||||
|
}
|
||||||
|
case 'pen': {
|
||||||
|
if (anno.points.length === 0) return { x: 0, y: 0, w: 0, h: 0 }
|
||||||
|
let minX = Infinity
|
||||||
|
let minY = Infinity
|
||||||
|
let maxX = -Infinity
|
||||||
|
let maxY = -Infinity
|
||||||
|
for (const pt of anno.points) {
|
||||||
|
if (pt.x < minX) minX = pt.x
|
||||||
|
if (pt.y < minY) minY = pt.y
|
||||||
|
if (pt.x > maxX) maxX = pt.x
|
||||||
|
if (pt.y > maxY) maxY = pt.y
|
||||||
|
}
|
||||||
|
return { x: minX, y: minY, w: maxX - minX, h: maxY - minY }
|
||||||
|
}
|
||||||
|
case 'text': {
|
||||||
|
const { w, h } = measureText(anno.text, anno.fontSize)
|
||||||
|
return { x: anno.x, y: anno.y, w, h }
|
||||||
|
}
|
||||||
|
case 'number': {
|
||||||
|
const r = anno.fontSize / 2
|
||||||
|
return { x: anno.x - r, y: anno.y - r, w: anno.fontSize, h: anno.fontSize }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 点到线段的距离 */
|
||||||
|
export function distToSegment(p: Point, a: Point, b: Point): number {
|
||||||
|
const dx = b.x - a.x
|
||||||
|
const dy = b.y - a.y
|
||||||
|
const len2 = dx * dx + dy * dy
|
||||||
|
if (len2 === 0) return Math.hypot(p.x - a.x, p.y - a.y)
|
||||||
|
let t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2
|
||||||
|
t = Math.max(0, Math.min(1, t))
|
||||||
|
const cx = a.x + t * dx
|
||||||
|
const cy = a.y + t * dy
|
||||||
|
return Math.hypot(p.x - cx, p.y - cy)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 命中测试 =====
|
||||||
|
|
||||||
|
/** 文字标注区域检测:core=文字内容区(编辑),border=边框区(移动),null=未命中 */
|
||||||
|
export function hitTestTextZone(anno: TextAnno, p: Point): 'core' | 'border' | null {
|
||||||
|
const { w, h } = measureText(anno.text, anno.fontSize)
|
||||||
|
const x1 = anno.x, y1 = anno.y
|
||||||
|
const x2 = anno.x + w, y2 = anno.y + h
|
||||||
|
const pad = 8
|
||||||
|
if (p.x < x1 - pad || p.x > x2 + pad || p.y < y1 - pad || p.y > y2 + pad) return null
|
||||||
|
if (p.x >= x1 && p.x <= x2 && p.y >= y1 && p.y <= y2) return 'core'
|
||||||
|
return 'border'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 点击测试单个标注 */
|
||||||
|
export function hitTestSingle(anno: Annotation, p: Point): boolean {
|
||||||
|
switch (anno.type) {
|
||||||
|
case 'rect':
|
||||||
|
case 'ellipse':
|
||||||
|
case 'mosaic':
|
||||||
|
case 'highlight': {
|
||||||
|
const x1 = Math.min(anno.x1, anno.x2)
|
||||||
|
const y1 = Math.min(anno.y1, anno.y2)
|
||||||
|
const x2 = Math.max(anno.x1, anno.x2)
|
||||||
|
const y2 = Math.max(anno.y1, anno.y2)
|
||||||
|
const pad = Math.max(4, anno.type === 'rect' || anno.type === 'ellipse' ? anno.lineWidth : 2)
|
||||||
|
return p.x >= x1 - pad && p.x <= x2 + pad && p.y >= y1 - pad && p.y <= y2 + pad
|
||||||
|
}
|
||||||
|
case 'arrow':
|
||||||
|
return distToSegment(p, { x: anno.x1, y: anno.y1 }, { x: anno.x2, y: anno.y2 }) <= Math.max(6, anno.lineWidth)
|
||||||
|
case 'pen': {
|
||||||
|
for (let i = 1; i < anno.points.length; i++) {
|
||||||
|
if (distToSegment(p, anno.points[i - 1], anno.points[i]) <= Math.max(6, anno.lineWidth)) return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
case 'text': {
|
||||||
|
return hitTestTextZone(anno, p) !== null
|
||||||
|
}
|
||||||
|
case 'number': {
|
||||||
|
const r = anno.fontSize / 2
|
||||||
|
const dx = p.x - anno.x
|
||||||
|
const dy = p.y - anno.y
|
||||||
|
return dx * dx + dy * dy <= r * r
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 点击测试:返回命中的标注索引(-1 未命中),从后往前测试(后画的在上层) */
|
||||||
|
export function hitTestAnno(annotations: Annotation[], p: Point): number {
|
||||||
|
for (let i = annotations.length - 1; i >= 0; i--) {
|
||||||
|
if (hitTestSingle(annotations[i], p)) return i
|
||||||
|
}
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 标注是否可调整大小(pen/text/number 仅支持移动) */
|
||||||
|
export function isAnnoResizable(anno: Annotation): boolean {
|
||||||
|
return anno.type === 'rect' || anno.type === 'ellipse' || anno.type === 'arrow' || anno.type === 'mosaic' || anno.type === 'highlight'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 选中标注是否有可变颜色属性 */
|
||||||
|
export function annoHasColor(anno: Annotation): boolean {
|
||||||
|
return anno.type !== 'mosaic'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 选中标注是否有粗细概念(lineWidth) */
|
||||||
|
export function annoHasLineWidth(anno: Annotation): boolean {
|
||||||
|
return anno.type === 'rect' || anno.type === 'ellipse' || anno.type === 'arrow' || anno.type === 'pen'
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 变换 =====
|
||||||
|
|
||||||
|
/** 深拷贝标注(用于拖拽/调整大小时保存原始快照) */
|
||||||
|
export function cloneAnno(a: Annotation): Annotation {
|
||||||
|
if (a.type === 'pen') return { ...a, points: a.points.map(pt => ({ ...pt })) }
|
||||||
|
return { ...a }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 移动标注:基于原始快照 + 偏移量更新目标标注坐标 */
|
||||||
|
export function applyMove(target: Annotation, orig: Annotation, dx: number, dy: number) {
|
||||||
|
switch (target.type) {
|
||||||
|
case 'rect':
|
||||||
|
case 'ellipse':
|
||||||
|
case 'arrow':
|
||||||
|
case 'mosaic':
|
||||||
|
case 'highlight': {
|
||||||
|
const o = orig as typeof target
|
||||||
|
target.x1 = o.x1 + dx
|
||||||
|
target.y1 = o.y1 + dy
|
||||||
|
target.x2 = o.x2 + dx
|
||||||
|
target.y2 = o.y2 + dy
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case 'pen': {
|
||||||
|
const o = orig as typeof target
|
||||||
|
target.points = o.points.map(pt => ({ x: pt.x + dx, y: pt.y + dy }))
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case 'text':
|
||||||
|
case 'number': {
|
||||||
|
const o = orig as typeof target
|
||||||
|
target.x = o.x + dx
|
||||||
|
target.y = o.y + dy
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 调整标注大小:根据手柄方向更新对应坐标(仅对可调整大小的标注有效) */
|
||||||
|
export function applyResize(target: Annotation, orig: Annotation, dir: HandleDir, dx: number, dy: number) {
|
||||||
|
switch (target.type) {
|
||||||
|
case 'rect':
|
||||||
|
case 'ellipse':
|
||||||
|
case 'arrow':
|
||||||
|
case 'mosaic':
|
||||||
|
case 'highlight': {
|
||||||
|
const o = orig as typeof target
|
||||||
|
let x1 = o.x1
|
||||||
|
let y1 = o.y1
|
||||||
|
let x2 = o.x2
|
||||||
|
let y2 = o.y2
|
||||||
|
if (dir.includes('e')) x2 = o.x2 + dx
|
||||||
|
if (dir.includes('s')) y2 = o.y2 + dy
|
||||||
|
if (dir.includes('w')) x1 = o.x1 + dx
|
||||||
|
if (dir.includes('n')) y1 = o.y1 + dy
|
||||||
|
target.x1 = x1
|
||||||
|
target.y1 = y1
|
||||||
|
target.x2 = x2
|
||||||
|
target.y2 = y2
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 绘制选中标注的虚线边框 */
|
||||||
|
export function drawSelectionBox(ctx: CanvasRenderingContext2D, bb: { x: number; y: number; w: number; h: number }) {
|
||||||
|
const pad = 2
|
||||||
|
ctx.strokeStyle = '#3b82f6'
|
||||||
|
ctx.lineWidth = 1
|
||||||
|
ctx.setLineDash([4, 4])
|
||||||
|
ctx.strokeRect(bb.x - pad, bb.y - pad, bb.w + pad * 2, bb.h + pad * 2)
|
||||||
|
ctx.setLineDash([])
|
||||||
|
}
|
||||||
@@ -0,0 +1,799 @@
|
|||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { invoke } from '@tauri-apps/api/core'
|
||||||
|
import { createLogger } from '@/lib/logger'
|
||||||
|
|
||||||
|
const logger = createLogger('feiniu')
|
||||||
|
|
||||||
|
/** 可播条目(飞牛 NAS 或本地文件),是播放器/歌单的统一数据模型 */
|
||||||
|
export interface PlayableItem {
|
||||||
|
source: 'feiniu' | 'local'
|
||||||
|
/** feiniu 源:track guid;local 源:文件路径 */
|
||||||
|
guid?: string
|
||||||
|
title: string
|
||||||
|
artistNames: string
|
||||||
|
album?: string
|
||||||
|
durationMs?: number
|
||||||
|
coverId?: string
|
||||||
|
/** local 源文件大小(字节) */
|
||||||
|
size?: number
|
||||||
|
/** local 源所在目录 */
|
||||||
|
dir?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FeiniuConnection {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
kind: 'lan' | 'frp' | 'fnconnect'
|
||||||
|
baseUrl: string
|
||||||
|
username: string
|
||||||
|
loggedIn: boolean
|
||||||
|
accessCode: string
|
||||||
|
insecure: boolean
|
||||||
|
fnId?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Playlist {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
items: PlayableItem[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PlayMode = 'loopAll' | 'loopOne' | 'shuffle'
|
||||||
|
|
||||||
|
interface LrcLine {
|
||||||
|
t: number
|
||||||
|
text: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const PLAYERS_KEY = 'thing.music.playlists'
|
||||||
|
const QUEUE_KEY = 'thing.music.queue'
|
||||||
|
const VOL_KEY = 'thing.music.volume'
|
||||||
|
|
||||||
|
function uid(): string {
|
||||||
|
return `p${Date.now().toString(36)}${Math.random().toString(36).slice(2, 7)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useFeiniuStore = defineStore('feiniu', () => {
|
||||||
|
// ===== 连接 =====
|
||||||
|
const connections = ref<FeiniuConnection[]>([])
|
||||||
|
const activeId = ref('')
|
||||||
|
const config = ref<{ baseUrl: string; username: string; loggedIn: boolean }>({
|
||||||
|
baseUrl: '',
|
||||||
|
username: '',
|
||||||
|
loggedIn: false
|
||||||
|
})
|
||||||
|
const mediaPrefix = ref('')
|
||||||
|
const connecting = ref(false)
|
||||||
|
// 缓存播放模式('stream' 直连 | 'cache' 缓存后播放)
|
||||||
|
const cacheMode = ref<'stream' | 'cache'>('stream')
|
||||||
|
const cacheStatus = ref<{ count: number; usedMb: number }>({ count: 0, usedMb: 0 })
|
||||||
|
|
||||||
|
// fnOS 文件服务(P6:上传到飞牛)
|
||||||
|
const fnosLoggedIn = ref(false)
|
||||||
|
const libraryNasPath = ref('')
|
||||||
|
const autoUpload = ref(false)
|
||||||
|
const uploading = ref(false)
|
||||||
|
|
||||||
|
const activeConn = computed(() => connections.value.find((c) => c.id === activeId.value) || null)
|
||||||
|
|
||||||
|
// ===== 曲库(飞牛 + 本地) =====
|
||||||
|
const tracks = ref<PlayableItem[]>([])
|
||||||
|
const page = ref(1)
|
||||||
|
const total = ref(0)
|
||||||
|
const loading = ref(false)
|
||||||
|
const keyword = ref('')
|
||||||
|
const localTracks = ref<PlayableItem[]>([])
|
||||||
|
const localScanBusy = ref(false)
|
||||||
|
|
||||||
|
// ===== 歌单 =====
|
||||||
|
const playlists = ref<Playlist[]>([])
|
||||||
|
|
||||||
|
// ===== 播放器内核 =====
|
||||||
|
const queue = ref<PlayableItem[]>([])
|
||||||
|
const queueIndex = ref(-1)
|
||||||
|
const playMode = ref<PlayMode>('loopAll')
|
||||||
|
const volume = ref(0.8)
|
||||||
|
const current = computed(() => queue.value[queueIndex.value] ?? null)
|
||||||
|
const playing = ref(false)
|
||||||
|
const loadingPlay = ref(false)
|
||||||
|
const position = ref(0)
|
||||||
|
const duration = ref(0)
|
||||||
|
const lyricLines = ref<LrcLine[]>([])
|
||||||
|
const lyricVisible = ref(false)
|
||||||
|
const queueVisible = ref(false)
|
||||||
|
const nowPlayingOpen = ref(false)
|
||||||
|
let lyricRaw = ''
|
||||||
|
let audioEl: HTMLAudioElement | null = null
|
||||||
|
|
||||||
|
function ensureAudio(): HTMLAudioElement {
|
||||||
|
if (!audioEl) {
|
||||||
|
const a = new Audio()
|
||||||
|
a.preload = 'auto'
|
||||||
|
a.volume = volume.value
|
||||||
|
a.addEventListener('loadedmetadata', () => (duration.value = a.duration || 0))
|
||||||
|
a.addEventListener('timeupdate', () => (position.value = a.currentTime))
|
||||||
|
a.addEventListener('play', () => (playing.value = true))
|
||||||
|
a.addEventListener('pause', () => (playing.value = false))
|
||||||
|
a.addEventListener('ended', () => onEnded())
|
||||||
|
a.addEventListener('error', () => {
|
||||||
|
loadingPlay.value = false
|
||||||
|
playing.value = false
|
||||||
|
})
|
||||||
|
audioEl = a
|
||||||
|
}
|
||||||
|
return audioEl
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 初始化 & 连接 =====
|
||||||
|
async function init() {
|
||||||
|
try {
|
||||||
|
const r = await invoke<{ activeId: string; list: FeiniuConnection[] }>('feiniu_list_connections')
|
||||||
|
connections.value = r?.list || []
|
||||||
|
activeId.value = r?.activeId || ''
|
||||||
|
const c = await invoke<{ baseUrl: string; username: string; loggedIn: boolean }>('feiniu_get_config')
|
||||||
|
config.value = c
|
||||||
|
if (c?.loggedIn) await refreshMediaPrefix()
|
||||||
|
} catch (e) {
|
||||||
|
logger.error(`初始化失败: ${e}`)
|
||||||
|
}
|
||||||
|
loadPlaylists()
|
||||||
|
restoreQueue()
|
||||||
|
try {
|
||||||
|
volume.value = Number(localStorage.getItem(VOL_KEY)) || 0.8
|
||||||
|
const cm = localStorage.getItem('thing.music.cachemode')
|
||||||
|
if (cm === 'cache' || cm === 'stream') cacheMode.value = cm
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
await ensureCacheStatus()
|
||||||
|
try {
|
||||||
|
libraryNasPath.value = localStorage.getItem('thing.music.feiniu.naspath') || ''
|
||||||
|
autoUpload.value = localStorage.getItem('thing.music.feiniu.autoupload') === '1'
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
await refreshFnosStatus()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshFnosStatus() {
|
||||||
|
if (!activeId.value) {
|
||||||
|
fnosLoggedIn.value = false
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const r = await invoke<{ loggedIn: boolean }>('feiniu_fnos_status', { connectionId: activeId.value })
|
||||||
|
fnosLoggedIn.value = !!r?.loggedIn
|
||||||
|
} catch {
|
||||||
|
fnosLoggedIn.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fnosLogin(username: string, password: string) {
|
||||||
|
if (!activeId.value) throw new Error('请先激活一个连接')
|
||||||
|
await invoke('feiniu_fnos_login', { connectionId: activeId.value, username, password })
|
||||||
|
fnosLoggedIn.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function fnosLogout() {
|
||||||
|
if (activeId.value) invoke('feiniu_fnos_logout', { connectionId: activeId.value }).catch(() => {})
|
||||||
|
fnosLoggedIn.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
function setLibraryNasPath(v: string) {
|
||||||
|
libraryNasPath.value = v
|
||||||
|
try {
|
||||||
|
localStorage.setItem('thing.music.feiniu.naspath', v)
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setAutoUpload(v: boolean) {
|
||||||
|
autoUpload.value = v
|
||||||
|
try {
|
||||||
|
localStorage.setItem('thing.music.feiniu.autoupload', v ? '1' : '0')
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 上传单个本地文件到飞牛曲库目录(激活连接)。 */
|
||||||
|
async function uploadToFeiniu(localPath: string, fileName: string): Promise<void> {
|
||||||
|
if (!fnosLoggedIn.value) throw new Error('请先登录 NAS 文件服务')
|
||||||
|
const base = libraryNasPath.value.replace(/[\\/]+$/, '')
|
||||||
|
const nasPath = base ? `${base}/${fileName}` : fileName
|
||||||
|
uploading.value = true
|
||||||
|
try {
|
||||||
|
await invoke('feiniu_fnos_upload', { localPath, nasPath })
|
||||||
|
} finally {
|
||||||
|
uploading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 上传一个本地曲目(自动取文件名)到飞牛曲库。 */
|
||||||
|
async function uploadLocalTrack(item: PlayableItem): Promise<void> {
|
||||||
|
if (!item.guid) throw new Error('缺少本地文件路径')
|
||||||
|
const name = item.guid.split(/[\\/]/).pop() || 'music.bin'
|
||||||
|
await uploadToFeiniu(item.guid, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 把最近 N 分钟内新出现的本地音频批量上传到飞牛曲库。返回 { total, ok }。 */
|
||||||
|
async function uploadRecentToFeiniu(minutes = 10): Promise<{ total: number; ok: number }> {
|
||||||
|
if (!fnosLoggedIn.value) throw new Error('请先连接 NAS 文件服务(设置 → 飞牛连接)')
|
||||||
|
if (!libraryNasPath.value) throw new Error('请先填写飞牛曲库目录(设置 → 上传到飞牛)')
|
||||||
|
const r = await invoke<{ items: any[] }>('feiniu_scan_local')
|
||||||
|
const now = Date.now() / 1000
|
||||||
|
const recent = (r?.items || []).filter((f) => now - (f.mtim || 0) <= minutes * 60)
|
||||||
|
let ok = 0
|
||||||
|
uploading.value = true
|
||||||
|
try {
|
||||||
|
for (const f of recent) {
|
||||||
|
const path = String(f.path)
|
||||||
|
const name = path.split(/[\\/]/).pop() || 'music.bin'
|
||||||
|
try {
|
||||||
|
await uploadToFeiniu(path, name)
|
||||||
|
ok++
|
||||||
|
} catch {
|
||||||
|
/* 单文件失败继续 */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
uploading.value = false
|
||||||
|
}
|
||||||
|
return { total: recent.length, ok }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 删除 NAS 上的文件(激活连接)。 */
|
||||||
|
async function deleteFromFeiniu(nasPath: string): Promise<void> {
|
||||||
|
await invoke('feiniu_fnos_delete', { nasPath })
|
||||||
|
}
|
||||||
|
|
||||||
|
/** FnConnect:解析 fnId 得到可达 base_url。 */
|
||||||
|
async function resolveFnConnect(fnId: string): Promise<{ baseUrl: string; relay: boolean }> {
|
||||||
|
return invoke('feiniu_fnconnect_resolve', { fnId })
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureCacheStatus() {
|
||||||
|
try {
|
||||||
|
const r = await invoke<{ count: number; usedMb: number }>('feiniu_cache_status')
|
||||||
|
cacheStatus.value = { count: r?.count ?? 0, usedMb: r?.usedMb ?? 0 }
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setCacheMode(mode: 'stream' | 'cache') {
|
||||||
|
cacheMode.value = mode
|
||||||
|
try {
|
||||||
|
localStorage.setItem('thing.music.cachemode', mode)
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
if (mode === 'stream') clearPlayback()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function clearCache() {
|
||||||
|
await invoke('feiniu_cache_clear')
|
||||||
|
await ensureCacheStatus()
|
||||||
|
clearPlayback()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshConnections() {
|
||||||
|
try {
|
||||||
|
const r = await invoke<{ activeId: string; list: FeiniuConnection[] }>('feiniu_list_connections')
|
||||||
|
connections.value = r?.list || []
|
||||||
|
activeId.value = r?.activeId || ''
|
||||||
|
await refreshFnosStatus()
|
||||||
|
const c = await invoke<{ baseUrl: string; username: string; loggedIn: boolean }>('feiniu_get_config')
|
||||||
|
config.value = c
|
||||||
|
} catch (e) {
|
||||||
|
logger.error(String(e))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveConnection(conn: Partial<FeiniuConnection> & { name: string; baseUrl: string; kind: string }): Promise<string> {
|
||||||
|
const r = await invoke<{ ok: boolean }>('feiniu_save_connection', {
|
||||||
|
connection: {
|
||||||
|
id: conn.id || '',
|
||||||
|
name: conn.name,
|
||||||
|
kind: conn.kind,
|
||||||
|
baseUrl: conn.baseUrl,
|
||||||
|
username: conn.username || '',
|
||||||
|
token: '',
|
||||||
|
deviceId: '',
|
||||||
|
accessCode: conn.accessCode || '',
|
||||||
|
insecure: conn.insecure || false,
|
||||||
|
fnId: conn.fnId || ''
|
||||||
|
}
|
||||||
|
})
|
||||||
|
void r
|
||||||
|
await refreshConnections()
|
||||||
|
return connections.value.find((c) => c.baseUrl === conn.baseUrl && c.name === conn.name)?.id || ''
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteConnection(id: string) {
|
||||||
|
await invoke('feiniu_delete_connection', { id })
|
||||||
|
await refreshConnections()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function activateConnection(id: string) {
|
||||||
|
await invoke('feiniu_activate_connection', { id })
|
||||||
|
await refreshConnections()
|
||||||
|
if (config.value.loggedIn) await refreshMediaPrefix()
|
||||||
|
await refreshFnosStatus()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function login(connectionId: string, username: string, password: string) {
|
||||||
|
connecting.value = true
|
||||||
|
try {
|
||||||
|
const r = await invoke<{ mediaPrefix: string }>('feiniu_login', {
|
||||||
|
connectionId,
|
||||||
|
username,
|
||||||
|
password
|
||||||
|
})
|
||||||
|
await refreshConnections()
|
||||||
|
config.value = { baseUrl: activeConn.value?.baseUrl || '', username, loggedIn: true }
|
||||||
|
if (r?.mediaPrefix) mediaPrefix.value = r.mediaPrefix
|
||||||
|
await loadTracks(1)
|
||||||
|
} catch (e) {
|
||||||
|
logger.error(String(e))
|
||||||
|
throw e
|
||||||
|
} finally {
|
||||||
|
connecting.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function logout(connectionId: string) {
|
||||||
|
try {
|
||||||
|
await invoke('feiniu_logout', { connectionId })
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
await refreshConnections()
|
||||||
|
config.value.loggedIn = false
|
||||||
|
mediaPrefix.value = ''
|
||||||
|
tracks.value = []
|
||||||
|
clearPlayback()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function testConnection(id: string, username: string, password: string): Promise<boolean> {
|
||||||
|
const r = await invoke<{ ok: boolean }>('feiniu_test_connection', { connectionId: id, username, password })
|
||||||
|
return !!r?.ok
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshMediaPrefix() {
|
||||||
|
try {
|
||||||
|
const r = await invoke<{ mediaPrefix: string }>('feiniu_media_prefix')
|
||||||
|
mediaPrefix.value = r?.mediaPrefix || ''
|
||||||
|
} catch (e) {
|
||||||
|
logger.error(String(e))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 飞牛曲库 =====
|
||||||
|
async function loadTracks(p: number = 1): Promise<void> {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const data = await invoke<any>('feiniu_list_tracks', {
|
||||||
|
page: p,
|
||||||
|
size: 50,
|
||||||
|
keyword: keyword.value.trim() || null
|
||||||
|
})
|
||||||
|
const list = Array.isArray(data) ? data : data?.list || data?.items || data?.tracks || []
|
||||||
|
tracks.value = (list as any[]).map((t) => normalizeTrack(t))
|
||||||
|
total.value = data?.total ?? data?.count ?? list.length
|
||||||
|
page.value = p
|
||||||
|
} catch (e) {
|
||||||
|
logger.error(String(e))
|
||||||
|
throw e
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeTrack(t: any): PlayableItem {
|
||||||
|
const artists = Array.isArray(t.artists) ? t.artists : []
|
||||||
|
const album = typeof t.album === 'string' ? t.album : t.album?.name || t.albumName || ''
|
||||||
|
return {
|
||||||
|
source: 'feiniu',
|
||||||
|
guid: t.guid || t.trackGuid || t.id,
|
||||||
|
title: t.title || t.name || '未知标题',
|
||||||
|
durationMs: t.durationMs ?? t.duration ?? undefined,
|
||||||
|
coverId: t.coverId || undefined,
|
||||||
|
album,
|
||||||
|
artistNames:
|
||||||
|
artists.map((a: { name?: string }) => a.name).filter(Boolean).join(' / ') ||
|
||||||
|
t.artist ||
|
||||||
|
t.singers ||
|
||||||
|
''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 本地曲库 =====
|
||||||
|
async function scanLocal() {
|
||||||
|
localScanBusy.value = true
|
||||||
|
try {
|
||||||
|
const data = await invoke<{ items: any[] }>('feiniu_scan_local')
|
||||||
|
localTracks.value = (data?.items || []).map((f) => ({
|
||||||
|
source: 'local' as const,
|
||||||
|
guid: f.path,
|
||||||
|
title: f.title || f.name || '未知',
|
||||||
|
artistNames: '',
|
||||||
|
durationMs: undefined,
|
||||||
|
size: f.size,
|
||||||
|
dir: f.dir
|
||||||
|
}))
|
||||||
|
} catch (e) {
|
||||||
|
logger.error(String(e))
|
||||||
|
throw e
|
||||||
|
} finally {
|
||||||
|
localScanBusy.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 歌单 =====
|
||||||
|
function loadPlaylists() {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(PLAYERS_KEY)
|
||||||
|
if (!raw) return
|
||||||
|
playlists.value = JSON.parse(raw)
|
||||||
|
} catch {
|
||||||
|
playlists.value = []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function persistPlaylists() {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(PLAYERS_KEY, JSON.stringify(playlists.value))
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function createPlaylist(name: string): string {
|
||||||
|
const id = uid()
|
||||||
|
playlists.value.push({ id, name, items: [] })
|
||||||
|
persistPlaylists()
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
function renamePlaylist(id: string, name: string) {
|
||||||
|
const p = playlists.value.find((p) => p.id === id)
|
||||||
|
if (p) {
|
||||||
|
p.name = name
|
||||||
|
persistPlaylists()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function deletePlaylist(id: string) {
|
||||||
|
playlists.value = playlists.value.filter((p) => p.id !== id)
|
||||||
|
persistPlaylists()
|
||||||
|
}
|
||||||
|
function addToPlaylist(playlistId: string, items: PlayableItem[]) {
|
||||||
|
const p = playlists.value.find((p) => p.id === playlistId)
|
||||||
|
if (!p) return
|
||||||
|
for (const it of items) {
|
||||||
|
const dup = p.items.some((x) => x.guid === it.guid && x.source === it.source)
|
||||||
|
if (!dup) p.items.push({ ...it })
|
||||||
|
}
|
||||||
|
persistPlaylists()
|
||||||
|
}
|
||||||
|
function removeFromPlaylist(playlistId: string, index: number) {
|
||||||
|
const p = playlists.value.find((p) => p.id === playlistId)
|
||||||
|
if (p) {
|
||||||
|
p.items.splice(index, 1)
|
||||||
|
persistPlaylists()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function moveInPlaylist(playlistId: string, from: number, to: number) {
|
||||||
|
const p = playlists.value.find((p) => p.id === playlistId)
|
||||||
|
if (!p || from < 0 || to < 0 || from >= p.items.length || to >= p.items.length) return
|
||||||
|
const [it] = p.items.splice(from, 1)
|
||||||
|
p.items.splice(to, 0, it)
|
||||||
|
persistPlaylists()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 播放器 =====
|
||||||
|
function playQueue(items: PlayableItem[], startIndex = 0) {
|
||||||
|
queue.value = items.map((i) => ({ ...i }))
|
||||||
|
queueIndex.value = Math.min(Math.max(startIndex, 0), items.length - 1)
|
||||||
|
playCurrent()
|
||||||
|
}
|
||||||
|
|
||||||
|
function playItem(item: PlayableItem) {
|
||||||
|
// 若已在队列中,跳转到它;否则作为新队列播放
|
||||||
|
const i = queue.value.findIndex((q) => q.guid === item.guid && q.source === item.source)
|
||||||
|
if (i >= 0) {
|
||||||
|
queueIndex.value = i
|
||||||
|
playCurrent()
|
||||||
|
} else {
|
||||||
|
queue.value = [{ ...item }]
|
||||||
|
queueIndex.value = 0
|
||||||
|
playCurrent()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function playCurrent() {
|
||||||
|
const t = current.value
|
||||||
|
if (!t) return
|
||||||
|
if (t.source === 'feiniu') loadLyric(t.guid)
|
||||||
|
else lyricLines.value = []
|
||||||
|
const a = ensureAudio()
|
||||||
|
a.pause()
|
||||||
|
if (t.source === 'feiniu' && cacheMode.value === 'cache') {
|
||||||
|
playCached(t, a)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
a.src =
|
||||||
|
t.source === 'feiniu'
|
||||||
|
? `${mediaPrefix.value}/stream?guid=${encodeURIComponent(t.guid || '')}`
|
||||||
|
: `file://${(t.guid || '').replace(/\\/g, '/')}`
|
||||||
|
a.currentTime = 0
|
||||||
|
startPlayback(a)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function playCached(t: PlayableItem, a: HTMLAudioElement) {
|
||||||
|
loadingPlay.value = true
|
||||||
|
try {
|
||||||
|
const r = await invoke<{ path: string | null }>('feiniu_cache_fetch', { guid: t.guid || '' })
|
||||||
|
if (r?.path) {
|
||||||
|
a.src = `file://${(r.path as string).replace(/\\/g, '/')}`
|
||||||
|
a.currentTime = 0
|
||||||
|
startPlayback(a)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* fall through to stream */
|
||||||
|
}
|
||||||
|
// 缓存失败(未登录/网络)→ 回退直连流
|
||||||
|
a.src = `${mediaPrefix.value}/stream?guid=${encodeURIComponent(t.guid || '')}`
|
||||||
|
a.currentTime = 0
|
||||||
|
startPlayback(a)
|
||||||
|
}
|
||||||
|
|
||||||
|
function startPlayback(a: HTMLAudioElement) {
|
||||||
|
loadingPlay.value = true
|
||||||
|
a.play()
|
||||||
|
.then(() => {
|
||||||
|
loadingPlay.value = false
|
||||||
|
persistQueue()
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
loadingPlay.value = false
|
||||||
|
persistQueue()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggle() {
|
||||||
|
const a = ensureAudio()
|
||||||
|
if (a.paused) a.play().catch(() => {})
|
||||||
|
else a.pause()
|
||||||
|
}
|
||||||
|
|
||||||
|
function next(manual = true) {
|
||||||
|
const n = queue.value.length
|
||||||
|
if (n === 0) return
|
||||||
|
if (manual && playMode.value === 'shuffle') {
|
||||||
|
let idx = queueIndex.value
|
||||||
|
while (idx === queueIndex.value && n > 1) idx = Math.floor(Math.random() * n)
|
||||||
|
queueIndex.value = idx
|
||||||
|
} else if (queueIndex.value < n - 1) {
|
||||||
|
queueIndex.value++
|
||||||
|
} else if (playMode.value !== 'loopOne') {
|
||||||
|
queueIndex.value = 0
|
||||||
|
} else {
|
||||||
|
// loopOne 且已到末尾:保持当前
|
||||||
|
queueIndex.value = 0
|
||||||
|
}
|
||||||
|
playCurrent()
|
||||||
|
}
|
||||||
|
|
||||||
|
function onEnded() {
|
||||||
|
if (playMode.value === 'loopOne') {
|
||||||
|
const a = ensureAudio()
|
||||||
|
a.currentTime = 0
|
||||||
|
a.play().catch(() => {})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
function prev() {
|
||||||
|
const a = ensureAudio()
|
||||||
|
if (a.currentTime > 3) {
|
||||||
|
a.currentTime = 0
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (queueIndex.value > 0) queueIndex.value--
|
||||||
|
else queueIndex.value = 0
|
||||||
|
playCurrent()
|
||||||
|
}
|
||||||
|
|
||||||
|
function seek(sec: number) {
|
||||||
|
const a = ensureAudio()
|
||||||
|
a.currentTime = Math.max(0, sec)
|
||||||
|
position.value = a.currentTime
|
||||||
|
}
|
||||||
|
|
||||||
|
function setVolume(v: number) {
|
||||||
|
volume.value = v
|
||||||
|
const a = ensureAudio()
|
||||||
|
a.volume = v
|
||||||
|
try {
|
||||||
|
localStorage.setItem(VOL_KEY, String(v))
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function togglePlayMode() {
|
||||||
|
playMode.value = playMode.value === 'loopAll' ? 'loopOne' : playMode.value === 'loopOne' ? 'shuffle' : 'loopAll'
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearPlayback() {
|
||||||
|
queue.value = []
|
||||||
|
queueIndex.value = -1
|
||||||
|
lyricLines.value = []
|
||||||
|
position.value = 0
|
||||||
|
duration.value = 0
|
||||||
|
playing.value = false
|
||||||
|
if (audioEl) {
|
||||||
|
audioEl.pause()
|
||||||
|
audioEl.removeAttribute('src')
|
||||||
|
audioEl.load()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function restoreQueue() {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(QUEUE_KEY)
|
||||||
|
if (!raw) return
|
||||||
|
const s = JSON.parse(raw)
|
||||||
|
if (!s?.queue || !Array.isArray(s.queue)) return
|
||||||
|
queue.value = s.queue
|
||||||
|
queueIndex.value = typeof s.index === 'number' ? s.index : -1
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function persistQueue() {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(QUEUE_KEY, JSON.stringify({ queue: queue.value, index: queueIndex.value }))
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function fmtDuration(sec?: number): string {
|
||||||
|
if (sec == null || !isFinite(sec)) return '--:--'
|
||||||
|
const s = Math.floor(sec)
|
||||||
|
const m = Math.floor(s / 60)
|
||||||
|
const r = s % 60
|
||||||
|
return `${String(m).padStart(2, '0')}:${String(r).padStart(2, '0')}`
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadLyric(guid?: string) {
|
||||||
|
lyricLines.value = []
|
||||||
|
if (!guid) return
|
||||||
|
try {
|
||||||
|
const r = await invoke<{ lyric: string }>('feiniu_lyric', { guid })
|
||||||
|
const text = r?.lyric || ''
|
||||||
|
if (text === lyricRaw) return
|
||||||
|
lyricRaw = text
|
||||||
|
lyricLines.value = parseLrc(text)
|
||||||
|
} catch (e) {
|
||||||
|
logger.error(String(e))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseLrc(text: string): LrcLine[] {
|
||||||
|
const lines: LrcLine[] = []
|
||||||
|
const lineRe = /\[(\d{1,2}):(\d{1,2})(?:[.:](\d{1,3}))?]/g
|
||||||
|
const parts = text.split(/\r?\n/)
|
||||||
|
for (const part of parts) {
|
||||||
|
const timestamps: number[] = []
|
||||||
|
let src = part
|
||||||
|
let m: RegExpExecArray | null
|
||||||
|
while ((m = lineRe.exec(part))) {
|
||||||
|
const mm = Number(m[1])
|
||||||
|
const ss = Number(m[2])
|
||||||
|
const frac = m[3] ? Number(m[3].padEnd(3, '0')) / 1000 : 0
|
||||||
|
timestamps.push(mm * 60 + ss + frac)
|
||||||
|
src = part.slice(lineRe.lastIndex)
|
||||||
|
}
|
||||||
|
const content = src.replace(/^\[[^\]]*]\s*/, '').trim()
|
||||||
|
if (!content) continue
|
||||||
|
for (const t of timestamps) lines.push({ t, text: content })
|
||||||
|
}
|
||||||
|
lines.sort((a, b) => a.t - b.t)
|
||||||
|
return lines
|
||||||
|
}
|
||||||
|
|
||||||
|
function currentLine(): number {
|
||||||
|
let idx = -1
|
||||||
|
for (let k = 0; k < lyricLines.value.length; k++) {
|
||||||
|
if (lyricLines.value[k].t <= position.value) idx = k
|
||||||
|
else break
|
||||||
|
}
|
||||||
|
return idx
|
||||||
|
}
|
||||||
|
|
||||||
|
const progress = computed(() => (duration.value > 0 ? (position.value / duration.value) * 100 : 0))
|
||||||
|
|
||||||
|
return {
|
||||||
|
connections,
|
||||||
|
activeId,
|
||||||
|
activeConn,
|
||||||
|
config,
|
||||||
|
mediaPrefix,
|
||||||
|
connecting,
|
||||||
|
cacheMode,
|
||||||
|
cacheStatus,
|
||||||
|
tracks,
|
||||||
|
page,
|
||||||
|
total,
|
||||||
|
loading,
|
||||||
|
keyword,
|
||||||
|
localTracks,
|
||||||
|
localScanBusy,
|
||||||
|
playlists,
|
||||||
|
queue,
|
||||||
|
queueIndex,
|
||||||
|
playMode,
|
||||||
|
volume,
|
||||||
|
current,
|
||||||
|
playing,
|
||||||
|
loadingPlay,
|
||||||
|
position,
|
||||||
|
duration,
|
||||||
|
lyricLines,
|
||||||
|
lyricVisible,
|
||||||
|
queueVisible,
|
||||||
|
nowPlayingOpen,
|
||||||
|
progress,
|
||||||
|
init,
|
||||||
|
refreshConnections,
|
||||||
|
saveConnection,
|
||||||
|
deleteConnection,
|
||||||
|
activateConnection,
|
||||||
|
login,
|
||||||
|
logout,
|
||||||
|
testConnection,
|
||||||
|
refreshMediaPrefix,
|
||||||
|
loadTracks,
|
||||||
|
scanLocal,
|
||||||
|
ensureCacheStatus,
|
||||||
|
setCacheMode,
|
||||||
|
clearCache,
|
||||||
|
fnosLoggedIn,
|
||||||
|
libraryNasPath,
|
||||||
|
autoUpload,
|
||||||
|
uploading,
|
||||||
|
refreshFnosStatus,
|
||||||
|
fnosLogin,
|
||||||
|
fnosLogout,
|
||||||
|
setLibraryNasPath,
|
||||||
|
setAutoUpload,
|
||||||
|
uploadToFeiniu,
|
||||||
|
uploadLocalTrack,
|
||||||
|
uploadRecentToFeiniu,
|
||||||
|
deleteFromFeiniu,
|
||||||
|
resolveFnConnect,
|
||||||
|
createPlaylist,
|
||||||
|
renamePlaylist,
|
||||||
|
deletePlaylist,
|
||||||
|
addToPlaylist,
|
||||||
|
removeFromPlaylist,
|
||||||
|
moveInPlaylist,
|
||||||
|
playQueue,
|
||||||
|
playItem,
|
||||||
|
toggle,
|
||||||
|
next,
|
||||||
|
prev,
|
||||||
|
seek,
|
||||||
|
setVolume,
|
||||||
|
togglePlayMode,
|
||||||
|
clearPlayback,
|
||||||
|
persistQueue,
|
||||||
|
fmtDuration,
|
||||||
|
currentLine
|
||||||
|
}
|
||||||
|
})
|
||||||
@@ -0,0 +1,595 @@
|
|||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import { computed, ref, watch } from 'vue'
|
||||||
|
import { invoke } from '@tauri-apps/api/core'
|
||||||
|
import { listen, type UnlistenFn } from '@tauri-apps/api/event'
|
||||||
|
import { commands, type MusicEnvStatus, type MusicSettings } from '@/lib/bindings'
|
||||||
|
import { useProxyStore } from '@/stores/proxyStore'
|
||||||
|
import { createLogger } from '@/lib/logger'
|
||||||
|
|
||||||
|
/** 搜索结果中的单曲(与 bridge.py song_to_dict 字段对应) */
|
||||||
|
export interface MusicSong {
|
||||||
|
songName: string | null
|
||||||
|
singers: string | null
|
||||||
|
album: string | null
|
||||||
|
duration: string | null
|
||||||
|
durationS: number | null
|
||||||
|
fileSize: string | null
|
||||||
|
fileSizeBytes: number | null
|
||||||
|
ext: string | null
|
||||||
|
source: string | null
|
||||||
|
rootSource: string | null
|
||||||
|
downloadUrl: string | null
|
||||||
|
valid: boolean
|
||||||
|
coverUrl: string | null
|
||||||
|
bitrate: number | null
|
||||||
|
/** 下载所需:save_path 命名用 */
|
||||||
|
identifier?: string | null
|
||||||
|
/** 默认下载请求头(rust 引擎直传下载器模块用) */
|
||||||
|
defaultDownloadHeaders?: Record<string, string> | null
|
||||||
|
defaultDownloadCookies?: Record<string, string> | null
|
||||||
|
/** 懒解析:官方搜索 API 的原始结果(resolve/下载前解析真实链接用) */
|
||||||
|
rawSearch?: Record<string, unknown> | null
|
||||||
|
/** 音质提示:true=具备无损(ext 或官方音质字段推断),null=未知;懒解析歌 ext/fileSize 为空时筛选依据 */
|
||||||
|
lossless?: boolean | null
|
||||||
|
/** 全音质档位(搜索阶段多档展示:label/ext/bitrate/sizeBytes/size/lossless);懒解析歌为数组,急切解析/无数据为 null */
|
||||||
|
qualities?: MusicQuality[] | null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 单个音质档位(musicdl 官方接口搜索阶段批量取回的格式+大小+无损) */
|
||||||
|
export interface MusicQuality {
|
||||||
|
label: string | null
|
||||||
|
ext: string | null
|
||||||
|
bitrate: number | null
|
||||||
|
sizeBytes: number | null
|
||||||
|
size: string | null
|
||||||
|
lossless: boolean | null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 桥接下载事件(bridge.py 事件行,经 Rust 原样转发) */
|
||||||
|
export interface MusicDownloadEvent {
|
||||||
|
event: string
|
||||||
|
taskId?: string
|
||||||
|
type?: 'start' | 'progress' | 'done' | 'error' | 'cancelled' | 'finished' | 'resolving' | 'bridge-stopped'
|
||||||
|
key?: string
|
||||||
|
songName?: string
|
||||||
|
singers?: string
|
||||||
|
ext?: string
|
||||||
|
/** 实际解析出的音质档位(start 事件回传,如 "无损"/"320K") */
|
||||||
|
quality?: string
|
||||||
|
downloaded?: number
|
||||||
|
total?: number
|
||||||
|
done?: number
|
||||||
|
message?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 任务内单曲状态(key = "{source}|{idx}") */
|
||||||
|
export interface MusicDownloadSongState {
|
||||||
|
key: string
|
||||||
|
songName: string
|
||||||
|
singers: string
|
||||||
|
status: 'queued' | 'resolving' | 'downloading' | 'done' | 'error' | 'cancelled'
|
||||||
|
downloaded: number
|
||||||
|
total: number
|
||||||
|
message?: string
|
||||||
|
/** 实际解析出的音质档位(start 事件回传);请求档位(如 "最高")在任务级 task.quality */
|
||||||
|
quality?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 音乐下载任务(musicdl 引擎) */
|
||||||
|
export interface MusicDownloadTask {
|
||||||
|
taskId: string
|
||||||
|
engine: 'musicdl' | 'rust'
|
||||||
|
status: 'downloading' | 'cancelling' | 'done' | 'error' | 'cancelled' | 'interrupted'
|
||||||
|
doneCount: number
|
||||||
|
songs: MusicDownloadSongState[]
|
||||||
|
/** 完整歌曲数据(localStorage 持久化,用于"重新下载") */
|
||||||
|
songsData: MusicSong[]
|
||||||
|
/** 下载目录(打开文件夹用) */
|
||||||
|
savedir?: string
|
||||||
|
/** 本次下载的目标音质 label("" 表示最高),用于任务标题展示 */
|
||||||
|
quality?: string
|
||||||
|
errorMessage?: string
|
||||||
|
createdAt: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 运行时安装进度事件负载(事件类型非 specta 生成范围,本地定义) */
|
||||||
|
export interface MusicInstallProgress {
|
||||||
|
stage: string
|
||||||
|
percent: number
|
||||||
|
downloadedBytes: number
|
||||||
|
totalBytes: number | null
|
||||||
|
message: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 搜索返回(bridge search 结果结构) */
|
||||||
|
export interface MusicSearchPayload {
|
||||||
|
results: Record<string, MusicSong[]>
|
||||||
|
total: number
|
||||||
|
sources: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 桥接 ping 返回 */
|
||||||
|
export interface MusicPingPayload {
|
||||||
|
version: string
|
||||||
|
python: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const logger = createLogger('music')
|
||||||
|
|
||||||
|
export const useMusicStore = defineStore('music', () => {
|
||||||
|
const settings = ref<MusicSettings | null>(null)
|
||||||
|
const env = ref<MusicEnvStatus | null>(null)
|
||||||
|
/** musicdl 已注册的全部搜索源(客户端名) */
|
||||||
|
const availableSources = ref<string[]>([])
|
||||||
|
|
||||||
|
// 搜索状态
|
||||||
|
const searching = ref(false)
|
||||||
|
const searchError = ref('')
|
||||||
|
const results = ref<Record<string, MusicSong[]>>({})
|
||||||
|
const resultTotal = ref(0)
|
||||||
|
/** 已执行过一次搜索/歌单解析(用于空结果时展示"未找到"而非初始引导空态) */
|
||||||
|
const searched = ref(false)
|
||||||
|
|
||||||
|
// 运行时安装状态
|
||||||
|
const installing = ref(false)
|
||||||
|
const installProgress = ref<MusicInstallProgress | null>(null)
|
||||||
|
const installError = ref('')
|
||||||
|
let progressUnlisten: UnlistenFn | null = null
|
||||||
|
|
||||||
|
async function init() {
|
||||||
|
restoreTasks()
|
||||||
|
await Promise.all([loadSettings(), refreshEnv()])
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadSettings() {
|
||||||
|
settings.value = await commands.musicGetSettings()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 保存设置(调用方先修改 settings 再调用;前端用 400ms debounce) */
|
||||||
|
async function saveSettings() {
|
||||||
|
if (!settings.value) return
|
||||||
|
await commands.musicSaveSettings(settings.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshEnv() {
|
||||||
|
env.value = await commands.musicEnvStatus()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadSources() {
|
||||||
|
try {
|
||||||
|
const v = (await invoke('music_get_sources')) as { sources: string[] }
|
||||||
|
availableSources.value = v.sources ?? []
|
||||||
|
} catch (e) {
|
||||||
|
logger.error(`加载音乐源失败: ${e}`)
|
||||||
|
availableSources.value = []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pingBridge(): Promise<MusicPingPayload> {
|
||||||
|
return (await invoke('music_ping')) as MusicPingPayload
|
||||||
|
}
|
||||||
|
|
||||||
|
async function search(keyword: string, sources: string[]) {
|
||||||
|
searching.value = true
|
||||||
|
searchError.value = ''
|
||||||
|
try {
|
||||||
|
const v = (await invoke('music_search', { keyword, sources })) as MusicSearchPayload
|
||||||
|
results.value = v.results ?? {}
|
||||||
|
resultTotal.value = v.total ?? 0
|
||||||
|
searched.value = true
|
||||||
|
} catch (e) {
|
||||||
|
searchError.value = typeof e === 'string' ? e : JSON.stringify(e)
|
||||||
|
throw e
|
||||||
|
} finally {
|
||||||
|
searching.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 歌单解析 =====
|
||||||
|
const parsing = ref(false)
|
||||||
|
const parseError = ref('')
|
||||||
|
|
||||||
|
/** 解析歌单链接,结果以首个歌曲来源为键写入 results(与搜索共用展示/下载) */
|
||||||
|
async function parsePlaylist(url: string, sources: string[]) {
|
||||||
|
parsing.value = true
|
||||||
|
parseError.value = ''
|
||||||
|
try {
|
||||||
|
const v = (await invoke('music_parse_playlist', { url, sources })) as {
|
||||||
|
songs: MusicSong[]
|
||||||
|
count: number
|
||||||
|
}
|
||||||
|
const count = v.count ?? 0
|
||||||
|
searched.value = true
|
||||||
|
if (count > 0) {
|
||||||
|
const srcKey = v.songs[0]?.source ?? 'playlist'
|
||||||
|
results.value = { [srcKey]: v.songs }
|
||||||
|
resultTotal.value = count
|
||||||
|
} else {
|
||||||
|
results.value = {}
|
||||||
|
resultTotal.value = 0
|
||||||
|
}
|
||||||
|
return count
|
||||||
|
} catch (e) {
|
||||||
|
parseError.value = typeof e === 'string' ? e : JSON.stringify(e)
|
||||||
|
throw e
|
||||||
|
} finally {
|
||||||
|
parsing.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 下载任务 =====
|
||||||
|
const tasks = ref<MusicDownloadTask[]>([])
|
||||||
|
let downloadUnlisten: UnlistenFn | null = null
|
||||||
|
|
||||||
|
// 任务历史持久化(localStorage,应用重启后保留记录;恢复时不尝试续传)
|
||||||
|
const TASKS_KEY = 'thing.music.tasks'
|
||||||
|
const MAX_TASKS = 30
|
||||||
|
let persistTimer: ReturnType<typeof setTimeout> | null = null
|
||||||
|
function persistTasks() {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(TASKS_KEY, JSON.stringify(tasks.value.slice(0, MAX_TASKS)))
|
||||||
|
} catch {
|
||||||
|
// localStorage 不可用/超限时静默降级(仅影响历史记录)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function restoreTasks() {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(TASKS_KEY)
|
||||||
|
if (!raw) return
|
||||||
|
const arr = JSON.parse(raw) as MusicDownloadTask[]
|
||||||
|
if (!Array.isArray(arr)) return
|
||||||
|
for (const t of arr) {
|
||||||
|
// 重启后桥接已无下载状态:残留的"下载中"统一标记为中断;
|
||||||
|
// "取消中"表明用户已请求取消,落定为已取消
|
||||||
|
if (t.status === 'downloading') t.status = 'interrupted'
|
||||||
|
else if (t.status === 'cancelling') t.status = 'cancelled'
|
||||||
|
if (!Array.isArray(t.songs)) t.songs = []
|
||||||
|
if (!Array.isArray(t.songsData)) t.songsData = []
|
||||||
|
}
|
||||||
|
tasks.value = arr.slice(0, MAX_TASKS)
|
||||||
|
} catch {
|
||||||
|
// 数据损坏则丢弃历史
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 仅在结构性变化(任务增删 / 任务状态 / 完成数)时持久化:
|
||||||
|
// 用轻量签名代替深度 watch,避免下载进度事件(每 300ms 修改 downloaded)
|
||||||
|
// 触发 30 个任务(含 songsData)的全量 JSON 序列化
|
||||||
|
const tasksSignature = computed(
|
||||||
|
() => tasks.value.map((t) => `${t.taskId}:${t.status}:${t.doneCount}`).join('|')
|
||||||
|
)
|
||||||
|
watch(
|
||||||
|
tasksSignature,
|
||||||
|
() => {
|
||||||
|
if (persistTimer) clearTimeout(persistTimer)
|
||||||
|
persistTimer = setTimeout(persistTasks, 400)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
async function ensureDownloadListener() {
|
||||||
|
if (downloadUnlisten) return
|
||||||
|
downloadUnlisten = await listen<MusicDownloadEvent>('music-download-event', (e) => {
|
||||||
|
handleDownloadEvent(e.payload)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleDownloadEvent(ev: MusicDownloadEvent) {
|
||||||
|
if (ev.type === 'bridge-stopped') {
|
||||||
|
// 桥接进程被停止:活动任务标记为中断;取消中的任务落定为已取消
|
||||||
|
for (const t of tasks.value) {
|
||||||
|
if (t.status === 'downloading') t.status = 'interrupted'
|
||||||
|
else if (t.status === 'cancelling') t.status = 'cancelled'
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!ev.taskId) return
|
||||||
|
const task = tasks.value.find((t) => t.taskId === ev.taskId)
|
||||||
|
if (!task) return
|
||||||
|
const type = ev.type
|
||||||
|
if (type === 'resolving') {
|
||||||
|
// 懒解析:下载 worker 正在解析真实下载链接(第三方 API + 官方音质阶梯)
|
||||||
|
const st = task.songs.find((s) => s.key === ev.key)
|
||||||
|
if (st) {
|
||||||
|
st.status = 'resolving'
|
||||||
|
st.songName = ev.songName ?? st.songName
|
||||||
|
st.singers = ev.singers ?? st.singers
|
||||||
|
}
|
||||||
|
if (task.status !== 'cancelling') task.status = 'downloading'
|
||||||
|
} else if (type === 'start') {
|
||||||
|
const st = task.songs.find((s) => s.key === ev.key)
|
||||||
|
if (st) {
|
||||||
|
st.status = 'downloading'
|
||||||
|
st.songName = ev.songName ?? st.songName
|
||||||
|
st.singers = ev.singers ?? st.singers
|
||||||
|
st.total = ev.total ?? st.total
|
||||||
|
st.quality = ev.quality ?? st.quality
|
||||||
|
}
|
||||||
|
// 取消请求后桥接仍可能推送在途歌曲的 start 事件,不覆盖「取消中」状态
|
||||||
|
if (task.status !== 'cancelling') task.status = 'downloading'
|
||||||
|
} else if (type === 'progress') {
|
||||||
|
const st = task.songs.find((s) => s.key === ev.key)
|
||||||
|
if (st) {
|
||||||
|
st.downloaded = ev.downloaded ?? 0
|
||||||
|
st.total = ev.total ?? st.total
|
||||||
|
}
|
||||||
|
} else if (type === 'done') {
|
||||||
|
const st = task.songs.find((s) => s.key === ev.key)
|
||||||
|
if (st) {
|
||||||
|
st.status = 'done'
|
||||||
|
st.downloaded = st.total || st.downloaded
|
||||||
|
}
|
||||||
|
task.doneCount++
|
||||||
|
} else if (type === 'error') {
|
||||||
|
const st = task.songs.find((s) => s.key === ev.key)
|
||||||
|
if (st) {
|
||||||
|
st.status = 'error'
|
||||||
|
st.message = ev.message
|
||||||
|
} else if (ev.key === undefined) {
|
||||||
|
// 任务级错误(worker 初始化失败/监督线程异常):桥接不会再发 finished,
|
||||||
|
// 此处直接落定最终状态,避免任务永久停留在「下载中」
|
||||||
|
task.errorMessage = ev.message
|
||||||
|
task.status = task.status === 'cancelling' ? 'cancelled' : 'error'
|
||||||
|
}
|
||||||
|
} else if (type === 'cancelled') {
|
||||||
|
const st = task.songs.find((s) => s.key === ev.key)
|
||||||
|
if (st) st.status = 'cancelled'
|
||||||
|
} else if (type === 'finished') {
|
||||||
|
const anyError = task.songs.some((s) => s.status === 'error')
|
||||||
|
const anyCancelled = task.songs.some((s) => s.status === 'cancelled')
|
||||||
|
task.status = anyError ? 'error' : anyCancelled ? 'cancelled' : 'done'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 清洗文件名中的 Windows 非法字符(\ / : * ? " < > | 及控制字符),并去掉结尾空格/点 */
|
||||||
|
function sanitizeFilename(name: string): string {
|
||||||
|
return (
|
||||||
|
name
|
||||||
|
.replace(/[\\/:*?"<>|\x00-\x1f]/g, '')
|
||||||
|
.replace(/\s+/g, ' ')
|
||||||
|
.trim()
|
||||||
|
.replace(/[. ]+$/, '') || 'music'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 懒解析:解析单首歌曲的真实下载链接(试听前调用),成功后原地更新
|
||||||
|
* 搜索结果并返回带链接的最新歌曲对象;失败返回 null */
|
||||||
|
async function resolveSong(source: string, index: number): Promise<MusicSong | null> {
|
||||||
|
const song = results.value[source]?.[index]
|
||||||
|
if (!song) return null
|
||||||
|
if (song.downloadUrl) return song
|
||||||
|
if (!song.rawSearch) return null
|
||||||
|
const v = (await invoke('music_resolve', { song })) as {
|
||||||
|
songs: (MusicSong | null)[]
|
||||||
|
}
|
||||||
|
const resolved = v.songs?.[0]
|
||||||
|
if (!resolved?.downloadUrl) return null
|
||||||
|
// 原地更新(索引未变,key 稳定);保留 rawSearch 供后续重新解析
|
||||||
|
if (results.value[source]?.[index] === song) {
|
||||||
|
results.value[source][index] = { ...song, ...resolved }
|
||||||
|
}
|
||||||
|
return resolved
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 启动下载。engine='rust' 时交给下载器模块(任务在其列表中管理),返回跳过的无链接歌曲数;
|
||||||
|
* 否则走 musicdl 桥接,返回 0 */
|
||||||
|
async function startDownload(
|
||||||
|
songs: MusicSong[],
|
||||||
|
opts: {
|
||||||
|
savedir: string
|
||||||
|
lyric: boolean
|
||||||
|
cover: boolean
|
||||||
|
proxyUrl: string
|
||||||
|
engine: string
|
||||||
|
maxConcurrent: number
|
||||||
|
/** 目标音质 label("" 表示最高);解析下载时按「≤所选最优档」封顶 */
|
||||||
|
quality?: string
|
||||||
|
}
|
||||||
|
): Promise<number> {
|
||||||
|
if (songs.length === 0) return 0
|
||||||
|
await ensureDownloadListener()
|
||||||
|
const quality = opts.quality ?? ''
|
||||||
|
|
||||||
|
if (opts.engine === 'rust') {
|
||||||
|
// 懒解析歌曲先批量解析出真实链接(桥接内并行),再交给下载器模块
|
||||||
|
const lazy = songs.filter((s) => !s.downloadUrl && s.rawSearch)
|
||||||
|
if (lazy.length > 0) {
|
||||||
|
try {
|
||||||
|
const v = (await invoke('music_resolve', { songs: lazy, quality })) as {
|
||||||
|
songs: (MusicSong | null)[]
|
||||||
|
}
|
||||||
|
// 返回与输入顺序对齐,失败位为 null
|
||||||
|
v.songs?.forEach((r, i) => {
|
||||||
|
if (r && lazy[i]) Object.assign(lazy[i], r)
|
||||||
|
})
|
||||||
|
} catch (e) {
|
||||||
|
logger.error(`批量解析下载链接失败: ${e}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let skipped = 0
|
||||||
|
for (const song of songs) {
|
||||||
|
if (!song.downloadUrl) {
|
||||||
|
skipped++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const ext = (song.ext ?? '').replace(/[\\/:*?"<>|\x00-\x1f]/g, '')
|
||||||
|
const raw = `${song.songName ?? 'music'}${ext ? '.' + ext : ''}`
|
||||||
|
try {
|
||||||
|
await commands.downloaderAddTask(
|
||||||
|
song.downloadUrl,
|
||||||
|
sanitizeFilename(raw),
|
||||||
|
opts.savedir,
|
||||||
|
song.defaultDownloadHeaders ?? null,
|
||||||
|
true,
|
||||||
|
null
|
||||||
|
)
|
||||||
|
} catch (e) {
|
||||||
|
logger.error(`下载失败 ${song.songName}: ${e}`)
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return skipped
|
||||||
|
}
|
||||||
|
|
||||||
|
const taskId = crypto.randomUUID()
|
||||||
|
const task: MusicDownloadTask = {
|
||||||
|
taskId,
|
||||||
|
engine: 'musicdl',
|
||||||
|
status: 'downloading',
|
||||||
|
doneCount: 0,
|
||||||
|
createdAt: Date.now(),
|
||||||
|
songsData: songs,
|
||||||
|
savedir: opts.savedir,
|
||||||
|
quality,
|
||||||
|
songs: songs.map((s, idx) => ({
|
||||||
|
key: `${s.source ?? ''}|${idx}`,
|
||||||
|
songName: s.songName ?? '',
|
||||||
|
singers: s.singers ?? '',
|
||||||
|
status: 'queued' as const,
|
||||||
|
downloaded: 0,
|
||||||
|
total: s.fileSizeBytes ?? 0
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
tasks.value.unshift(task)
|
||||||
|
if (tasks.value.length > 30) tasks.value.length = 30
|
||||||
|
try {
|
||||||
|
await invoke('music_download', {
|
||||||
|
taskId,
|
||||||
|
// 有 rawSearch 时丢弃搜索阶段的 downloadUrl(CDN 链接有时效,
|
||||||
|
// 交给桥接在下载 worker 里重新解析,顺带修复"隔夜链接过期"问题)
|
||||||
|
songs: songs.map((s) => (s.rawSearch ? { ...s, downloadUrl: null } : s)),
|
||||||
|
savedir: opts.savedir,
|
||||||
|
lyric: opts.lyric,
|
||||||
|
cover: opts.cover,
|
||||||
|
proxyUrl: opts.proxyUrl,
|
||||||
|
maxConcurrent: opts.maxConcurrent,
|
||||||
|
quality
|
||||||
|
})
|
||||||
|
} catch (e) {
|
||||||
|
task.status = 'error'
|
||||||
|
task.errorMessage = String(e)
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
async function cancelDownload(taskId: string) {
|
||||||
|
const task = tasks.value.find((t) => t.taskId === taskId)
|
||||||
|
if (!task || (task.status !== 'downloading' && task.status !== 'cancelling')) return
|
||||||
|
// 队列级取消:当前歌曲会完成,其余标记取消;最终状态由 finished 事件落定,
|
||||||
|
// 此处先置「取消中」防止用户在剩余歌曲停止前误点「重新下载」产生重复任务
|
||||||
|
task.status = 'cancelling'
|
||||||
|
try {
|
||||||
|
await invoke('music_download_cancel', { taskId })
|
||||||
|
} catch {
|
||||||
|
// 桥接不可用(进程已死,无后台下载)→ 直接落定为已取消,避免卡在取消中
|
||||||
|
if (task.status === 'cancelling') task.status = 'cancelled'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeTask(taskId: string) {
|
||||||
|
// 下载中/取消中的任务先请求队列级取消,防止移除后后台仍在下载
|
||||||
|
const task = tasks.value.find((t) => t.taskId === taskId)
|
||||||
|
if (task && (task.status === 'downloading' || task.status === 'cancelling')) {
|
||||||
|
invoke('music_download_cancel', { taskId }).catch(() => {})
|
||||||
|
}
|
||||||
|
tasks.value = tasks.value.filter((t) => t.taskId !== taskId)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 重新下载:用任务内保存的完整歌曲数据重新发起(error/cancelled/interrupted 状态可用) */
|
||||||
|
async function redownloadTask(taskId: string) {
|
||||||
|
const task = tasks.value.find((t) => t.taskId === taskId)
|
||||||
|
if (
|
||||||
|
!task ||
|
||||||
|
task.status === 'downloading' ||
|
||||||
|
task.status === 'cancelling' ||
|
||||||
|
task.songsData.length === 0
|
||||||
|
) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const s = settings.value
|
||||||
|
if (!s) return
|
||||||
|
// 代理 URL:惰性读取代理模块设置(避免 store 初始化时跨 store 依赖)
|
||||||
|
let proxy = ''
|
||||||
|
if (s.useProxy) {
|
||||||
|
const port = useProxyStore().settings?.mixedPort
|
||||||
|
proxy = port ? `http://127.0.0.1:${port}` : ''
|
||||||
|
}
|
||||||
|
await startDownload(task.songsData, {
|
||||||
|
savedir: s.savedir,
|
||||||
|
lyric: s.lyricDownload,
|
||||||
|
cover: s.coverDownload,
|
||||||
|
proxyUrl: proxy,
|
||||||
|
engine: s.downloadEngine,
|
||||||
|
maxConcurrent: s.maxConcurrent,
|
||||||
|
quality: s.defaultDownloadQuality ?? ''
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async function installRuntime() {
|
||||||
|
if (installing.value) return
|
||||||
|
installing.value = true
|
||||||
|
installError.value = ''
|
||||||
|
installProgress.value = null
|
||||||
|
if (!progressUnlisten) {
|
||||||
|
progressUnlisten = await listen<MusicInstallProgress>(
|
||||||
|
'music-runtime-install-progress',
|
||||||
|
(e) => {
|
||||||
|
installProgress.value = e.payload
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
env.value = await commands.musicInstallRuntime()
|
||||||
|
} catch (e) {
|
||||||
|
// 保留失败原因供设置页面板展示;进度停在最后事件值,需清掉避免误导
|
||||||
|
installError.value = typeof e === 'string' ? e : JSON.stringify(e)
|
||||||
|
throw e
|
||||||
|
} finally {
|
||||||
|
installing.value = false
|
||||||
|
if (progressUnlisten) {
|
||||||
|
progressUnlisten()
|
||||||
|
progressUnlisten = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancelInstall() {
|
||||||
|
commands.musicCancelRuntimeInstall().catch(() => {})
|
||||||
|
}
|
||||||
|
|
||||||
|
async function stopBridge() {
|
||||||
|
await commands.musicStopBridge()
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
settings,
|
||||||
|
env,
|
||||||
|
availableSources,
|
||||||
|
searching,
|
||||||
|
searchError,
|
||||||
|
searched,
|
||||||
|
parsing,
|
||||||
|
parseError,
|
||||||
|
results,
|
||||||
|
resultTotal,
|
||||||
|
installing,
|
||||||
|
installProgress,
|
||||||
|
installError,
|
||||||
|
tasks,
|
||||||
|
init,
|
||||||
|
loadSettings,
|
||||||
|
saveSettings,
|
||||||
|
refreshEnv,
|
||||||
|
loadSources,
|
||||||
|
pingBridge,
|
||||||
|
search,
|
||||||
|
parsePlaylist,
|
||||||
|
resolveSong,
|
||||||
|
startDownload,
|
||||||
|
cancelDownload,
|
||||||
|
removeTask,
|
||||||
|
redownloadTask,
|
||||||
|
installRuntime,
|
||||||
|
cancelInstall,
|
||||||
|
stopBridge
|
||||||
|
}
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user