Compare commits

..
14 Commits
Author SHA1 Message Date
Ultradesu 1ab53e3898 Fixed ytdl retries
Build and Publish / Build and Publish Docker Image (push) Successful in 3m40s
2026-08-14 12:56:03 +01:00
Ultradesu 0b32d7e813 Fixed ytdl retries
Build and Publish / Build and Publish Docker Image (push) Successful in 3m40s
2026-08-14 12:18:42 +01:00
Ultradesu 5402d9595d Added socks proxy, reworked download manager configuration
Build and Publish / Build and Publish Docker Image (push) Successful in 3m41s
2026-08-14 10:54:56 +01:00
Aleksandr Bogomiakov 9d9edcfec8 Fix Docker build
Build and Publish / Build and Publish Docker Image (push) Successful in 4m4s
2026-08-14 01:59:16 +01:00
Aleksandr Bogomiakov 943191a0ff Added youtube import. Reworked Download Manager
Build and Publish / Build and Publish Docker Image (push) Successful in 3m52s
2026-08-14 01:21:51 +01:00
Ultradesu 2b254f417f Updated readme 2026-08-12 01:41:00 +01:00
Ultradesu 69883af8bd Reworked settings page
Build and Publish / Build and Publish Docker Image (push) Successful in 3m28s
2026-08-11 12:26:16 +01:00
Aleksandr Bogomiakov 6f337ee626 Add DHT routing for similarity search
Build and Publish / Build and Publish Docker Image (push) Successful in 3m30s
2026-08-10 19:54:40 +01:00
Aleksandr Bogomiakov 77cbb62d84 Added similarity search
Build and Publish / Build and Publish Docker Image (push) Successful in 3m29s
2026-08-10 01:44:40 +01:00
Ultradesu 05d68724f3 Fixed invite logic to be lightweight
Build and Publish / Build and Publish Docker Image (push) Successful in 4m13s
2026-07-29 14:21:32 +01:00
Ultradesu d71845509d Bump protocols. Added proto status
Build and Publish / Build and Publish Docker Image (push) Successful in 6m1s
2026-07-28 23:01:57 +01:00
Ultradesu 4efcfdc539 Bump protocols. Added proto status
Build and Publish / Build and Publish Docker Image (push) Successful in 5m25s
2026-07-28 22:46:43 +01:00
Ultradesu d61d7a6bac Bump protocols. Added proto status
Build and Publish / Build and Publish Docker Image (push) Successful in 5m13s
2026-07-28 22:20:33 +01:00
Ultradesu cad8b2280f Added favicon 2026-07-28 21:27:48 +01:00
34 changed files with 10776 additions and 614 deletions
+2
View File
@@ -3,3 +3,5 @@
/.claude /.claude
/media /media
/federation /federation
/similarity-models
/federation-cache
Generated
+620 -7
View File
@@ -159,6 +159,12 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "anymap3"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb5dfbc6d8d2675589ccbe4d0fd61df2419075625f8c1a62325e718e2b0049f9"
[[package]] [[package]]
name = "arc-swap" name = "arc-swap"
version = "1.9.2" version = "1.9.2"
@@ -488,6 +494,24 @@ dependencies = [
"virtue", "virtue",
] ]
[[package]]
name = "bit-set"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d"
dependencies = [
"bit-vec",
]
[[package]]
name = "bit-vec"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
dependencies = [
"serde",
]
[[package]] [[package]]
name = "bitflags" name = "bitflags"
version = "1.3.2" version = "1.3.2"
@@ -1069,6 +1093,16 @@ dependencies = [
"crossbeam-utils", "crossbeam-utils",
] ]
[[package]]
name = "crossbeam-deque"
version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb"
dependencies = [
"crossbeam-epoch",
"crossbeam-utils",
]
[[package]] [[package]]
name = "crossbeam-epoch" name = "crossbeam-epoch"
version = "0.9.20" version = "0.9.20"
@@ -1093,6 +1127,12 @@ version = "0.8.22"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"
[[package]]
name = "crunchy"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
[[package]] [[package]]
name = "crypto-bigint" name = "crypto-bigint"
version = "0.5.5" version = "0.5.5"
@@ -1284,6 +1324,12 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "dasp_sample"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f"
[[package]] [[package]]
name = "data-encoding" name = "data-encoding"
version = "2.11.0" version = "2.11.0"
@@ -1341,6 +1387,17 @@ dependencies = [
"serde_core", "serde_core",
] ]
[[package]]
name = "derive-new"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2cdc8d50f426189eef89dac62fabfa0abb27d5cc008f25bf4156a0203325becc"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]] [[package]]
name = "derive_builder" name = "derive_builder"
version = "0.20.2" version = "0.20.2"
@@ -1493,12 +1550,30 @@ version = "0.15.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b"
[[package]]
name = "downcast-rs"
version = "2.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc"
[[package]] [[package]]
name = "dyn-clone" name = "dyn-clone"
version = "1.0.20" version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
[[package]]
name = "dyn-eq"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c2d035d21af5cde1a6f5c7b444a5bf963520a9f142e5d06931178433d7d5388"
[[package]]
name = "dyn-hash"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fdab65db9274e0168143841eb8f864a0a21f8b1b8d2ba6812bbe6024346e99e"
[[package]] [[package]]
name = "ecdsa" name = "ecdsa"
version = "0.16.9" version = "0.16.9"
@@ -1641,6 +1716,17 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "erased-serde"
version = "0.4.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec"
dependencies = [
"serde",
"serde_core",
"typeid",
]
[[package]] [[package]]
name = "errno" name = "errno"
version = "0.3.14" version = "0.3.14"
@@ -1707,8 +1793,9 @@ dependencies = [
[[package]] [[package]]
name = "federation-net" name = "federation-net"
version = "0.1.0" version = "0.3.0"
source = "git+https://gt.hexor.cy/ab/frid.git#8de7d1292708fa0b225e5a4a9d5ab4f0676202d3" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3e690b370c505d153bef214b21a8f2aa55d667367ac1e16bde8bc0de88963c2"
dependencies = [ dependencies = [
"blake3", "blake3",
"data-encoding", "data-encoding",
@@ -1747,6 +1834,16 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24" checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24"
[[package]]
name = "filetime"
version = "0.2.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
dependencies = [
"cfg-if",
"libc",
]
[[package]] [[package]]
name = "find-msvc-tools" name = "find-msvc-tools"
version = "0.1.9" version = "0.1.9"
@@ -1763,6 +1860,12 @@ dependencies = [
"miniz_oxide", "miniz_oxide",
] ]
[[package]]
name = "float-ord"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ce81f49ae8a0482e4c55ea62ebbd7e5a686af544c00b9d090bba3ff9be97b3d"
[[package]] [[package]]
name = "flume" name = "flume"
version = "0.11.1" version = "0.11.1"
@@ -1835,7 +1938,7 @@ checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
[[package]] [[package]]
name = "furumusic" name = "furumusic"
version = "0.9.5" version = "0.10.4"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"async-stream", "async-stream",
@@ -1847,14 +1950,18 @@ dependencies = [
"cot", "cot",
"croner", "croner",
"encoding_rs", "encoding_rs",
"futures-util",
"id3", "id3",
"image", "image",
"libc",
"librqbit", "librqbit",
"md-5", "md-5",
"music-dht", "music-dht",
"openidconnect", "openidconnect",
"postcard", "postcard",
"reqwest 0.12.28", "reqwest 0.12.28",
"rodio",
"rustfft",
"schemars 0.9.0", "schemars 0.9.0",
"serde", "serde",
"serde_json", "serde_json",
@@ -1863,9 +1970,11 @@ dependencies = [
"symphonia", "symphonia",
"tokio", "tokio",
"tokio-cron-scheduler", "tokio-cron-scheduler",
"tokio-util",
"tower", "tower",
"tracing", "tracing",
"tracing-subscriber", "tracing-subscriber",
"tract-onnx",
"uuid", "uuid",
] ]
@@ -2190,6 +2299,18 @@ dependencies = [
"tracing", "tracing",
] ]
[[package]]
name = "half"
version = "2.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
dependencies = [
"cfg-if",
"crunchy",
"num-traits",
"zerocopy",
]
[[package]] [[package]]
name = "hash32" name = "hash32"
version = "0.2.1" version = "0.2.1"
@@ -2235,6 +2356,8 @@ dependencies = [
"allocator-api2", "allocator-api2",
"equivalent", "equivalent",
"foldhash 0.2.0", "foldhash 0.2.0",
"serde",
"serde_core",
] ]
[[package]] [[package]]
@@ -2798,6 +2921,15 @@ dependencies = [
"smallvec", "smallvec",
] ]
[[package]]
name = "inventory"
version = "0.3.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4f0c30c76f2f4ccee3fe55a2435f691ca00c0e4bd87abe4f4a851b1d4dac39b"
dependencies = [
"rustversion",
]
[[package]] [[package]]
name = "ipconfig" name = "ipconfig"
version = "0.3.4" version = "0.3.4"
@@ -3490,6 +3622,12 @@ dependencies = [
"tracing", "tracing",
] ]
[[package]]
name = "maplit"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d"
[[package]] [[package]]
name = "matchers" name = "matchers"
version = "0.2.0" version = "0.2.0"
@@ -3505,6 +3643,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 = "matrixmultiply"
version = "0.3.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7"
dependencies = [
"autocfg",
"rawpointer",
]
[[package]] [[package]]
name = "md-5" name = "md-5"
version = "0.10.6" version = "0.10.6"
@@ -3530,6 +3678,12 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "memo-map"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38d1115007560874e373613744c6fba374c17688327a71c1476d1a5954cc857b"
[[package]] [[package]]
name = "mime" name = "mime"
version = "0.3.17" version = "0.3.17"
@@ -3546,6 +3700,16 @@ dependencies = [
"unicase", "unicase",
] ]
[[package]]
name = "minijinja"
version = "2.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42d74234349a775546a83af0f0c0c0e3a73227dee4950a542cda81a47240b3e6"
dependencies = [
"memo-map",
"serde",
]
[[package]] [[package]]
name = "miniz_oxide" name = "miniz_oxide"
version = "0.8.9" version = "0.8.9"
@@ -3613,8 +3777,9 @@ dependencies = [
[[package]] [[package]]
name = "music-dht" name = "music-dht"
version = "0.2.0" version = "0.4.0"
source = "git+https://gt.hexor.cy/ab/frid.git#8de7d1292708fa0b225e5a4a9d5ab4f0676202d3" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c5b429b90a8f1b0980b3a35a6fa5445d7a275c737eb04db18db4d7f14c81478"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"blake3", "blake3",
@@ -3702,6 +3867,21 @@ dependencies = [
"tempfile", "tempfile",
] ]
[[package]]
name = "ndarray"
version = "0.17.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "520080814a7a6b4a6e9070823bb24b4531daac8c4627e08ba5de8c5ef2f2752d"
dependencies = [
"matrixmultiply",
"num-complex 0.4.6",
"num-integer",
"num-traits",
"portable-atomic",
"portable-atomic-util",
"rawpointer",
]
[[package]] [[package]]
name = "ndk-context" name = "ndk-context"
version = "0.1.1" version = "0.1.1"
@@ -3833,6 +4013,24 @@ dependencies = [
"winapi", "winapi",
] ]
[[package]]
name = "nom"
version = "8.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"
dependencies = [
"memchr",
]
[[package]]
name = "nom-language"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2de2bc5b451bfedaef92c90b8939a8fff5770bdcc1fafd6239d086aab8fa6b29"
dependencies = [
"nom",
]
[[package]] [[package]]
name = "nonzero_ext" name = "nonzero_ext"
version = "0.3.0" version = "0.3.0"
@@ -3916,10 +4114,20 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8536030f9fea7127f841b45bb6243b27255787fb4eb83958aa1ef9d2fdc0c36" checksum = "b8536030f9fea7127f841b45bb6243b27255787fb4eb83958aa1ef9d2fdc0c36"
dependencies = [ dependencies = [
"num-complex", "num-complex 0.2.4",
"num-integer", "num-integer",
"num-iter", "num-iter",
"num-rational", "num-rational 0.2.4",
"num-traits",
]
[[package]]
name = "num-bigint"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
dependencies = [
"num-integer",
"num-traits", "num-traits",
] ]
@@ -3949,6 +4157,15 @@ dependencies = [
"num-traits", "num-traits",
] ]
[[package]]
name = "num-complex"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
dependencies = [
"num-traits",
]
[[package]] [[package]]
name = "num-conv" name = "num-conv"
version = "0.2.2" version = "0.2.2"
@@ -3996,6 +4213,17 @@ dependencies = [
"num-traits", "num-traits",
] ]
[[package]]
name = "num-rational"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
dependencies = [
"num-bigint",
"num-integer",
"num-traits",
]
[[package]] [[package]]
name = "num-traits" name = "num-traits"
version = "0.2.19" version = "0.2.19"
@@ -4350,6 +4578,12 @@ version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "pastey"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
[[package]] [[package]]
name = "pem-rfc7468" name = "pem-rfc7468"
version = "0.7.0" version = "0.7.0"
@@ -4560,6 +4794,15 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "portable-atomic-util"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618"
dependencies = [
"portable-atomic",
]
[[package]] [[package]]
name = "portmapper" name = "portmapper"
version = "0.19.1" version = "0.19.1"
@@ -4649,6 +4892,15 @@ dependencies = [
"num-traits", "num-traits",
] ]
[[package]]
name = "primal-check"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc0d895b311e3af9902528fbb8f928688abbd95872819320517cc24ca6b2bd08"
dependencies = [
"num-integer",
]
[[package]] [[package]]
name = "primeorder" name = "primeorder"
version = "0.13.6" version = "0.13.6"
@@ -4676,6 +4928,29 @@ dependencies = [
"unicode-ident", "unicode-ident",
] ]
[[package]]
name = "prost"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1"
dependencies = [
"bytes",
"prost-derive",
]
[[package]]
name = "prost-derive"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf"
dependencies = [
"anyhow",
"itertools 0.14.0",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]] [[package]]
name = "pxfm" name = "pxfm"
version = "0.1.30" version = "0.1.30"
@@ -4881,6 +5156,16 @@ version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "rand_distr"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d431c2703ccf129de4d45253c03f49ebb22b97d6ad79ee3ecfc7e3f4862c1d8"
dependencies = [
"num-traits",
"rand 0.10.2",
]
[[package]] [[package]]
name = "rand_pcg" name = "rand_pcg"
version = "0.10.2" version = "0.10.2"
@@ -4899,6 +5184,32 @@ dependencies = [
"bitflags 2.13.1", "bitflags 2.13.1",
] ]
[[package]]
name = "rawpointer"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"
[[package]]
name = "rayon"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
dependencies = [
"either",
"rayon-core",
]
[[package]]
name = "rayon-core"
version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
dependencies = [
"crossbeam-deque",
"crossbeam-utils",
]
[[package]] [[package]]
name = "redox_syscall" name = "redox_syscall"
version = "0.5.18" version = "0.5.18"
@@ -5097,6 +5408,18 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "rodio"
version = "0.22.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0a536bb79db59098ef71a4dd4246c02eb87b316deceb1b68e0cde7167ec01eb"
dependencies = [
"dasp_sample",
"num-rational 0.4.2",
"symphonia",
"thiserror 2.0.19",
]
[[package]] [[package]]
name = "rsa" name = "rsa"
version = "0.9.10" version = "0.9.10"
@@ -5152,6 +5475,20 @@ dependencies = [
"semver", "semver",
] ]
[[package]]
name = "rustfft"
version = "6.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21db5f9893e91f41798c88680037dba611ca6674703c1a18601b01a72c8adb89"
dependencies = [
"num-complex 0.4.6",
"num-integer",
"num-traits",
"primal-check",
"strength_reduce",
"transpose",
]
[[package]] [[package]]
name = "rustix" name = "rustix"
version = "1.1.4" version = "1.1.4"
@@ -5252,6 +5589,19 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]]
name = "safetensors"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "79b079b829cb27a1c3c374341345ed2e8b2c0c839034522cee576c140bd7f846"
dependencies = [
"hashbrown 0.16.1",
"libc",
"serde",
"serde_json",
"tempfile",
]
[[package]] [[package]]
name = "same-file" name = "same-file"
version = "1.0.6" version = "1.0.6"
@@ -5261,6 +5611,15 @@ dependencies = [
"winapi-util", "winapi-util",
] ]
[[package]]
name = "scan_fmt"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b53b0a5db882a8e2fdaae0a43f7b39e7e9082389e978398bdf223a55b581248"
dependencies = [
"regex",
]
[[package]] [[package]]
name = "schannel" name = "schannel"
version = "0.1.29" version = "0.1.29"
@@ -5994,6 +6353,22 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
[[package]]
name = "strength_reduce"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82"
[[package]]
name = "string-interner"
version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad3df9b59e2eded8d825c7c4363ad339a20fb6bc0b9a4778560f518f59910b15"
dependencies = [
"hashbrown 0.16.1",
"serde",
]
[[package]] [[package]]
name = "stringprep" name = "stringprep"
version = "0.1.5" version = "0.1.5"
@@ -6327,6 +6702,17 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
[[package]]
name = "tar"
version = "0.4.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
dependencies = [
"filetime",
"libc",
"xattr",
]
[[package]] [[package]]
name = "tempfile" name = "tempfile"
version = "3.27.0" version = "3.27.0"
@@ -6786,12 +7172,229 @@ dependencies = [
"tracing-log", "tracing-log",
] ]
[[package]]
name = "tract-core"
version = "0.23.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "608e176a669d5da02cccc92bbfe5ee4e57686ed8841022608a9eba014d3b7886"
dependencies = [
"anyhow",
"anymap3",
"bit-set",
"derive-new",
"downcast-rs",
"dyn-clone",
"dyn-eq",
"erased-serde",
"inventory",
"lazy_static",
"log",
"maplit",
"ndarray",
"num-complex 0.4.6",
"num-integer",
"num-traits",
"pastey",
"rustfft",
"serde",
"smallvec",
"tract-data",
"tract-linalg",
]
[[package]]
name = "tract-data"
version = "0.23.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "870236dd45aaeb1381023cb709a67ff14ece608ee0b37f99aa166d166db9b0d0"
dependencies = [
"anyhow",
"downcast-rs",
"dyn-clone",
"dyn-eq",
"dyn-hash",
"half",
"inventory",
"itertools 0.14.0",
"lazy_static",
"libm",
"maplit",
"ndarray",
"nom",
"nom-language",
"num-integer",
"num-traits",
"parking_lot",
"scan_fmt",
"smallvec",
"string-interner",
]
[[package]]
name = "tract-extra"
version = "0.23.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "effcae1ebfce133e8bf6c79ad31298cbee0a9eceb3e4642fe1d14cb54cca78e6"
dependencies = [
"tract-nnef",
"tract-pulse",
]
[[package]]
name = "tract-hir"
version = "0.23.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28783b2bb583177685f65016a866b01eb3d383bce4fa7ae1b9692b325b64449d"
dependencies = [
"derive-new",
"log",
"tract-core",
]
[[package]]
name = "tract-linalg"
version = "0.23.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3e01491f7360806ef061af4c016a2d0a801d586768896394a0b8a7d6872c2b0"
dependencies = [
"byteorder",
"cc",
"derive-new",
"downcast-rs",
"dyn-clone",
"dyn-eq",
"dyn-hash",
"half",
"lazy_static",
"log",
"minijinja",
"num-traits",
"pastey",
"scan_fmt",
"tract-data",
"walkdir",
]
[[package]]
name = "tract-nnef"
version = "0.23.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00417fabf01aeea7bc56107367862e5bb8da18c9ad850c9061d3823700479ecc"
dependencies = [
"byteorder",
"erased-serde",
"flate2",
"log",
"minijinja",
"nom",
"nom-language",
"safetensors",
"serde",
"serde_json",
"simd-adler32",
"tar",
"tract-core",
"walkdir",
]
[[package]]
name = "tract-onnx"
version = "0.23.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3215dd27bddd2a041a20fee750013b400135186d3485501c9274c755b19ceb0"
dependencies = [
"bytes",
"derive-new",
"dyn-eq",
"log",
"memmap2",
"num-integer",
"prost",
"smallvec",
"tract-extra",
"tract-hir",
"tract-nnef",
"tract-onnx-opl",
"tract-transformers",
]
[[package]]
name = "tract-onnx-opl"
version = "0.23.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44f549ad3f245c1c00ce710c66cc0e086be0b637f35934d37b655ff175e1ab3e"
dependencies = [
"dyn-eq",
"getrandom 0.4.3",
"log",
"rand 0.10.2",
"rand_distr",
"rustfft",
"tract-extra",
"tract-nnef",
]
[[package]]
name = "tract-pulse"
version = "0.23.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a164e22e96ab9b5c90458fa270700570d87963e3dec9ccaac1ab18d9fa763ce2"
dependencies = [
"downcast-rs",
"dyn-eq",
"erased-serde",
"lazy_static",
"log",
"serde",
"tract-pulse-opl",
"tract-transformers",
]
[[package]]
name = "tract-pulse-opl"
version = "0.23.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65418f9e93e0af0d567f4f2f1bf2309b53930fa2543c635a69fda10c87a04987"
dependencies = [
"downcast-rs",
"dyn-eq",
"lazy_static",
"tract-nnef",
]
[[package]]
name = "tract-transformers"
version = "0.23.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8471ebf7f52d226552283d9130539595540c28ed41b8e032df3830507d3ccdd5"
dependencies = [
"float-ord",
"rayon",
"tract-nnef",
]
[[package]]
name = "transpose"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e"
dependencies = [
"num-integer",
"strength_reduce",
]
[[package]] [[package]]
name = "try-lock" name = "try-lock"
version = "0.2.5" 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 = "typeid"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"
[[package]] [[package]]
name = "typenum" name = "typenum"
version = "1.20.1" version = "1.20.1"
@@ -7557,6 +8160,16 @@ dependencies = [
"tap", "tap",
] ]
[[package]]
name = "xattr"
version = "1.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
dependencies = [
"libc",
"rustix",
]
[[package]] [[package]]
name = "xml-rs" name = "xml-rs"
version = "0.8.28" version = "0.8.28"
+10 -4
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "furumusic" name = "furumusic"
version = "0.9.6" version = "0.10.4"
edition = "2024" edition = "2024"
description = "Reusable web-app boilerplate: auth, OIDC/SSO, admin panel, user management, i18n, PostgreSQL" description = "Reusable web-app boilerplate: auth, OIDC/SSO, admin panel, user management, i18n, PostgreSQL"
@@ -12,8 +12,10 @@ cot = { version = "0.6.0", default-features = false, features = ["postgres", "js
schemars = { version = "0.9", features = ["derive"] } schemars = { version = "0.9", features = ["derive"] }
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
openidconnect = "4.0" openidconnect = "4.0"
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "json"] } reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "json", "stream"] }
tokio = { version = "1", features = ["sync", "fs", "io-util"] } tokio = { version = "1", features = ["sync", "fs", "io-util", "process"] }
tokio-util = "0.7"
libc = "0.2"
async-stream = "0.3" async-stream = "0.3"
bytes = "1" bytes = "1"
tower = "0.5" tower = "0.5"
@@ -31,6 +33,10 @@ md-5 = "0.10"
image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp", "gif", "bmp"] } image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp", "gif", "bmp"] }
sqlx = { version = "0.8", features = ["runtime-tokio-rustls", "postgres"] } sqlx = { version = "0.8", features = ["runtime-tokio-rustls", "postgres"] }
anyhow = "1.0" anyhow = "1.0"
futures-util = "0.3"
rodio = { version = "0.22.2", default-features = false, features = ["mp3", "flac", "vorbis", "wav", "symphonia-aac", "symphonia-isomp4", "symphonia-alac", "symphonia-adpcm", "symphonia-aiff", "symphonia-mkv", "symphonia-pcm"] }
rustfft = "6.4.1"
tract-onnx = "0.23.4"
tokio-cron-scheduler = "0.15" tokio-cron-scheduler = "0.15"
croner = "3" croner = "3"
async-trait = "0.1" async-trait = "0.1"
@@ -39,4 +45,4 @@ uuid = "1"
librqbit = { version = "8.1.1", features = ["disable-upload"] } librqbit = { version = "8.1.1", features = ["disable-upload"] }
# P2P federation: publishes the library into a shared DHT and serves audio / # P2P federation: publishes the library into a shared DHT and serves audio /
# catalogs to furumi peers (TUI clients) over the frid stack. # catalogs to furumi peers (TUI clients) over the frid stack.
music-dht = { git = "https://gt.hexor.cy/ab/frid.git" } music-dht = "0.4.0"
+13 -2
View File
@@ -1,4 +1,4 @@
FROM rust:1-slim AS builder FROM rust:1-bookworm AS builder
RUN apt-get update \ RUN apt-get update \
&& apt-get install -y --no-install-recommends pkg-config libssl-dev ca-certificates \ && apt-get install -y --no-install-recommends pkg-config libssl-dev ca-certificates \
@@ -14,14 +14,25 @@ COPY templates ./templates
RUN cargo build --release RUN cargo build --release
FROM denoland/deno:bin-2.8.3 AS deno
FROM debian:bookworm-slim FROM debian:bookworm-slim
ARG YT_DLP_VERSION=2026.07.04
RUN apt-get update \ RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates \ && apt-get install -y --no-install-recommends \
ca-certificates \
ffmpeg \
python3 \
python3-pip \
&& pip3 install --break-system-packages --no-cache-dir --disable-pip-version-check \
"yt-dlp[default]==${YT_DLP_VERSION}" \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
WORKDIR /data WORKDIR /data
COPY --from=builder /app/target/release/furumusic /usr/local/bin/furumusic COPY --from=builder /app/target/release/furumusic /usr/local/bin/furumusic
COPY --from=deno /deno /usr/local/bin/deno
EXPOSE 8000 EXPOSE 8000
CMD ["furumusic", "-l", "0.0.0.0:8000"] CMD ["furumusic", "-l", "0.0.0.0:8000"]
+125 -183
View File
@@ -1,201 +1,143 @@
# furumusic # Furumusic
Reusable web-app boilerplate: auth, OIDC/SSO, admin panel, user management, i18n, PostgreSQL. **Your library. Your users. Your network.**
Built with Rust ([cot](https://cot.rs) framework). Furumusic is a self-hosted, multi-user music server with a full web player and
support for the Furumi federated network. It turns a collection of music files
into a shared library that is available from any modern browser, while every
user keeps their own playlists, likes, listening history, and playback state.
## Quick start Music can be uploaded directly, imported from a `.torrent` file, or downloaded
from a magnet link. An optional AI-assisted import pipeline reads the available
tags and path information, reconstructs inconsistent metadata, finds artwork,
and organizes the result into artists, releases, and tracks. Uncertain matches
are kept for review instead of silently entering the library with bad data.
## Why Furumusic?
Furumusic is for a household, a small community, or anyone who wants one music
library without handing it to a subscription service. The server owns the
catalog and media files; the browser is only the player.
- one shared library with separate user accounts;
- a responsive web player with artists, releases, search, queue, and playlists;
- direct file uploads and imports from YouTube, torrent files, or magnet links;
- optional AI-assisted recognition and normalization of metadata;
- password login or OIDC/SSO with group-based access control;
- optional federation without a central catalog or search service;
- trusted-device pairing, playback handoff, and synchronization between Furumi
players;
- Last.fm scrobbling and similarity-based discovery when configured.
Furumusic does not include music. Import only media you are allowed to store and
share.
## Importing music
Users can add audio files from the web interface or ask the server to download
selected files from a torrent. Both routes feed the same import pipeline, so a
library remains consistent regardless of where its files came from.
The importer combines embedded tags, filenames, folder structure, and existing
catalog context. With an OpenAI-compatible language model configured, it can
normalize artist and release names, separate featured artists, recover track
numbers and release types, and flag ambiguous results for a user to approve.
Cover art is taken from nearby image files or embedded artwork when available.
The inbox and permanent library are separate directories. New files are first
processed in the inbox and are moved into the organized library only after
their metadata has been accepted.
## Federation
Federation is optional. Independent Furumusic and Furumi players that use the
same Network ID discover one another as a logical network. Each peer keeps its
own library and can continue working alone.
When federation is enabled, local and remote artists, releases, and tracks can
appear in the same search and library views. Missing audio is streamed from an
available peer and can optionally be retained locally. Similarity search also
stays decentralized: embeddings and exact ranking remain on the instance that
owns the music.
Trusted-device pairing is separate from public catalog discovery. It connects
a user's own Furumi players so likes, playlists, playback state, and control can
move between approved devices.
## Build and run
Furumusic requires PostgreSQL and a Rust toolchain with Rust 2024 edition
support. Create an empty database, provide its connection URL, and start the
server:
```bash ```bash
export FURU_DATABASE_URL=postgresql://user:pass@localhost/furumusic export FURU_DATABASE_URL='postgresql://furumusic:password@127.0.0.1/furumusic'
cargo run cargo run --release --locked
# Open http://localhost:8000/admin/setup to create the first admin account
``` ```
## Project structure Open <http://127.0.0.1:8000/admin/setup> to create the first administrator.
After setup, configure the inbox and library directories under **Admin →
Settings** before importing music.
To listen on another address or port:
```bash
cargo run --release --locked -- -l 0.0.0.0:8000
``` ```
Cargo.toml Project manifest and dependencies
build.rs Captures rustc version + target at compile time A Nix development shell is included for Linux and macOS:
src/
main.rs Entrypoint; HTTP router, login/logout handlers, tracing init ```bash
config.rs 3-tier config system (default → DB → env); FURU_* env vars nix develop
auth.rs Session auth, Role enum (Admin/User), login/logout/guards cargo run --locked
user.rs User + OidcLink DB models, CRUD, password hashing, migrations
oidc.rs OIDC/SSO flow: discovery, PKCE, token exchange, user provisioning
i18n/
mod.rs Language resolution (cookie → Accept-Language → default), extractor
phrases.rs All UI strings in English and Russian (translations! macro)
api/
mod.rs JSON API endpoints (mounted at /api), session-based auth
admin/
mod.rs Admin sub-app router: dashboard, settings, users, debug, setup
views.rs Admin page handlers and templates
templates/
base.html Root HTML layout with lang/title blocks
login.html Login page (password + optional SSO button)
admin/
layout.html Admin sidebar/nav wrapper
index.html Admin dashboard
debug.html Build info + config table (with secret redaction)
settings.html OIDC and auth settings form
setup.html First-run admin account creation
users.html User list
user_form.html User create/edit form
``` ```
The repository also contains a multi-stage `Dockerfile` for building a small
runtime image. A deployment must provide PostgreSQL plus persistent, writable
volumes for the inbox and music library.
## Configuration
Most settings can be changed from the administration interface. Every setting
also has a `FURU_`-prefixed environment variable; environment values take
priority over values stored in PostgreSQL.
The settings needed for a useful first installation are:
| Setting | Purpose |
| --- | --- |
| `FURU_DATABASE_URL` | PostgreSQL connection URL; required to run the service |
| `FURU_AGENT_INBOX_DIR` | Temporary inbox for uploads and downloaded files |
| `FURU_AGENT_STORAGE_DIR` | Permanent, organized music library |
| `FURU_AGENT_ENABLED` | Enables the background metadata import pipeline |
| `FURU_AGENT_LLM_URL` | Base URL of an OpenAI-compatible model server |
| `FURU_AGENT_LLM_MODEL` | Model used to recognize and normalize metadata |
| `FURU_FEDERATION_ENABLED` | Publishes the library and enables peer discovery |
| `FURU_FEDERATION_NETWORK_ID` | Joins peers with the same value into one logical network |
AI recognition, federation, similarity search, Last.fm, and OIDC are optional.
A local password-authenticated server can be used without any of them.
## Architecture ## Architecture
### Config system (`src/config.rs`) Furumusic is written in Rust on the
[Cot](https://cot.rs) web framework. PostgreSQL stores the catalog, accounts,
playlists, configuration, and background-job state. Audio inspection uses
Symphonia, torrent downloads use librqbit, and the shared `music-dht`/Frid
protocol stack provides decentralized catalog search, media transfer, and
connected-device synchronization.
Every setting lives in `AppConfig` and is resolved in three layers: The browser interface and JSON API are served by the same application. Import,
artwork, metadata enrichment, similarity indexing, and maintenance run as
durable background jobs rather than blocking playback requests.
1. **Compiled default**`AppConfig::default()` ## Contributing
2. **Database override** — rows in the `furumusic__config_entry` table
3. **Environment variable**`FURU_<FIELD_NAME>` (highest priority)
`ConfigSources` tracks where each field's effective value came from (shown in the admin debug page). Bug reports, design discussions, and patches are welcome. Before submitting a
change, run:
**To add a new config field:** ```bash
cargo fmt --all -- --check
1. Add the field to `AppConfig` struct cargo clippy --all-targets -- -D warnings
2. Set its default in `AppConfig::default()` cargo test --all-targets
3. Add the field to `ConfigSources` struct and its `Default` impl
4. Add it to the `impl_env_overrides!(…)` invocation
5. Add an `apply_db_field!()` call in `apply_db_overrides`
6. Add an `entry!()` line in `admin/views.rs → config_display_entries()`
### Auth (`src/auth.rs`)
Session-based authentication with two roles:
- **`Role::Admin`** — full access to admin panel
- **`Role::User`** — standard user
Key functions:
- `login(session, user_id)` — sets session, cycles session ID
- `logout(session)` — flushes session
- `get_session_user(session, db)` — returns `AuthenticatedUser` if active
- `require_admin_or_redirect(session, db)` — guard that returns 403 or redirects to `/login`
### OIDC/SSO (`src/oidc.rs`)
Full OpenID Connect authorization code flow with PKCE:
1. `GET /auth/oidc/start` — discovers provider, builds auth URL, stores CSRF/nonce/PKCE in session, redirects to IdP
2. `GET /auth/oidc/callback` — validates CSRF, exchanges code for tokens, verifies ID token, provisions user
Provider metadata is cached for 1 hour and invalidated when OIDC config changes.
**Group access and role mapping:** The `oidc_user_groups` config field lists OIDC group names (comma-separated) allowed to access the service. When it is set, users outside both `oidc_user_groups` and `oidc_admin_groups` are denied before provisioning/login. The `oidc_admin_groups` config field lists OIDC group names that grant the admin role. Groups are extracted from the `groups` claim in the ID token JWT payload.
**User provisioning order:**
1. Find existing `OidcLink` by issuer+sub → update claims, update role
2. Find existing `User` by email → create OidcLink, update role
3. Create new user (no password) + OidcLink
Stale links (pointing to deleted users) are cleaned up automatically.
### User model (`src/user.rs`)
Two database models:
- **`User`** — id, username (unique), password (optional for OIDC-only), email, display_name, avatar_url, role, is_active
- **`OidcLink`** — id, user_id, issuer, sub, email, name, avatar_url; unique index on (issuer, sub)
Migrations: M0003 (User table), M0004 (OidcLink table), M0005 (OidcLink indexes).
### i18n (`src/i18n/`)
Compile-time bilingual UI (English + Russian).
- `translations!` macro in `phrases.rs` generates a `Translations` struct with static `EN` and `RU` instances
- Language resolution: `furu_lang` cookie → `Accept-Language` header → English default
- `I18n` is a cot request extractor — handlers receive it automatically
- `set_lang` endpoint (`/set-lang?lang=ru&next=/`) sets the cookie
### API (`src/api/`)
JSON API mounted at `/api`. Uses the same session cookie as HTML pages — works automatically for same-origin frontend requests (no CORS, no tokens needed).
Helpers in `api/mod.rs`:
- `json_ok(value)` — 200 with `application/json`
- `json_error(status, message)` — error response as `{"error": "..."}`
| Route | Method | Description |
|-------|--------|-------------|
| `/api/me` | GET | Current user (id, name, role) or 401 |
**Swagger UI** is available at `/swagger/` when `FURU_SWAGGER_ENABLED=true`. The OpenAPI spec is auto-generated from handler types.
To add a new API endpoint:
1. Define request/response structs with `#[derive(Serialize, JsonSchema)]`
2. Write an async handler, return `Json(response).into_response()`
3. Add a `Route::with_api_handler_and_name(…, api_get(handler), …)` in `ApiApp::router()`
4. The endpoint appears automatically in Swagger UI
### Admin panel (`src/admin/`)
Mounted at `/admin`. All routes (except `/admin/setup`) require `Role::Admin`.
| Route | Purpose |
|-------|---------|
| `/admin/setup` | First-run: create initial admin (only works when zero users exist) |
| `/admin/` | Dashboard |
| `/admin/debug` | Build info, config values with sources, DB connectivity |
| `/admin/settings` | OIDC config, auth toggles (saved to DB config table) |
| `/admin/users` | User list |
| `/admin/users/new` | Create user |
| `/admin/users/{id}/edit` | Edit user |
| `/admin/users/{id}/delete` | Delete user (POST) |
## How to extend
### 1. Add a config field
See [Config system](#config-system-srcconfigrs) above — 6 locations to update.
### 2. Add a database model
1. Define a struct with `#[cot::db::model]` in a new or existing file
2. Write a migration struct implementing `cot::db::migrations::Migration`
3. Register the migration in the `AdminApp::migrations()` method in `src/admin/mod.rs`
### 3. Add a page
1. Create a template in `templates/`
2. Write a handler function that returns `Html`
3. Add a `Route::with_handler_and_name(…)` in the appropriate `router()` method
4. If admin-only, wrap with `require_admin_or_redirect`
### 4. Add a translation
Add a line to the `translations!` macro in `src/i18n/phrases.rs`:
```rust
my_key: "English text", "Русский текст";
``` ```
Access it in handlers/templates as `i18n.t.my_key` (or `t.my_key` in templates).
### 5. Add an API endpoint
Same as adding a page, but return a JSON response instead of `Html`. The `json` feature is enabled in Cargo.toml.
## Environment variables
All prefixed with `FURU_`. Priority: env var > DB override > compiled default.
| Variable | Description | Default |
|----------|-------------|---------|
| `FURU_DATABASE_URL` | PostgreSQL connection URL | *(empty — required)* |
| `FURU_LOG_LEVEL` | Tracing filter (e.g. `info`, `debug`, `warn,furumusic=trace`) | `info` |
| `FURU_AUTH_PASSWORD_ENABLED` | Enable password login | `true` |
| `FURU_AUTH_SSO_ENABLED` | Enable SSO/OIDC login | `false` |
| `FURU_OIDC_ISSUER` | OIDC issuer URL | *(empty)* |
| `FURU_OIDC_CLIENT_ID` | OIDC client ID | *(empty)* |
| `FURU_OIDC_CLIENT_SECRET` | OIDC client secret | *(empty)* |
| `FURU_OIDC_BUTTON_TEXT` | SSO button label | `Sign in with SSO` |
| `FURU_OIDC_ADMIN_GROUPS` | Comma-separated OIDC groups that grant admin | *(empty)* |
| `FURU_OIDC_USER_GROUPS` | Comma-separated OIDC groups allowed to access the service. Empty means any authenticated SSO user is allowed. | *(empty)* |
| `FURU_SWAGGER_ENABLED` | Serve Swagger UI at `/swagger/` | `false` |
Generated
+27
View File
@@ -0,0 +1,27 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1786106723,
"narHash": "sha256-zDSUbpoeo/9ZmD2+wXnzxoo1+uhL8vxc0b8yuYMKYq0=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "f13ff45afd1bb73e640eaa08a7066dbed07e3238",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}
+41
View File
@@ -0,0 +1,41 @@
{
description = "Furumusic development environment";
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
outputs = { nixpkgs, ... }:
let
supportedSystems = [
"x86_64-linux"
"aarch64-linux"
"x86_64-darwin"
"aarch64-darwin"
];
forEachSystem = function:
nixpkgs.lib.genAttrs supportedSystems (system:
function (import nixpkgs { inherit system; }));
in
{
devShells = forEachSystem (pkgs: {
default = pkgs.mkShell {
nativeBuildInputs = with pkgs; [
cargo
clippy
pkg-config
rustc
rustfmt
];
buildInputs = with pkgs; [
cacert
deno
ffmpeg-headless
openssl
yt-dlp
] ++ lib.optionals stdenv.isDarwin [ libiconv ];
RUST_SRC_PATH = "${pkgs.rustPlatform.rustLibSrc}";
};
});
};
}
+42 -13
View File
@@ -422,6 +422,20 @@ impl App for AdminApp {
}), }),
"admin_v2_federation_status", "admin_v2_federation_status",
), ),
Route::with_handler_and_name(
"/v2/api/similarity",
get(move |session: Session, db: Database| async move {
v2::similarity_status(session, db).await
}),
"admin_v2_similarity_status",
),
Route::with_handler_and_name(
"/v2/api/similarity/clear",
cot::router::method::post(move |session: Session, db: Database| async move {
v2::similarity_clear(session, db).await
}),
"admin_v2_similarity_clear",
),
Route::with_handler_and_name( Route::with_handler_and_name(
"/v2/api/federation/sync", "/v2/api/federation/sync",
cot::router::method::post(move |session: Session, db: Database| async move { cot::router::method::post(move |session: Session, db: Database| async move {
@@ -1055,19 +1069,34 @@ impl App for AdminApp {
), ),
"admin_releases_edit", "admin_releases_edit",
), ),
Route::with_handler_and_name( {
"/releases/{id}/delete", let pool = Arc::clone(&pool);
cot::router::method::post( let pool_config = Arc::clone(&pool_config);
|session: Session, db: Database, path: Path<PathId>| async move { Route::with_handler_and_name(
let admin = match auth::require_admin_or_redirect(&session, &db).await { "/releases/{id}/delete",
Ok(u) => u, cot::router::method::post(move |session: Session, db: Database, path: Path<PathId>| {
Err(resp) => return Ok(resp), let pool = Arc::clone(&pool);
}; let pool_config = Arc::clone(&pool_config);
views::releases_delete(admin, &db, path.0.id).await async move {
}, let admin = match auth::require_admin_or_redirect(&session, &db).await {
), Ok(u) => u,
"admin_releases_delete", Err(resp) => return Ok(resp),
), };
let pg_pool = pool
.get_or_init(|| async {
sqlx::postgres::PgPoolOptions::new()
.max_connections(5)
.connect(&pool_config.database_url)
.await
.expect("admin pool")
})
.await;
views::releases_delete(admin, &db, pg_pool, path.0.id).await
}
}),
"admin_releases_delete",
)
},
// -- Media Files -------------------------------------------------- // -- Media Files --------------------------------------------------
Route::with_handler_and_name( Route::with_handler_and_name(
"/media-files", "/media-files",
+278 -91
View File
@@ -16,7 +16,7 @@ use sqlx::{PgPool, Postgres, QueryBuilder};
use super::BUILD_INFO; use super::BUILD_INFO;
use crate::agent; use crate::agent;
use crate::auth::{self, AuthenticatedUser, Role}; use crate::auth::{self, AuthenticatedUser, Role};
use crate::config::{AppConfig, ConfigEntry, ConfigSources}; use crate::config::{AppConfig, ConfigEntry, ConfigSources, DownloadProxy};
use crate::i18n::{I18n, Translations}; use crate::i18n::{I18n, Translations};
use crate::scheduler::{self, JobRegistry, JobRun, ScheduledJob}; use crate::scheduler::{self, JobRegistry, JobRun, ScheduledJob};
@@ -454,6 +454,58 @@ struct AdminSettingsValues {
federation_network_id: String, federation_network_id: String,
#[serde(default)] #[serde(default)]
federation_save_on_listen: bool, federation_save_on_listen: bool,
#[serde(default)]
similarity_enabled: bool,
#[serde(default = "default_similarity_model")]
similarity_model: String,
#[serde(default = "default_similarity_profile")]
similarity_profile: String,
#[serde(default = "default_similarity_workers")]
similarity_workers: String,
#[serde(default = "default_true")]
downloads_enabled: bool,
#[serde(default = "default_true")]
torrent_downloads_enabled: bool,
#[serde(default = "default_true")]
youtube_downloads_enabled: bool,
#[serde(default)]
download_proxies: Vec<AdminDownloadProxy>,
#[serde(default)]
torrent_proxy_id: String,
#[serde(default)]
youtube_proxy_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
struct AdminDownloadProxy {
id: String,
address: String,
#[serde(default)]
username: String,
#[serde(default)]
password: String,
}
impl From<DownloadProxy> for AdminDownloadProxy {
fn from(proxy: DownloadProxy) -> Self {
Self {
id: proxy.id,
address: proxy.address,
username: proxy.username,
password: proxy.password,
}
}
}
impl From<AdminDownloadProxy> for DownloadProxy {
fn from(proxy: AdminDownloadProxy) -> Self {
Self {
id: proxy.id,
address: proxy.address,
username: proxy.username,
password: proxy.password,
}
}
} }
#[derive(Debug, Clone, Serialize, JsonSchema)] #[derive(Debug, Clone, Serialize, JsonSchema)]
@@ -481,6 +533,16 @@ struct AdminSettingsSources {
federation_enabled: &'static str, federation_enabled: &'static str,
federation_network_id: &'static str, federation_network_id: &'static str,
federation_save_on_listen: &'static str, federation_save_on_listen: &'static str,
similarity_enabled: &'static str,
similarity_model: &'static str,
similarity_profile: &'static str,
similarity_workers: &'static str,
downloads_enabled: &'static str,
torrent_downloads_enabled: &'static str,
youtube_downloads_enabled: &'static str,
download_proxies: &'static str,
torrent_proxy_id: &'static str,
youtube_proxy_id: &'static str,
} }
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
@@ -511,6 +573,38 @@ pub(super) struct UpdateSettingsRequest {
federation_network_id: String, federation_network_id: String,
#[serde(default)] #[serde(default)]
federation_save_on_listen: bool, federation_save_on_listen: bool,
#[serde(default)]
similarity_enabled: bool,
#[serde(default = "default_similarity_model")]
similarity_model: String,
#[serde(default = "default_similarity_profile")]
similarity_profile: String,
#[serde(default = "default_similarity_workers")]
similarity_workers: String,
#[serde(default = "default_true")]
downloads_enabled: bool,
#[serde(default = "default_true")]
torrent_downloads_enabled: bool,
#[serde(default = "default_true")]
youtube_downloads_enabled: bool,
#[serde(default)]
download_proxies: Vec<AdminDownloadProxy>,
#[serde(default)]
torrent_proxy_id: String,
#[serde(default)]
youtube_proxy_id: String,
}
fn default_similarity_model() -> String {
crate::similarity::DEFAULT_MODEL_ID.to_owned()
}
fn default_similarity_profile() -> String {
crate::similarity::DEFAULT_PROFILE_ID.to_owned()
}
fn default_similarity_workers() -> String {
"1".to_owned()
} }
#[derive(Debug, Serialize, JsonSchema)] #[derive(Debug, Serialize, JsonSchema)]
@@ -948,6 +1042,70 @@ pub async fn update_settings(
if let Err(response) = require_admin_json(&session, &db).await { if let Err(response) = require_admin_json(&session, &db).await {
return Ok(response); return Ok(response);
} }
let similarity_model = body.similarity_model.trim().to_string();
if crate::similarity::model_by_id(&similarity_model).is_none() {
return Ok(json_error(
StatusCode::BAD_REQUEST,
"unknown similarity model",
));
}
let similarity_profile = body.similarity_profile.trim().to_string();
if crate::similarity::profile_by_id(&similarity_profile).is_none() {
return Ok(json_error(
StatusCode::BAD_REQUEST,
"unknown similarity preprocessing profile",
));
}
let similarity_workers = match body.similarity_workers.trim().parse::<u64>() {
Ok(workers @ 1..=16) => workers,
_ => {
return Ok(json_error(
StatusCode::BAD_REQUEST,
"similarity workers must be an integer from 1 to 16",
));
}
};
if body.download_proxies.len() > 32 {
return Ok(json_error(
StatusCode::BAD_REQUEST,
"at most 32 download proxies can be saved",
));
}
let mut download_proxies = Vec::with_capacity(body.download_proxies.len());
let mut proxy_ids = HashSet::new();
for (index, proxy) in body.download_proxies.into_iter().enumerate() {
let proxy = match DownloadProxy::from(proxy).normalized() {
Ok(proxy) => proxy,
Err(error) => {
return Ok(json_error(
StatusCode::BAD_REQUEST,
&format!("proxy {}: {error}", index + 1),
));
}
};
if !proxy_ids.insert(proxy.id.clone()) {
return Ok(json_error(
StatusCode::BAD_REQUEST,
"download proxy ids must be unique",
));
}
download_proxies.push(proxy);
}
let torrent_proxy_id = body.torrent_proxy_id.trim().to_string();
let youtube_proxy_id = body.youtube_proxy_id.trim().to_string();
for (method, proxy_id) in [
("torrent", torrent_proxy_id.as_str()),
("YouTube", youtube_proxy_id.as_str()),
] {
if !proxy_id.is_empty() && !proxy_ids.contains(proxy_id) {
return Ok(json_error(
StatusCode::BAD_REQUEST,
&format!("selected {method} proxy is not in the saved proxy list"),
));
}
}
let download_proxies_json = serde_json::to_string(&download_proxies)
.map_err(|error| cot::Error::internal(error.to_string()))?;
let fields = [ let fields = [
( (
"auth_password_enabled", "auth_password_enabled",
@@ -1002,6 +1160,22 @@ pub async fn update_settings(
"federation_save_on_listen", "federation_save_on_listen",
body.federation_save_on_listen.to_string(), body.federation_save_on_listen.to_string(),
), ),
("similarity_enabled", body.similarity_enabled.to_string()),
("similarity_model", similarity_model),
("similarity_profile", similarity_profile),
("similarity_workers", similarity_workers.to_string()),
("downloads_enabled", body.downloads_enabled.to_string()),
(
"torrent_downloads_enabled",
body.torrent_downloads_enabled.to_string(),
),
(
"youtube_downloads_enabled",
body.youtube_downloads_enabled.to_string(),
),
("download_proxies", download_proxies_json),
("torrent_proxy_id", torrent_proxy_id),
("youtube_proxy_id", youtube_proxy_id),
]; ];
for (key, value) in fields { for (key, value) in fields {
let mut entry = ConfigEntry::new(key.to_string(), value); let mut entry = ConfigEntry::new(key.to_string(), value);
@@ -1014,6 +1188,7 @@ pub async fn update_settings(
// the freshly saved settings — no server restart involved. // the freshly saved settings — no server restart involved.
let (fresh, _) = AppConfig::load_with_db(&db).await; let (fresh, _) = AppConfig::load_with_db(&db).await;
tokio::spawn(async move { tokio::spawn(async move {
crate::similarity::handle().apply(&fresh);
crate::federation::handle().apply(&fresh).await; crate::federation::handle().apply(&fresh).await;
}); });
Json(serde_json::json!({ "ok": true })).into_response() Json(serde_json::json!({ "ok": true })).into_response()
@@ -1033,6 +1208,57 @@ pub async fn federation_status(
Json(crate::federation::handle().status().await).into_response() Json(crate::federation::handle().status().await).into_response()
} }
pub async fn similarity_status(
session: Session,
db: Database,
) -> cot::Result<cot::response::Response> {
if let Err(response) = require_admin_json(&session, &db).await {
return Ok(response);
}
let manager = crate::similarity::handle();
let status = manager.status();
let model_id = if status.model.is_empty() {
crate::similarity::DEFAULT_MODEL_ID
} else {
&status.model
};
let profiles = crate::similarity::PROFILES
.iter()
.map(|profile| {
serde_json::json!({
"id": profile.id,
"title": profile.title,
"details": crate::similarity::profile_details(
profile.id,
model_id,
).unwrap_or_default(),
})
})
.collect::<Vec<_>>();
Json(serde_json::json!({
"status": status,
"models": crate::similarity::MODELS,
"profiles": profiles,
}))
.into_response()
}
pub async fn similarity_clear(
session: Session,
db: Database,
) -> cot::Result<cot::response::Response> {
if let Err(response) = require_admin_json(&session, &db).await {
return Ok(response);
}
match crate::similarity::handle().clear().await {
Ok(()) => Json(serde_json::json!({ "ok": true })).into_response(),
Err(error) => Ok(json_error(
StatusCode::INTERNAL_SERVER_ERROR,
&format!("embedding cleanup failed: {error:#}"),
)),
}
}
pub async fn federation_sync( pub async fn federation_sync(
session: Session, session: Session,
db: Database, db: Database,
@@ -1124,6 +1350,15 @@ pub async fn settings_probe(
} }
fn settings_dto(config: AppConfig, sources: ConfigSources) -> AdminSettingsDto { fn settings_dto(config: AppConfig, sources: ConfigSources) -> AdminSettingsDto {
let download_proxies = config
.parsed_download_proxies()
.unwrap_or_else(|error| {
tracing::warn!(%error, "ignoring invalid saved download proxy list");
Vec::new()
})
.into_iter()
.map(AdminDownloadProxy::from)
.collect();
AdminSettingsDto { AdminSettingsDto {
lastfm_api_key_configured: !config.lastfm_api_key.trim().is_empty(), lastfm_api_key_configured: !config.lastfm_api_key.trim().is_empty(),
lastfm_shared_secret_configured: !config.lastfm_shared_secret.trim().is_empty(), lastfm_shared_secret_configured: !config.lastfm_shared_secret.trim().is_empty(),
@@ -1153,6 +1388,16 @@ fn settings_dto(config: AppConfig, sources: ConfigSources) -> AdminSettingsDto {
federation_enabled: config.federation_enabled, federation_enabled: config.federation_enabled,
federation_network_id: config.federation_network_id, federation_network_id: config.federation_network_id,
federation_save_on_listen: config.federation_save_on_listen, federation_save_on_listen: config.federation_save_on_listen,
similarity_enabled: config.similarity_enabled,
similarity_model: config.similarity_model,
similarity_profile: config.similarity_profile,
similarity_workers: config.similarity_workers.to_string(),
downloads_enabled: config.downloads_enabled,
torrent_downloads_enabled: config.torrent_downloads_enabled,
youtube_downloads_enabled: config.youtube_downloads_enabled,
download_proxies,
torrent_proxy_id: config.torrent_proxy_id,
youtube_proxy_id: config.youtube_proxy_id,
}, },
sources: AdminSettingsSources { sources: AdminSettingsSources {
auth_password_enabled: sources.auth_password_enabled.code(), auth_password_enabled: sources.auth_password_enabled.code(),
@@ -1178,6 +1423,16 @@ fn settings_dto(config: AppConfig, sources: ConfigSources) -> AdminSettingsDto {
federation_enabled: sources.federation_enabled.code(), federation_enabled: sources.federation_enabled.code(),
federation_network_id: sources.federation_network_id.code(), federation_network_id: sources.federation_network_id.code(),
federation_save_on_listen: sources.federation_save_on_listen.code(), federation_save_on_listen: sources.federation_save_on_listen.code(),
similarity_enabled: sources.similarity_enabled.code(),
similarity_model: sources.similarity_model.code(),
similarity_profile: sources.similarity_profile.code(),
similarity_workers: sources.similarity_workers.code(),
downloads_enabled: sources.downloads_enabled.code(),
torrent_downloads_enabled: sources.torrent_downloads_enabled.code(),
youtube_downloads_enabled: sources.youtube_downloads_enabled.code(),
download_proxies: sources.download_proxies.code(),
torrent_proxy_id: sources.torrent_proxy_id.code(),
youtube_proxy_id: sources.youtube_proxy_id.code(),
}, },
} }
} }
@@ -1811,7 +2066,12 @@ pub async fn bulk_library(
.into_response(); .into_response();
} }
let affected = apply_library_action(pool, &kind, action, &ids).await?; let storage_dir = if action == "delete" && matches!(kind.as_str(), "releases" | "tracks") {
AppConfig::load_with_db(&db).await.0.agent_storage_dir
} else {
String::new()
};
let affected = apply_library_action(pool, &kind, action, &ids, &storage_dir).await?;
Json(MutationResponse { ok: true, affected }).into_response() Json(MutationResponse { ok: true, affected }).into_response()
} }
@@ -3365,10 +3625,11 @@ async fn apply_library_action(
kind: &str, kind: &str,
action: &str, action: &str,
ids: &[i64], ids: &[i64],
storage_dir: &str,
) -> cot::Result<u64> { ) -> cot::Result<u64> {
match action { match action {
"hide" | "show" => set_library_visibility(pool, kind, ids, action == "hide").await, "hide" | "show" => set_library_visibility(pool, kind, ids, action == "hide").await,
"delete" => delete_library_items(pool, kind, ids).await, "delete" => delete_library_items(pool, kind, ids, storage_dir).await,
_ => Ok(0), _ => Ok(0),
} }
} }
@@ -3419,10 +3680,15 @@ async fn set_library_visibility(
Ok(result.rows_affected()) Ok(result.rows_affected())
} }
async fn delete_library_items(pool: &PgPool, kind: &str, ids: &[i64]) -> cot::Result<u64> { async fn delete_library_items(
pool: &PgPool,
kind: &str,
ids: &[i64],
storage_dir: &str,
) -> cot::Result<u64> {
match kind { match kind {
"releases" => delete_releases(pool, ids).await, "releases" => delete_releases(pool, ids, storage_dir).await,
"tracks" => delete_tracks(pool, ids).await, "tracks" => delete_tracks(pool, ids, storage_dir).await,
"playlists" => delete_playlists(pool, ids).await, "playlists" => delete_playlists(pool, ids).await,
_ => delete_artists(pool, ids).await, _ => delete_artists(pool, ids).await,
} }
@@ -3452,95 +3718,16 @@ async fn delete_artists(pool: &PgPool, ids: &[i64]) -> cot::Result<u64> {
Ok(result.rows_affected()) Ok(result.rows_affected())
} }
async fn delete_releases(pool: &PgPool, ids: &[i64]) -> cot::Result<u64> { async fn delete_releases(pool: &PgPool, ids: &[i64], storage_dir: &str) -> cot::Result<u64> {
let track_ids = crate::library_cleanup::delete_releases(pool, ids, storage_dir)
sqlx::query_as::<_, IdRow>("SELECT id FROM furumusic__track WHERE release_id = ANY($1)")
.bind(ids)
.fetch_all(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?
.into_iter()
.map(|row| row.id)
.collect::<Vec<_>>();
if !track_ids.is_empty() {
sqlx::query("DELETE FROM furumusic__playlist_track WHERE track_id = ANY($1)")
.bind(&track_ids)
.execute(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
sqlx::query("DELETE FROM furumusic__user_liked_track WHERE track_id = ANY($1)")
.bind(&track_ids)
.execute(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
sqlx::query("DELETE FROM furumusic__play_history WHERE track_id = ANY($1)")
.bind(&track_ids)
.execute(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
sqlx::query("DELETE FROM furumusic__track_genre WHERE track_id = ANY($1)")
.bind(&track_ids)
.execute(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
sqlx::query("DELETE FROM furumusic__track_artist WHERE track_id = ANY($1)")
.bind(&track_ids)
.execute(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
}
sqlx::query("DELETE FROM furumusic__track WHERE release_id = ANY($1)")
.bind(ids)
.execute(pool)
.await .await
.map_err(|e| cot::Error::internal(e.to_string()))?; .map_err(|error| cot::Error::internal(error.to_string()))
sqlx::query("DELETE FROM furumusic__release_artist WHERE release_id = ANY($1)")
.bind(ids)
.execute(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
let result = sqlx::query("DELETE FROM furumusic__release WHERE id = ANY($1)")
.bind(ids)
.execute(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
Ok(result.rows_affected())
} }
async fn delete_tracks(pool: &PgPool, ids: &[i64]) -> cot::Result<u64> { async fn delete_tracks(pool: &PgPool, ids: &[i64], storage_dir: &str) -> cot::Result<u64> {
sqlx::query("DELETE FROM furumusic__playlist_track WHERE track_id = ANY($1)") crate::library_cleanup::delete_tracks(pool, ids, storage_dir)
.bind(ids)
.execute(pool)
.await .await
.map_err(|e| cot::Error::internal(e.to_string()))?; .map_err(|error| cot::Error::internal(error.to_string()))
sqlx::query("DELETE FROM furumusic__user_liked_track WHERE track_id = ANY($1)")
.bind(ids)
.execute(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
sqlx::query("DELETE FROM furumusic__play_history WHERE track_id = ANY($1)")
.bind(ids)
.execute(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
sqlx::query("DELETE FROM furumusic__track_genre WHERE track_id = ANY($1)")
.bind(ids)
.execute(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
sqlx::query("DELETE FROM furumusic__track_artist WHERE track_id = ANY($1)")
.bind(ids)
.execute(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
let result = sqlx::query("DELETE FROM furumusic__track WHERE id = ANY($1)")
.bind(ids)
.execute(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
Ok(result.rows_affected())
} }
async fn delete_playlists(pool: &PgPool, ids: &[i64]) -> cot::Result<u64> { async fn delete_playlists(pool: &PgPool, ids: &[i64]) -> cot::Result<u64> {
+3 -1
View File
@@ -1262,9 +1262,11 @@ pub async fn releases_update(
pub async fn releases_delete( pub async fn releases_delete(
_admin: AuthenticatedUser, _admin: AuthenticatedUser,
db: &Database, db: &Database,
pool: &sqlx::PgPool,
release_id: i64, release_id: i64,
) -> cot::Result<cot::http::Response<Body>> { ) -> cot::Result<cot::http::Response<Body>> {
Release::delete_by_id(db, release_id) let (config, _) = AppConfig::load_with_db(db).await;
crate::library_cleanup::delete_releases(pool, &[release_id], &config.agent_storage_dir)
.await .await
.map_err(|e| cot::Error::internal(format!("failed to delete release: {e}")))?; .map_err(|e| cot::Error::internal(format!("failed to delete release: {e}")))?;
Ok(auth::redirect("/admin/releases")) Ok(auth::redirect("/admin/releases"))
+232
View File
@@ -138,6 +138,16 @@ pub struct ConfigSources {
pub federation_enabled: ConfigSource, pub federation_enabled: ConfigSource,
pub federation_network_id: ConfigSource, pub federation_network_id: ConfigSource,
pub federation_save_on_listen: ConfigSource, pub federation_save_on_listen: ConfigSource,
pub similarity_enabled: ConfigSource,
pub similarity_model: ConfigSource,
pub similarity_profile: ConfigSource,
pub similarity_workers: ConfigSource,
pub downloads_enabled: ConfigSource,
pub torrent_downloads_enabled: ConfigSource,
pub youtube_downloads_enabled: ConfigSource,
pub download_proxies: ConfigSource,
pub torrent_proxy_id: ConfigSource,
pub youtube_proxy_id: ConfigSource,
} }
impl Default for ConfigSources { impl Default for ConfigSources {
@@ -168,6 +178,16 @@ impl Default for ConfigSources {
federation_enabled: ConfigSource::Default, federation_enabled: ConfigSource::Default,
federation_network_id: ConfigSource::Default, federation_network_id: ConfigSource::Default,
federation_save_on_listen: ConfigSource::Default, federation_save_on_listen: ConfigSource::Default,
similarity_enabled: ConfigSource::Default,
similarity_model: ConfigSource::Default,
similarity_profile: ConfigSource::Default,
similarity_workers: ConfigSource::Default,
downloads_enabled: ConfigSource::Default,
torrent_downloads_enabled: ConfigSource::Default,
youtube_downloads_enabled: ConfigSource::Default,
download_proxies: ConfigSource::Default,
torrent_proxy_id: ConfigSource::Default,
youtube_proxy_id: ConfigSource::Default,
} }
} }
} }
@@ -230,6 +250,84 @@ macro_rules! impl_env_overrides {
// AppConfig // AppConfig
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
/// Saved SOCKS5 proxy used by user-facing download methods.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DownloadProxy {
pub id: String,
pub address: String,
#[serde(default)]
pub username: String,
#[serde(default)]
pub password: String,
}
impl DownloadProxy {
/// Validate and normalize a proxy without performing network or DNS I/O.
pub fn normalized(mut self) -> anyhow::Result<Self> {
self.id = self.id.trim().to_string();
self.address = self.address.trim().to_string();
if self.id.is_empty() || self.id.len() > 64 {
anyhow::bail!("proxy id must contain from 1 to 64 characters");
}
if !self
.id
.chars()
.all(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_'))
{
anyhow::bail!("proxy id may contain only letters, digits, '-' and '_'");
}
if self.address.is_empty() || self.address.len() > 512 {
anyhow::bail!("proxy address must contain a host and port");
}
if self
.address
.chars()
.any(|character| matches!(character, '/' | '?' | '#' | '@'))
{
anyhow::bail!("proxy address must be in host:port format");
}
if self.username.len() > 256 || self.password.len() > 256 {
anyhow::bail!("proxy credentials are too long");
}
let parsed = reqwest::Url::parse(&format!("socks5://{}", self.address))
.map_err(|_| anyhow::anyhow!("proxy address must be in host:port format"))?;
let host = parsed
.host_str()
.filter(|host| !host.trim().is_empty())
.ok_or_else(|| anyhow::anyhow!("proxy address has no host"))?;
let port = parsed
.port()
.ok_or_else(|| anyhow::anyhow!("proxy address has no port"))?;
if port == 0 {
anyhow::bail!("proxy port must be between 1 and 65535");
}
self.address = if host.starts_with('[') && host.ends_with(']') {
format!("{host}:{port}")
} else if host.contains(':') {
format!("[{host}]:{port}")
} else {
format!("{host}:{port}")
};
Ok(self)
}
/// Build the URL accepted by librqbit and yt-dlp. Credentials are included
/// only when both fields are non-empty.
pub fn socks_url(&self) -> anyhow::Result<String> {
let proxy = self.clone().normalized()?;
let mut url = reqwest::Url::parse(&format!("socks5://{}", proxy.address))?;
if !proxy.username.is_empty() && !proxy.password.is_empty() {
url.set_username(&proxy.username)
.map_err(|_| anyhow::anyhow!("invalid proxy username"))?;
url.set_password(Some(&proxy.password))
.map_err(|_| anyhow::anyhow!("invalid proxy password"))?;
}
Ok(url.to_string())
}
}
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppConfig { pub struct AppConfig {
/// PostgreSQL connection URL. /// PostgreSQL connection URL.
@@ -285,6 +383,26 @@ pub struct AppConfig {
/// Whether a federated track requested for playback is imported into the /// Whether a federated track requested for playback is imported into the
/// shared local library. This is a server-wide administrator policy. /// shared local library. This is a server-wide administrator policy.
pub federation_save_on_listen: bool, pub federation_save_on_listen: bool,
/// Whether local embedding calculation and similarity search are enabled.
pub similarity_enabled: bool,
/// Embedding model selected by the administrator.
pub similarity_model: String,
/// Audio preprocessing profile selected by the administrator.
pub similarity_profile: String,
/// Maximum number of concurrent CPU embedding workers.
pub similarity_workers: u64,
/// Whether the download manager and local-file uploads are available.
pub downloads_enabled: bool,
/// Whether torrent imports are available when the download manager is enabled.
pub torrent_downloads_enabled: bool,
/// Whether YouTube imports are available when the download manager is enabled.
pub youtube_downloads_enabled: bool,
/// JSON-encoded list of [`DownloadProxy`] entries.
pub download_proxies: String,
/// Saved proxy id used for torrent downloads; empty means a direct connection.
pub torrent_proxy_id: String,
/// Saved proxy id used for YouTube downloads; empty means a direct connection.
pub youtube_proxy_id: String,
} }
impl Default for AppConfig { impl Default for AppConfig {
@@ -315,6 +433,19 @@ impl Default for AppConfig {
federation_enabled: false, federation_enabled: false,
federation_network_id: String::new(), federation_network_id: String::new(),
federation_save_on_listen: false, federation_save_on_listen: false,
similarity_enabled: false,
similarity_model: "discogs-effnet-bsdynamic-1".into(),
similarity_profile: "furumi-full-track-v1".into(),
similarity_workers: std::thread::available_parallelism()
.map(|count| (count.get() / 2).clamp(1, 4) as u64)
.unwrap_or(1),
// Preserve the behavior from before these controls were added.
downloads_enabled: true,
torrent_downloads_enabled: true,
youtube_downloads_enabled: true,
download_proxies: "[]".into(),
torrent_proxy_id: String::new(),
youtube_proxy_id: String::new(),
} }
} }
} }
@@ -346,6 +477,16 @@ impl_env_overrides!(
federation_enabled, federation_enabled,
federation_network_id, federation_network_id,
federation_save_on_listen, federation_save_on_listen,
similarity_enabled,
similarity_model,
similarity_profile,
similarity_workers,
downloads_enabled,
torrent_downloads_enabled,
youtube_downloads_enabled,
download_proxies,
torrent_proxy_id,
youtube_proxy_id,
); );
impl AppConfig { impl AppConfig {
@@ -476,6 +617,43 @@ impl AppConfig {
apply_db_field!(federation_enabled); apply_db_field!(federation_enabled);
apply_db_field!(federation_network_id); apply_db_field!(federation_network_id);
apply_db_field!(federation_save_on_listen); apply_db_field!(federation_save_on_listen);
apply_db_field!(similarity_enabled);
apply_db_field!(similarity_model);
apply_db_field!(similarity_profile);
apply_db_field!(similarity_workers);
apply_db_field!(downloads_enabled);
apply_db_field!(torrent_downloads_enabled);
apply_db_field!(youtube_downloads_enabled);
apply_db_field!(download_proxies);
apply_db_field!(torrent_proxy_id);
apply_db_field!(youtube_proxy_id);
}
pub fn parsed_download_proxies(&self) -> anyhow::Result<Vec<DownloadProxy>> {
let proxies: Vec<DownloadProxy> = serde_json::from_str(&self.download_proxies)
.map_err(|_| anyhow::anyhow!("saved download proxy list is invalid"))?;
proxies.into_iter().map(DownloadProxy::normalized).collect()
}
pub fn selected_proxy_url(&self, proxy_id: &str) -> anyhow::Result<Option<String>> {
let proxy_id = proxy_id.trim();
if proxy_id.is_empty() {
return Ok(None);
}
let proxy = self
.parsed_download_proxies()?
.into_iter()
.find(|proxy| proxy.id == proxy_id)
.ok_or_else(|| anyhow::anyhow!("selected download proxy is not configured"))?;
proxy.socks_url().map(Some)
}
pub fn torrent_proxy_url(&self) -> anyhow::Result<Option<String>> {
self.selected_proxy_url(&self.torrent_proxy_id)
}
pub fn youtube_proxy_url(&self) -> anyhow::Result<Option<String>> {
self.selected_proxy_url(&self.youtube_proxy_id)
} }
} }
@@ -495,6 +673,60 @@ mod tests {
let cfg = AppConfig::default(); let cfg = AppConfig::default();
assert!(cfg.database_url.is_empty()); assert!(cfg.database_url.is_empty());
assert_eq!(cfg.log_level, "info"); assert_eq!(cfg.log_level, "info");
assert!(!cfg.similarity_enabled);
assert_eq!(cfg.similarity_model, crate::similarity::DEFAULT_MODEL_ID);
assert_eq!(
cfg.similarity_profile,
crate::similarity::DEFAULT_PROFILE_ID
);
assert!((1..=4).contains(&cfg.similarity_workers));
assert!(cfg.downloads_enabled);
assert!(cfg.torrent_downloads_enabled);
assert!(cfg.youtube_downloads_enabled);
assert!(cfg.parsed_download_proxies().unwrap().is_empty());
}
#[test]
fn download_proxy_url_encodes_complete_credentials() {
let proxy = DownloadProxy {
id: "proxy-1".into(),
address: "proxy.example:1080".into(),
username: "user name".into(),
password: "p@ss:word".into(),
};
assert_eq!(
proxy.socks_url().unwrap(),
"socks5://user%20name:p%40ss%3Aword@proxy.example:1080"
);
}
#[test]
fn download_proxy_url_omits_partial_credentials() {
let proxy = DownloadProxy {
id: "proxy-1".into(),
address: "127.0.0.1:1080".into(),
username: "user".into(),
password: String::new(),
};
assert_eq!(proxy.socks_url().unwrap(), "socks5://127.0.0.1:1080");
}
#[test]
fn selected_download_proxy_is_resolved_by_id() {
let mut cfg = AppConfig::default();
cfg.download_proxies = serde_json::to_string(&[DownloadProxy {
id: "youtube".into(),
address: "[::1]:9050".into(),
username: String::new(),
password: String::new(),
}])
.unwrap();
cfg.youtube_proxy_id = "youtube".into();
assert_eq!(
cfg.youtube_proxy_url().unwrap().as_deref(),
Some("socks5://[::1]:9050")
);
assert_eq!(cfg.torrent_proxy_url().unwrap(), None);
} }
#[test] #[test]
+80
View File
@@ -0,0 +1,80 @@
//! Informational publication of the protocol versions exposed by this peer.
use std::time::Duration;
use anyhow::Result;
use music_dht::StreamAcceptor;
use music_dht::capabilities::{
CAPABILITIES_PROTOCOL_VERSION, CapabilityManifest, CapabilityMessage, JAM_ID, SIMILARITY_ID,
read_message, write_message,
};
use super::serve::AUDIO_PROTOCOL_VERSION;
fn local_manifest() -> CapabilityManifest {
CapabilityManifest::frid("furumusic", env!("CARGO_PKG_VERSION"))
// The web server does not expose federation Jam yet.
.without_protocol(JAM_ID)
.with_protocol("audio", AUDIO_PROTOCOL_VERSION)
.with_protocol(
SIMILARITY_ID,
music_dht::similarity::SIMILARITY_PROTOCOL_VERSION,
)
}
pub async fn serve(mut acceptor: StreamAcceptor) {
while let Some(stream) = acceptor.accept().await {
tokio::spawn(async move {
if let Err(error) = serve_one(stream).await {
tracing::debug!("capability stream failed: {error:#}");
}
});
}
}
async fn serve_one(mut stream: music_dht::ByteStream) -> Result<()> {
let response = match read_message(&mut stream).await? {
CapabilityMessage::Get {
version: CAPABILITIES_PROTOCOL_VERSION,
} => CapabilityMessage::Manifest {
manifest: local_manifest(),
},
CapabilityMessage::Get { version } => CapabilityMessage::Error {
message: format!("unsupported capability protocol {version}"),
},
_ => CapabilityMessage::Error {
message: "expected capability request".to_string(),
},
};
write_message(&mut stream, &response).await?;
stream.send.finish()?;
let _ = tokio::time::timeout(Duration::from_secs(2), stream.send.stopped()).await;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn manifest_describes_only_supported_player_protocols() {
let manifest = local_manifest();
assert_eq!(manifest.application, "furumusic");
assert_eq!(
manifest.protocols.get("audio"),
Some(&AUDIO_PROTOCOL_VERSION)
);
assert!(!manifest.protocols.contains_key(JAM_ID));
assert_eq!(
manifest.protocols.get(SIMILARITY_ID),
Some(&music_dht::similarity::SIMILARITY_PROTOCOL_VERSION)
);
assert_eq!(
manifest
.protocols
.get(music_dht::capabilities::SIMILARITY_DHT_ID),
Some(&music_dht::similarity_lsh::SIMILARITY_DHT_PROTOCOL_VERSION)
);
manifest.validate().unwrap();
}
}
+64
View File
@@ -85,6 +85,8 @@ pub struct TrackDto {
pub key: TrackKeyDto, pub key: TrackKeyDto,
pub metadata: TrackMetadataDto, pub metadata: TrackMetadataDto,
pub availability: TrackAvailabilityDto, pub availability: TrackAvailabilityDto,
#[serde(skip_serializing_if = "Option::is_none")]
pub similarity_score: Option<f32>,
} }
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
@@ -98,6 +100,67 @@ pub struct SearchEvent {
} }
impl Federation { impl Federation {
pub async fn prepare_similarity_tracks(
&self,
tracks: Vec<super::similarity::RemoteSimilarityTrack>,
) -> Result<Vec<TrackDto>> {
let pool = self.pool().await?;
let mut prepared = Vec::new();
for track in tracks {
let Some(content_id) = track.content_id.as_deref().and_then(normalize_content_id)
else {
continue;
};
let local = local_availability(&pool, &content_id).await?;
// A local result is already present in the first result section.
if local.is_some() {
continue;
}
let owner = track.owner;
let item_id = track.item_id;
let dto = TrackDto {
key: TrackKeyDto {
content_id: content_id.clone(),
},
metadata: TrackMetadataDto {
title: track.title,
artists: artist_refs(&track.artist_names),
featured_artists: artist_refs(&track.featured_artist_names),
release: track.release_title.map(|title| ReleaseRefDto {
key: ReleaseKeyDto {
normalized_title: music_dht::normalize_name(&title),
primary_artists: track
.artist_names
.iter()
.map(|artist| music_dht::normalize_name(artist))
.collect(),
release_type: None,
year: track.year,
},
local_id: None,
title,
}),
year: track.year,
duration_seconds: track.duration_seconds.map(|value| value as f64),
track_number: track.track_number,
disc_number: track.disc_number,
cover_url: Some(format!(
"/api/player/federation/tracks/artwork?owner={owner}&item_id={item_id}"
)),
},
availability: TrackAvailabilityDto {
state: "federated",
local: None,
federation: vec![FederationSourceDto { owner, item_id }],
},
similarity_score: Some(track.similarity_score),
};
persist_track_ref(&pool, &dto).await?;
prepared.push(dto);
}
Ok(prepared)
}
pub fn stream_artist_catalogs( pub fn stream_artist_catalogs(
self: &std::sync::Arc<Self>, self: &std::sync::Arc<Self>,
name: String, name: String,
@@ -431,6 +494,7 @@ fn track_from_item(
local, local,
federation: vec![FederationSourceDto { owner, item_id }], federation: vec![FederationSourceDto { owner, item_id }],
}, },
similarity_score: None,
} }
} }
+41 -6
View File
@@ -32,6 +32,9 @@ const RESPONSE_DRAIN_TIMEOUT: Duration = Duration::from_secs(2);
const DEVICE_SYNC_INTERVAL: Duration = Duration::from_secs(2); const DEVICE_SYNC_INTERVAL: Duration = Duration::from_secs(2);
const LOCAL_SEED_RECHECK_MS: i64 = 60 * 1000; const LOCAL_SEED_RECHECK_MS: i64 = 60 * 1000;
const MAX_LINE: usize = 8 * 1024 * 1024; const MAX_LINE: usize = 8 * 1024 * 1024;
/// Playback commands carry queue state but are useful only briefly and only
/// to their addressed device. They must not inflate a new peer's catch-up.
const PLAYBACK_COMMAND_TTL_MS: i64 = 5 * 60 * 1_000;
const MAX_OPS_PER_BATCH: i64 = 1000; const MAX_OPS_PER_BATCH: i64 = 1000;
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
@@ -84,6 +87,7 @@ struct Identity {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
struct StoredDevice { struct StoredDevice {
device_id: String, device_id: String,
endpoint_id: String,
endpoint_ticket: String, endpoint_ticket: String,
} }
@@ -1573,8 +1577,7 @@ async fn sync_device(
user_id: i64, user_id: i64,
device: &StoredDevice, device: &StoredDevice,
) -> Result<()> { ) -> Result<()> {
let ticket: PeerTicket = device.endpoint_ticket.parse()?; let peer = resolve_device_peer(&service, device).await?;
let peer = service.connect(ticket).await?;
let own_ticket = service.ticket().await?.to_string(); let own_ticket = service.ticket().await?.to_string();
let identity = ensure_identity(pool, user_id, "").await?; let identity = ensure_identity(pool, user_id, "").await?;
let profile = own_profile(pool, user_id, "", &own_ticket).await?; let profile = own_profile(pool, user_id, "", &own_ticket).await?;
@@ -3420,12 +3423,16 @@ async fn local_playback_snapshot(
user_id: i64, user_id: i64,
identity: &Identity, identity: &Identity,
) -> Option<PlaybackSnapshot> { ) -> Option<PlaybackSnapshot> {
let state = hub.current_playback_state_json(user_id)?; // Keep publishing an inactive snapshot after a handoff. Omitting the
// snapshot left the last `active: true` value alive on trusted peers until
// its TTL elapsed, allowing the always-on web peer to reclaim playback.
let active = hub.federation_playback_is_local(user_id);
let state = hub.playback_state_json_for_commands(user_id)?;
let wire = playback_state_from_browser_json(pool, state).await.ok()?; let wire = playback_state_from_browser_json(pool, state).await.ok()?;
Some(PlaybackSnapshot { Some(PlaybackSnapshot {
device_id: identity.device_id.clone(), device_id: identity.device_id.clone(),
device_name: identity.name.clone(), device_name: identity.name.clone(),
active: true, active,
updated_at_ms: now_ms(), updated_at_ms: now_ms(),
state: wire, state: wire,
}) })
@@ -4118,7 +4125,7 @@ pub async fn playlist_content_ids_for_removal(
async fn active_remote_devices(pool: &sqlx::PgPool, user_id: i64) -> Result<Vec<StoredDevice>> { async fn active_remote_devices(pool: &sqlx::PgPool, user_id: i64) -> Result<Vec<StoredDevice>> {
let identity = ensure_identity(pool, user_id, "").await?; let identity = ensure_identity(pool, user_id, "").await?;
let rows = sqlx::query( let rows = sqlx::query(
"SELECT device_id, endpoint_ticket "SELECT device_id, endpoint_id, endpoint_ticket
FROM furumusic__fed_device FROM furumusic__fed_device
WHERE user_id = $1 WHERE user_id = $1
AND trusted_at_ms IS NOT NULL AND trusted_at_ms IS NOT NULL
@@ -4134,11 +4141,31 @@ async fn active_remote_devices(pool: &sqlx::PgPool, user_id: i64) -> Result<Vec<
.into_iter() .into_iter()
.map(|row| StoredDevice { .map(|row| StoredDevice {
device_id: row.get("device_id"), device_id: row.get("device_id"),
endpoint_id: row.get("endpoint_id"),
endpoint_ticket: row.get("endpoint_ticket"), endpoint_ticket: row.get("endpoint_ticket"),
}) })
.collect()) .collect())
} }
async fn resolve_device_peer(
service: &MusicDhtService,
device: &StoredDevice,
) -> Result<music_dht::EndpointId> {
if let Ok(peer) = device.endpoint_id.parse::<music_dht::EndpointId>()
&& (service.connected_peers().contains(&peer)
|| service
.known_peers()
.iter()
.any(|contact| contact.peer_id == peer))
{
// Prefer the live/current-schema DHT contact over a persisted ticket
// that may have been issued before a schema upgrade.
return Ok(peer);
}
let ticket: PeerTicket = device.endpoint_ticket.parse()?;
service.connect(ticket).await.map_err(Into::into)
}
async fn active_device_count(pool: &sqlx::PgPool, user_id: i64) -> Result<i64> { async fn active_device_count(pool: &sqlx::PgPool, user_id: i64) -> Result<i64> {
sqlx::query_scalar( sqlx::query_scalar(
"SELECT COUNT(*) FROM furumusic__fed_device "SELECT COUNT(*) FROM furumusic__fed_device
@@ -4202,11 +4229,19 @@ async fn ops_for_peer(
AND a.origin_device_id = o.origin_device_id AND a.origin_device_id = o.origin_device_id
WHERE o.user_id = $1 WHERE o.user_id = $1
AND o.seq > COALESCE(a.max_seq, 0) AND o.seq > COALESCE(a.max_seq, 0)
AND (
o.kind != 'playback_command'
OR (
o.hlc_ms >= $3
AND o.payload_json->>'target_device_id' = $2
)
)
ORDER BY o.hlc_ms, o.op_id ORDER BY o.hlc_ms, o.op_id
LIMIT $3", LIMIT $4",
) )
.bind(user_id) .bind(user_id)
.bind(peer_device_id) .bind(peer_device_id)
.bind(now_ms().saturating_sub(PLAYBACK_COMMAND_TTL_MS))
.bind(MAX_OPS_PER_BATCH) .bind(MAX_OPS_PER_BATCH)
.fetch_all(pool) .fetch_all(pool)
.await?; .await?;
+205 -6
View File
@@ -5,17 +5,21 @@
//! releases, tracks — names and small metadata, never files) into the //! releases, tracks — names and small metadata, never files) into the
//! shared DHT and serves audio, track metadata, cover art and per-artist //! shared DHT and serves audio, track metadata, cover art and per-artist
//! catalogs to other peers (TUI clients) over the same wire protocols the //! catalogs to other peers (TUI clients) over the same wire protocols the
//! clients speak among themselves. Serve-only: the server does not search //! clients speak among themselves. The web player also searches known peers
//! or download from other peers. //! for catalog metadata and, when enabled, compatible similarity embeddings;
//! local playback and the local library remain independent of the network.
//! //!
//! Settings are the regular admin config entries (`federation_enabled`, //! Settings are the regular admin config entries (`federation_enabled`,
//! `federation_network_id`, `federation_save_on_listen`) and apply on the fly — saving the settings //! `federation_network_id`, `federation_save_on_listen`) and apply on the fly —
//! starts, stops or re-joins the node without a server restart. //! saving the settings starts, stops or re-joins the node without a server
//! restart.
mod capabilities;
pub mod client; pub mod client;
pub mod devices; pub mod devices;
mod receive; mod receive;
mod serve; mod serve;
mod similarity;
mod storage; mod storage;
use std::collections::{HashMap, HashSet, VecDeque}; use std::collections::{HashMap, HashSet, VecDeque};
@@ -24,6 +28,9 @@ use std::sync::{Arc, OnceLock};
use std::time::Duration; use std::time::Duration;
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use music_dht::capabilities::CAPABILITIES_ALPN;
use music_dht::similarity_dht::SimilarityDht;
use music_dht::similarity_lsh::SIMILARITY_DHT_ALPN;
use music_dht::{ use music_dht::{
ByteStream, ByteStreamConnectionStats, ItemKind, ItemSpec, MusicDhtConfig, MusicDhtService, ByteStream, ByteStreamConnectionStats, ItemKind, ItemSpec, MusicDhtConfig, MusicDhtService,
NetworkId, PeerTicket, PublishStats, RendezvousConfig, SyncStats, NetworkId, PeerTicket, PublishStats, RendezvousConfig, SyncStats,
@@ -36,6 +43,7 @@ use crate::config::AppConfig;
use storage::PostgresFederationStorage; use storage::PostgresFederationStorage;
pub use serve::{AUDIO_ALPN, CATALOG_ALPN}; pub use serve::{AUDIO_ALPN, CATALOG_ALPN};
pub use similarity::SIMILARITY_ALPN;
/// How often the published library is re-synchronized with the database. /// How often the published library is re-synchronized with the database.
const SYNC_INTERVAL: Duration = Duration::from_secs(60); const SYNC_INTERVAL: Duration = Duration::from_secs(60);
@@ -43,6 +51,7 @@ const TRANSPORT_SAMPLE_LIMIT: usize = 16;
struct Running { struct Running {
service: Arc<MusicDhtService>, service: Arc<MusicDhtService>,
similarity_dht: Arc<SimilarityDht>,
network_name: String, network_name: String,
tasks: Vec<tokio::task::JoinHandle<()>>, tasks: Vec<tokio::task::JoinHandle<()>>,
} }
@@ -122,6 +131,7 @@ struct TransportStatsState {
audio_samples: u64, audio_samples: u64,
catalog_samples: u64, catalog_samples: u64,
sync_samples: u64, sync_samples: u64,
similarity_samples: u64,
last: VecDeque<TransportSample>, last: VecDeque<TransportSample>,
} }
@@ -155,6 +165,7 @@ impl TransportStats {
"audio" => state.audio_samples += 1, "audio" => state.audio_samples += 1,
"catalog" => state.catalog_samples += 1, "catalog" => state.catalog_samples += 1,
"device-sync" => state.sync_samples += 1, "device-sync" => state.sync_samples += 1,
"similarity" => state.similarity_samples += 1,
_ => {} _ => {}
} }
state.last.push_front(sample); state.last.push_front(sample);
@@ -175,6 +186,7 @@ impl TransportStats {
"audio_samples": state.audio_samples, "audio_samples": state.audio_samples,
"catalog_samples": state.catalog_samples, "catalog_samples": state.catalog_samples,
"sync_samples": state.sync_samples, "sync_samples": state.sync_samples,
"similarity_samples": state.similarity_samples,
"last_path": latest.map(|sample| sample.selected_path.clone()), "last_path": latest.map(|sample| sample.selected_path.clone()),
"last_rtt_ms": latest.and_then(|sample| sample.selected_rtt_ms), "last_rtt_ms": latest.and_then(|sample| sample.selected_rtt_ms),
"last_peer": latest.map(|sample| sample.peer_id.clone()), "last_peer": latest.map(|sample| sample.peer_id.clone()),
@@ -201,6 +213,50 @@ impl TransportStats {
} }
} }
async fn enrich_transport_users(pool: &PgPool, transport: &mut Value) {
let Some(samples) = transport.get_mut("last").and_then(Value::as_array_mut) else {
return;
};
let peer_ids: Vec<String> = samples
.iter()
.filter_map(|sample| sample.get("peer_id").and_then(Value::as_str))
.map(str::to_owned)
.collect();
if peer_ids.is_empty() {
return;
}
let Ok(rows) = sqlx::query(
"SELECT DISTINCT ON (d.endpoint_id)
d.endpoint_id,
COALESCE(NULLIF(u.display_name, ''), u.username::text) AS user_name
FROM furumusic__fed_device d
JOIN furumusic__user u ON u.id = d.user_id
WHERE d.endpoint_id = ANY($1) AND d.revoked_at_ms IS NULL
ORDER BY d.endpoint_id, d.last_seen_ms DESC NULLS LAST",
)
.bind(&peer_ids)
.fetch_all(pool)
.await
else {
return;
};
let users: HashMap<String, String> = rows
.into_iter()
.map(|row| (row.get("endpoint_id"), row.get("user_name")))
.collect();
for sample in samples {
let Some(peer_id) = sample.get("peer_id").and_then(Value::as_str) else {
continue;
};
let Some(user_name) = users.get(peer_id) else {
continue;
};
if let Some(object) = sample.as_object_mut() {
object.insert("user_name".to_owned(), Value::String(user_name.clone()));
}
}
}
pub fn record_stream_transport( pub fn record_stream_transport(
stats: &Arc<TransportStats>, stats: &Arc<TransportStats>,
protocol: &'static str, protocol: &'static str,
@@ -212,7 +268,8 @@ pub fn record_stream_transport(
} }
pub struct Federation { pub struct Federation {
/// Transport data directory; server-side DHT state and identity live in PostgreSQL. /// Transport files and replaceable similarity-routing cache. Durable
/// catalog DHT state and identity live in PostgreSQL.
data_dir: PathBuf, data_dir: PathBuf,
database_url: std::sync::Mutex<String>, database_url: std::sync::Mutex<String>,
storage_dir: std::sync::Mutex<String>, storage_dir: std::sync::Mutex<String>,
@@ -371,6 +428,9 @@ impl Federation {
let dht_storage = Arc::new(PostgresFederationStorage::new(pool.clone()).await?); let dht_storage = Arc::new(PostgresFederationStorage::new(pool.clone()).await?);
let secret_key = dht_storage.load_or_create_secret_key().await?; let secret_key = dht_storage.load_or_create_secret_key().await?;
self.transport_stats.reset(); self.transport_stats.reset();
tokio::fs::create_dir_all(&self.data_dir)
.await
.with_context(|| format!("creating {}", self.data_dir.display()))?;
let config = MusicDhtConfig::builder() let config = MusicDhtConfig::builder()
.data_dir(&self.data_dir) .data_dir(&self.data_dir)
@@ -380,6 +440,9 @@ impl Federation {
.stream_protocol(AUDIO_ALPN) .stream_protocol(AUDIO_ALPN)
.stream_protocol(CATALOG_ALPN) .stream_protocol(CATALOG_ALPN)
.stream_protocol(devices::SYNC_ALPN) .stream_protocol(devices::SYNC_ALPN)
.schema_independent_stream_protocol(SIMILARITY_ALPN)
.schema_independent_stream_protocol(SIMILARITY_DHT_ALPN)
.schema_independent_stream_protocol(CAPABILITIES_ALPN)
.build() .build()
.map_err(|err| anyhow::anyhow!("invalid federation config: {err}"))?; .map_err(|err| anyhow::anyhow!("invalid federation config: {err}"))?;
let (service, mut events) = let (service, mut events) =
@@ -393,6 +456,25 @@ impl Federation {
"federation started" "federation started"
); );
let similarity_dht = SimilarityDht::open(
Arc::clone(&service),
self.data_dir.join("similarity-routing.sqlite3"),
)
.await
.map_err(|error| anyhow::anyhow!("failed to start the similarity DHT: {error}"))?;
let similarity_dht_acceptor = service
.stream_acceptor(SIMILARITY_DHT_ALPN)
.map_err(|error| anyhow::anyhow!("failed to take similarity DHT acceptor: {error}"))?;
let similarity_dht_serve_task =
tokio::spawn(Arc::clone(&similarity_dht).serve(similarity_dht_acceptor));
let similarity_dht_maintenance_task =
tokio::spawn(Arc::clone(&similarity_dht).maintenance());
let similarity_manager = crate::similarity::handle();
let similarity_dht_sync_task = tokio::spawn(similarity_route_sync_loop(
Arc::clone(&similarity_dht),
Arc::clone(&similarity_manager),
));
// Drain DHT events into the log; the channel is bounded. // Drain DHT events into the log; the channel is bounded.
let event_task = tokio::spawn(async move { let event_task = tokio::spawn(async move {
while let Some(event) = events.recv().await { while let Some(event) = events.recv().await {
@@ -447,9 +529,23 @@ impl Federation {
device_hub, device_hub,
Arc::clone(&self.transport_stats), Arc::clone(&self.transport_stats),
)); ));
let capabilities_acceptor = service
.stream_acceptor(CAPABILITIES_ALPN)
.map_err(|err| anyhow::anyhow!("failed to take the capabilities acceptor: {err}"))?;
let capabilities_task = tokio::spawn(capabilities::serve(capabilities_acceptor));
let similarity_acceptor = service
.stream_acceptor(SIMILARITY_ALPN)
.map_err(|err| anyhow::anyhow!("failed to take the similarity acceptor: {err}"))?;
let similarity_task = tokio::spawn(similarity::serve_peers(
similarity_acceptor,
similarity_manager,
service.endpoint_id(),
Arc::clone(&self.transport_stats),
));
*guard = Some(Running { *guard = Some(Running {
service, service,
similarity_dht,
network_name, network_name,
tasks: vec![ tasks: vec![
event_task, event_task,
@@ -458,6 +554,11 @@ impl Federation {
catalog_task, catalog_task,
device_task, device_task,
device_sync_task, device_sync_task,
capabilities_task,
similarity_task,
similarity_dht_serve_task,
similarity_dht_maintenance_task,
similarity_dht_sync_task,
], ],
}); });
self.set_error(None); self.set_error(None);
@@ -481,6 +582,20 @@ impl Federation {
.context("federation is not running") .context("federation is not running")
} }
async fn similarity_services(&self) -> Result<(Arc<MusicDhtService>, Arc<SimilarityDht>)> {
self.running
.lock()
.await
.as_ref()
.map(|running| {
(
Arc::clone(&running.service),
Arc::clone(&running.similarity_dht),
)
})
.context("federation is not running")
}
async fn spawn_sync_soon(self: &Arc<Self>) { async fn spawn_sync_soon(self: &Arc<Self>) {
if let Ok(service) = self.service().await { if let Ok(service) = self.service().await {
let fed = Arc::clone(self); let fed = Arc::clone(self);
@@ -778,14 +893,19 @@ impl Federation {
.iter() .iter()
.map(|p| p.to_string()) .map(|p| p.to_string())
.collect(); .collect();
let mut transport = self.transport_stats.snapshot();
if let Ok(pool) = self.pool().await {
enrich_transport_users(&pool, &mut transport).await;
}
json!({ json!({
"running": true, "running": true,
"network": running.network_name, "network": running.network_name,
"endpoint_id": service.endpoint_id().to_string(), "endpoint_id": service.endpoint_id().to_string(),
"connected_peers": peers, "connected_peers": peers,
"known_contacts": service.known_peers().len(), "known_contacts": service.known_peers().len(),
"similarity_routing_peers": running.similarity_dht.known_peers(),
"published_items": published, "published_items": published,
"transport": self.transport_stats.snapshot(), "transport": transport,
}) })
} }
None => json!({ "running": false }), None => json!({ "running": false }),
@@ -819,6 +939,26 @@ impl Federation {
Ok(peer.to_string()) Ok(peer.to_string())
} }
pub async fn search_similarity(
&self,
query: crate::similarity::QueryVector,
limit: usize,
) -> Result<similarity::SimilaritySearchOutcome> {
anyhow::ensure!(
crate::similarity::handle().enabled(),
"similarity search is disabled"
);
let (service, similarity_dht) = self.similarity_services().await?;
similarity::search(
service,
similarity_dht,
query,
limit,
Arc::clone(&self.transport_stats),
)
.await
}
pub async fn fed_device_status( pub async fn fed_device_status(
&self, &self,
user_id: i64, user_id: i64,
@@ -944,6 +1084,65 @@ impl Federation {
} }
} }
async fn similarity_route_sync_loop(
routing: Arc<SimilarityDht>,
manager: Arc<crate::similarity::Manager>,
) {
let mut interval = tokio::time::interval(SYNC_INTERVAL);
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let mut published_marker: Option<(String, blake3::Hash)> = None;
loop {
interval.tick().await;
if !manager.enabled() {
if published_marker.take().is_some() {
routing.clear_local_signatures();
tracing::info!("local similarity DHT publication disabled");
}
continue;
}
let status = manager.status();
let Some(profile_id) = status.active_profile else {
continue;
};
if status.phase != crate::similarity::Phase::Ready {
continue;
}
let signatures = match manager.routing_signatures(&profile_id).await {
Ok(signatures) => signatures,
Err(error) => {
tracing::warn!(%error, %profile_id, "similarity routing signatures unavailable");
continue;
}
};
let mut hasher = blake3::Hasher::new();
for signature in &signatures {
hasher.update(signature);
}
let marker = (profile_id.clone(), hasher.finalize());
if published_marker.as_ref() == Some(&marker) {
continue;
}
match routing
.sync_local_signatures(profile_id.clone(), signatures)
.await
{
Ok(stats) => {
tracing::info!(
profile = %profile_id,
records = stats.records,
keys = stats.keys,
remote_nodes = stats.remote_nodes,
"local similarity DHT index synchronized"
);
published_marker = Some(marker);
}
Err(error) => {
tracing::warn!(%error, %profile_id, "similarity DHT synchronization failed");
}
}
}
}
async fn persist_content_id( async fn persist_content_id(
pool: &PgPool, pool: &PgPool,
media_file_id: i64, media_file_id: i64,
+2
View File
@@ -21,6 +21,8 @@ use super::{TransportStats, record_stream_transport};
/// ALPN of the peer-to-peer audio streaming protocol. /// ALPN of the peer-to-peer audio streaming protocol.
pub const AUDIO_ALPN: &[u8] = b"furumi-fd/audio/1"; pub const AUDIO_ALPN: &[u8] = b"furumi-fd/audio/1";
/// Version of the peer-to-peer audio streaming protocol.
pub const AUDIO_PROTOCOL_VERSION: u16 = 1;
/// Maximum size of a JSON protocol line (request or response header). /// Maximum size of a JSON protocol line (request or response header).
const MAX_PROTOCOL_LINE: usize = 4096; const MAX_PROTOCOL_LINE: usize = 4096;
+398
View File
@@ -0,0 +1,398 @@
//! Furumusic policy and PostgreSQL adapter for the shared similarity protocol.
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::Duration;
use anyhow::{Context as _, Result};
use futures_util::stream::{self, StreamExt as _};
use music_dht::similarity::{self as wire, SimilarityHit, SimilarityRequest, SimilarityResponse};
use music_dht::similarity_dht::SimilarityDht;
use music_dht::{
ByteStream, EndpointId, ItemId, ItemKind, MusicDhtService, PeerTicket, StreamAcceptor,
};
use crate::similarity::{Manager, QueryVector};
use super::TransportStats;
pub use music_dht::similarity::SIMILARITY_ALPN;
const INITIAL_QUERY_PEERS: usize = 16;
const MAX_QUERY_PEERS: usize = 48;
const QUERY_CONCURRENCY: usize = 8;
const QUERY_TIMEOUT: Duration = Duration::from_secs(5);
const ROUTING_TIMEOUT: Duration = Duration::from_secs(5);
const MAX_PER_ARTIST: usize = 3;
const MAX_NEAR_DUPLICATE_SIGNATURE_DISTANCE: u32 = 8;
#[derive(Debug, Clone)]
pub struct RemoteSimilarityTrack {
pub owner: String,
pub item_id: String,
pub title: String,
pub artist_names: Vec<String>,
pub featured_artist_names: Vec<String>,
pub year: Option<i32>,
pub duration_seconds: Option<i64>,
pub content_id: Option<String>,
pub release_title: Option<String>,
pub track_number: Option<i32>,
pub disc_number: Option<i32>,
pub similarity_score: f32,
}
pub struct SimilaritySearchOutcome {
pub tracks: Vec<RemoteSimilarityTrack>,
pub queried_peers: usize,
}
pub async fn serve_peers(
mut acceptor: StreamAcceptor,
manager: Arc<Manager>,
own: EndpointId,
transport: Arc<TransportStats>,
) {
while let Some(stream) = acceptor.accept().await {
let manager = Arc::clone(&manager);
let transport = Arc::clone(&transport);
tokio::spawn(async move {
let peer = stream.peer_id;
if let Err(error) = serve_one(stream, manager, own, transport).await {
tracing::warn!(peer = %peer, "similarity request failed: {error:#}");
}
});
}
}
async fn serve_one(
mut stream: ByteStream,
manager: Arc<Manager>,
own: EndpointId,
transport: Arc<TransportStats>,
) -> Result<()> {
super::record_stream_transport(&transport, "similarity", "inbound", "open", &stream);
let request = wire::read_request(&mut stream).await?;
let response = if !manager.enabled() {
SimilarityResponse::refused("similarity search is disabled on this instance")?
} else {
let profile_id = request.profile_id;
let vector = request.vector;
let limit = request.limit;
let rank_manager = Arc::clone(&manager);
let ranked = tokio::task::spawn_blocking(move || {
rank_manager.rank_vector(&profile_id, &vector, None, None, limit)
})
.await
.context("local similarity task failed")
.and_then(|result| result);
match ranked {
Ok(ranked) => {
let ids = ranked
.iter()
.map(|track| track.track_id)
.collect::<Vec<_>>();
match manager.metadata_for_tracks(&ids).await {
Ok(metadata) => {
let by_id = ranked
.into_iter()
.map(|track| (track.track_id, track))
.collect::<HashMap<_, _>>();
let hits = metadata
.into_iter()
.filter_map(|track| {
let ranked = by_id.get(&track.track_id)?;
let hit = SimilarityHit {
score: ranked.score,
item_id: hex(
ItemId::derive(
&own,
ItemKind::Track,
&format!("track:{}", track.track_id),
)
.as_bytes(),
),
title: track.title,
artist_names: track.artist_names,
featured_artist_names: track.featured_artist_names,
year: track.year,
duration_seconds: Some(track.duration_seconds.round() as i64),
content_id: track.content_id,
release_title: Some(track.release_title),
track_number: track.track_number,
disc_number: track.disc_number,
embedding_signature: Some(ranked.embedding_signature),
};
match hit.validate() {
Ok(()) => Some(hit),
Err(error) => {
tracing::debug!(%error, "invalid local similarity metadata skipped");
None
}
}
})
.collect();
SimilarityResponse::success(hits)?
}
Err(error) => SimilarityResponse::refused(format!(
"similarity metadata is unavailable: {error:#}"
))?,
}
}
Err(error) => {
SimilarityResponse::refused(format!("similarity query is unavailable: {error:#}"))?
}
}
};
wire::write_response(&mut stream, &response).await?;
stream.send.finish()?;
let _ = stream.send.stopped().await;
super::record_stream_transport(&transport, "similarity", "inbound", "done", &stream);
Ok(())
}
pub async fn search(
service: Arc<MusicDhtService>,
routing: Arc<SimilarityDht>,
query: QueryVector,
limit: usize,
transport: Arc<TransportStats>,
) -> Result<SimilaritySearchOutcome> {
let own = service.endpoint_id();
let routed = match tokio::time::timeout(
ROUTING_TIMEOUT,
routing.find_peers(&query.profile_id, &query.vector, MAX_QUERY_PEERS),
)
.await
{
Ok(Ok(peers)) => peers,
Err(_) => {
tracing::debug!("similarity DHT lookup timed out; using known peers");
Vec::new()
}
Ok(Err(error)) => {
tracing::debug!(%error, "similarity DHT lookup unavailable; using known peers");
Vec::new()
}
};
let mut seen = HashSet::new();
let mut peers: Vec<QueryPeer> = routed
.into_iter()
.filter_map(|ticket| {
let owner = ticket.endpoint_id();
(owner != own && seen.insert(owner)).then_some(QueryPeer {
owner,
ticket: Some(ticket),
})
})
.collect();
for peer in service
.connected_peers()
.into_iter()
.chain(service.known_peers().into_iter().map(|peer| peer.peer_id))
{
if peer != own && seen.insert(peer) {
peers.push(QueryPeer {
owner: peer,
ticket: None,
});
}
if peers.len() >= MAX_QUERY_PEERS {
break;
}
}
let query_signature = wire::embedding_signature(&query.vector)?;
let request = Arc::new(SimilarityRequest::new(
query.profile_id,
query.vector,
limit.clamp(1, wire::MAX_SIMILARITY_RESULTS),
)?);
let mut hits = Vec::new();
let initial = peers.len().min(INITIAL_QUERY_PEERS);
let mut queried_peers = initial;
let responses = query_peers(
Arc::clone(&service),
&peers[..initial],
Arc::clone(&request),
Arc::clone(&transport),
)
.await;
let mut successful = 0usize;
for response in responses {
match response {
Ok(peer_hits) => {
successful += 1;
hits.extend(peer_hits);
}
Err(error) => tracing::debug!(%error, "similarity peer query skipped"),
}
}
if initial < peers.len() && (hits.len() < limit || successful < initial.min(4)) {
queried_peers += peers.len() - initial;
for response in query_peers(
Arc::clone(&service),
&peers[initial..],
Arc::clone(&request),
Arc::clone(&transport),
)
.await
{
match response {
Ok(peer_hits) => hits.extend(peer_hits),
Err(error) => tracing::debug!(%error, "fallback similarity peer query skipped"),
}
}
}
hits.sort_by(|left, right| right.1.total_cmp(&left.1));
let mut dedup = HashSet::new();
let mut signatures = vec![query_signature];
let mut artist_counts: HashMap<String, usize> = HashMap::new();
let mut tracks = Vec::new();
for (track, _, signature) in hits {
if query
.source_content_id
.as_deref()
.is_some_and(|source| track.content_id.as_deref() == Some(source))
{
continue;
}
let key = track
.content_id
.clone()
.unwrap_or_else(|| format!("{}:{}", track.owner, track.item_id));
if !dedup.insert(key) {
continue;
}
if signature.is_some_and(|candidate| {
signatures.iter().any(|existing| {
wire::signature_distance(&candidate, existing)
<= MAX_NEAR_DUPLICATE_SIGNATURE_DISTANCE
})
}) {
continue;
}
let artist = track
.artist_names
.first()
.map(|name| music_dht::normalize_name(name))
.unwrap_or_default();
let count = artist_counts.entry(artist.clone()).or_default();
if !artist.is_empty() && *count >= MAX_PER_ARTIST {
continue;
}
*count += 1;
if let Some(signature) = signature {
signatures.push(signature);
}
tracks.push(track);
if tracks.len() >= limit.min(wire::MAX_SIMILARITY_RESULTS) {
break;
}
}
Ok(SimilaritySearchOutcome {
tracks,
queried_peers,
})
}
type PeerHits = Vec<(
RemoteSimilarityTrack,
f32,
Option<[u8; wire::SIMILARITY_SIGNATURE_BYTES]>,
)>;
#[derive(Clone)]
struct QueryPeer {
owner: EndpointId,
ticket: Option<PeerTicket>,
}
async fn query_peers(
service: Arc<MusicDhtService>,
peers: &[QueryPeer],
request: Arc<SimilarityRequest>,
transport: Arc<TransportStats>,
) -> Vec<Result<PeerHits>> {
stream::iter(peers.iter().cloned().map(|peer| {
let service = Arc::clone(&service);
let request = Arc::clone(&request);
let transport = Arc::clone(&transport);
async move {
tokio::time::timeout(
QUERY_TIMEOUT,
query_peer(service, peer, &request, transport),
)
.await
.map_err(|_| anyhow::anyhow!("similarity peer timed out"))?
}
}))
.buffer_unordered(QUERY_CONCURRENCY)
.collect()
.await
}
async fn query_peer(
service: Arc<MusicDhtService>,
peer: QueryPeer,
request: &SimilarityRequest,
transport: Arc<TransportStats>,
) -> Result<PeerHits> {
let owner = peer.owner;
let mut stream = match peer.ticket {
Some(ticket) => service.open_stream_to(&ticket, SIMILARITY_ALPN).await,
None => service.open_stream(owner, SIMILARITY_ALPN).await,
}
.map_err(|error| anyhow::anyhow!("cannot reach similarity peer: {error}"))?;
super::record_stream_transport(&transport, "similarity", "outbound", "open", &stream);
let response = wire::exchange(&mut stream, request).await?;
super::record_stream_transport(&transport, "similarity", "outbound", "done", &stream);
anyhow::ensure!(
response.ok,
"peer refused similarity query: {}",
response.error.unwrap_or_default()
);
Ok(response
.hits
.into_iter()
.map(|hit| {
let score = hit.score;
let signature = hit.embedding_signature;
(
RemoteSimilarityTrack {
owner: owner.to_string(),
item_id: hit.item_id,
title: hit.title,
artist_names: hit.artist_names,
featured_artist_names: hit.featured_artist_names,
year: hit.year,
duration_seconds: hit.duration_seconds,
content_id: hit.content_id,
release_title: hit.release_title,
track_number: hit.track_number,
disc_number: hit.disc_number,
similarity_score: score,
},
score,
signature,
)
})
.collect())
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hamming_threshold_keeps_exact_and_near_duplicates_out() {
let query = [0u8; wire::SIMILARITY_SIGNATURE_BYTES];
let mut near = query;
near[0] = 0b0000_0111;
assert!(wire::signature_distance(&query, &near) <= MAX_NEAR_DUPLICATE_SIGNATURE_DISTANCE);
}
}
+75 -11
View File
@@ -96,9 +96,9 @@ translations! {
settings_swagger: "Swagger UI" , "Swagger UI"; settings_swagger: "Swagger UI" , "Swagger UI";
settings_swagger_help: "Serves interactive API docs at /swagger/ (requires restart)" , "Интерактивная документация API на /swagger/ (требуется перезапуск)"; settings_swagger_help: "Serves interactive API docs at /swagger/ (requires restart)" , "Интерактивная документация API на /swagger/ (требуется перезапуск)";
settings_lastfm_api_key: "Last.fm API key" , "API ключ Last.fm"; settings_lastfm_api_key: "Last.fm API key" , "API ключ Last.fm";
settings_lastfm_api_key_help: "Used for Last.fm popularity and account connection" , "Используется для популярности Last.fm и подключения аккаунта"; settings_lastfm_api_key_help: "Identifies this application to Last.fm and enables metadata, popularity data, and user account connection" , "Идентифицирует приложение в Last.fm и включает метаданные, данные о популярности и подключение аккаунтов";
settings_lastfm_shared_secret: "Last.fm shared secret" , "Shared secret Last.fm"; settings_lastfm_shared_secret: "Last.fm shared secret" , "Shared secret Last.fm";
settings_lastfm_shared_secret_help: "Required for signed Last.fm scrobbling requests" , "Нужен для подписанных запросов скробблинга Last.fm"; settings_lastfm_shared_secret_help: "Authenticates signed Last.fm requests, including scrobbling. Keep this value private" , "Подтверждает подписанные запросы Last.fm, включая скробблинг. Не раскрывайте это значение";
// OIDC login errors // OIDC login errors
login_oidc_error: "SSO login failed. Please try again." , "Ошибка входа через SSO. Попробуйте ещё раз."; login_oidc_error: "SSO login failed. Please try again." , "Ошибка входа через SSO. Попробуйте ещё раз.";
@@ -298,6 +298,9 @@ translations! {
player_likes_playlist: "Likes" , "Лайки"; player_likes_playlist: "Likes" , "Лайки";
player_listened: "listened" , "прослушано"; player_listened: "listened" , "прослушано";
player_search_placeholder: "Search artists, releases, tracks..." , "Поиск артистов, релизов, треков..."; player_search_placeholder: "Search artists, releases, tracks..." , "Поиск артистов, релизов, треков...";
player_search_similar_to: "Search similar to:" , "Поиск похожих на:";
player_find_similar: "Find similar tracks" , "Найти похожие треки";
player_similarity_failed: "Similarity search failed" , "Не удалось найти похожие треки";
player_connection_lost: "Server connection lost" , "Нет соединения с сервером"; player_connection_lost: "Server connection lost" , "Нет соединения с сервером";
player_connection_lost_detail: "Player cannot reach the server. Retrying..." , "Плеер не может связаться с сервером. Повторяю..."; player_connection_lost_detail: "Player cannot reach the server. Retrying..." , "Плеер не может связаться с сервером. Повторяю...";
player_active_device: "Active device" , "Активный девайс"; player_active_device: "Active device" , "Активный девайс";
@@ -314,6 +317,9 @@ translations! {
player_delete_playlist_confirm: "Delete this playlist?" , "Удалить этот плейлист?"; player_delete_playlist_confirm: "Delete this playlist?" , "Удалить этот плейлист?";
player_rename: "Rename" , "Переименовать"; player_rename: "Rename" , "Переименовать";
player_close: "Close" , "Закрыть"; player_close: "Close" , "Закрыть";
player_interface_language: "Interface language" , "Язык интерфейса";
player_language_description: "Choose the language used by the web player." , "Выберите язык интерфейса веб-плеера.";
player_switch_language: "Русский" , "English";
player_log_out: "Log out" , "Выйти"; player_log_out: "Log out" , "Выйти";
player_admin_panel: "Admin Panel" , "Админка"; player_admin_panel: "Admin Panel" , "Админка";
player_info: "Info" , "Информация"; player_info: "Info" , "Информация";
@@ -383,9 +389,54 @@ translations! {
player_live_releases: "Live releases" , "Концертные релизы"; player_live_releases: "Live releases" , "Концертные релизы";
player_soundtracks: "Soundtracks" , "Саундтреки"; player_soundtracks: "Soundtracks" , "Саундтреки";
// Player torrent/history UI // Player download/history UI
player_torrent_manager: "Torrent manager" , "Торрент-менеджер"; player_torrent_manager: "Download Manager" , "Менеджер загрузок";
player_import_torrent: "Import torrent" , "Импортировать торрент"; player_import_torrent: "Open Download Manager" , "Открыть менеджер загрузок";
player_youtube: "YouTube" , "YouTube";
player_torrents: "Torrents" , "Торренты";
player_files: "Files" , "Файлы";
player_youtube_url: "Public video or playlist URL" , "Ссылка на открытое видео или плейлист";
player_youtube_url_hint: "Public youtube.com, music.youtube.com and youtu.be links are supported. Each video is imported as one AI batch." , "Поддерживаются открытые ссылки youtube.com, music.youtube.com и youtu.be. Каждое видео импортируется одним ИИ-батчем.";
player_youtube_downloads: "YouTube downloads" , "Загрузки YouTube";
player_no_youtube_downloads: "No YouTube downloads yet" , "Загрузок YouTube пока нет";
player_youtube_parse: "Check link" , "Проверить ссылку";
player_youtube_parsing: "Reading YouTube link..." , "Читаю ссылку YouTube...";
player_youtube_preview_failed: "Could not read YouTube link" , "Не удалось прочитать ссылку YouTube";
player_youtube_preview_title: "Choose videos to import" , "Выберите видео для импорта";
player_youtube_select_all: "Select all" , "Отметить все";
player_youtube_clear_selection: "Clear selection" , "Снять все";
player_youtube_selected_count: "selected" , "выбрано";
player_youtube_start_import: "Start import" , "Начать импорт";
player_start_download: "Start download" , "Начать загрузку";
player_retry_failed: "Retry failed" , "Повторить ошибки";
player_download_steps: "Processing steps" , "Этапы обработки";
player_chapters: "chapters" , "глав";
player_youtube_video: "video" , "видео";
player_youtube_playlist: "playlist" , "плейлист";
player_youtube_items: "videos" , "видео";
player_youtube_errors: "errors" , "ошибок";
player_youtube_queued: "Queued" , "В очереди";
player_youtube_resolving: "Reading link" , "Чтение ссылки";
player_youtube_postprocessing: "FFmpeg processing" , "Обработка FFmpeg";
player_youtube_awaiting_ai: "Waiting for AI" , "Ожидание ИИ";
player_youtube_ai_processing: "AI processing" , "Обработка ИИ";
player_youtube_needs_review: "Needs review" , "Требует проверки";
player_youtube_complete_with_errors: "Completed with errors" , "Завершено с ошибками";
player_youtube_skipped: "Already imported" , "Уже импортировано";
player_youtube_cancelled: "Stopped" , "Остановлено";
player_youtube_stop: "Stop import" , "Остановить импорт";
player_youtube_stop_confirm: "Stop this YouTube import? Completed and already published audio will remain." , "Остановить этот импорт из YouTube? Готовое и уже переданное на обработку аудио останется.";
player_youtube_stopping: "Stopping YouTube import..." , "Останавливаю импорт из YouTube...";
player_youtube_stopped: "YouTube import stopped." , "Импорт из YouTube остановлен.";
player_youtube_stop_failed: "Could not stop YouTube import" , "Не удалось остановить импорт из YouTube";
player_youtube_starting: "Adding YouTube download..." , "Добавляю загрузку YouTube...";
player_youtube_started: "YouTube download added." , "Загрузка YouTube добавлена.";
player_youtube_load_failed: "Could not load YouTube downloads" , "Не удалось загрузить список YouTube";
player_youtube_start_failed: "Could not start YouTube download" , "Не удалось начать загрузку YouTube";
player_youtube_retry_failed: "Could not retry YouTube download" , "Не удалось повторить загрузку YouTube";
player_youtube_delete_failed: "Could not remove YouTube download" , "Не удалось удалить загрузку YouTube";
player_youtube_delete_confirm: "Remove this YouTube download from history? Imported audio will remain." , "Удалить эту загрузку YouTube из истории? Импортированное аудио останется.";
player_remove_from_history: "Remove from history" , "Удалить из истории";
player_client_idle: "Client idle" , "Клиент простаивает"; player_client_idle: "Client idle" , "Клиент простаивает";
player_active: "active" , "активно"; player_active: "active" , "активно";
player_ai_idle: "AI idle" , "ИИ простаивает"; player_ai_idle: "AI idle" , "ИИ простаивает";
@@ -461,11 +512,24 @@ translations! {
player_track_approved_imported: "Track approved and imported" , "Трек подтверждён и импортирован"; player_track_approved_imported: "Track approved and imported" , "Трек подтверждён и импортирован";
player_failed_update_selected_tracks: "Failed to update selected tracks" , "Не удалось обновить выбранные треки"; player_failed_update_selected_tracks: "Failed to update selected tracks" , "Не удалось обновить выбранные треки";
player_selected_tracks_updated: "Selected tracks updated" , "Выбранные треки обновлены"; player_selected_tracks_updated: "Selected tracks updated" , "Выбранные треки обновлены";
player_choose_saved_or_add_torrent: "Choose a saved item or upload new files." , "Выберите сохранённый элемент или загрузите новые файлы."; player_choose_saved_or_add_torrent: "Choose a saved torrent or add a new one." , "Выберите сохранённый торрент или добавьте новый.";
player_local_files: "Local audio files" , "Локальные аудиофайлы"; player_local_files: "Local audio files" , "Локальные аудиофайлы";
player_file_uploads: "File uploads" , "Загрузки файлов";
player_drop_audio_title: "Drop audio files here" , "Перетащите аудиофайлы сюда";
player_drop_audio_hint: "or click to choose files" , "или нажмите, чтобы выбрать файлы";
player_drop_audio_formats: "MP3, FLAC, WAV, M4A, OGG, Opus and AAC" , "MP3, FLAC, WAV, M4A, OGG, Opus и AAC";
player_upload_selected_files: "Upload selected files" , "Загрузить выбранные файлы";
player_upload_history: "Upload history" , "История загрузок";
player_no_file_uploads: "No file uploads yet" , "Загрузок файлов пока нет";
player_file_upload_load_failed: "Could not load file upload history" , "Не удалось загрузить историю файлов";
player_remove_file_upload_confirm: "Remove this file upload from history? Imported audio will remain." , "Удалить эту загрузку файла из истории? Импортированное аудио останется.";
player_file_upload_history_removed: "File upload removed from history." , "Загрузка файла удалена из истории.";
player_file_upload_history_remove_failed: "Could not remove file upload from history" , "Не удалось удалить загрузку файла из истории";
player_no_supported_audio_files: "Choose at least one supported audio file." , "Выберите хотя бы один поддерживаемый аудиофайл.";
player_torrent_file: "Torrent file" , "Torrent-файл"; player_torrent_file: "Torrent file" , "Torrent-файл";
player_magnet_link: "Magnet link" , "Magnet-ссылка"; player_magnet_link: "Magnet link" , "Magnet-ссылка";
player_upload_content: "Upload" , "Загрузить"; player_upload_content: "Preview torrent" , "Проверить торрент";
player_add_torrent: "Add torrent" , "Добавить торрент";
player_download_selected: "Download selected" , "Скачать выбранное"; player_download_selected: "Download selected" , "Скачать выбранное";
player_pause_download: "Pause download" , "Поставить на паузу"; player_pause_download: "Pause download" , "Поставить на паузу";
player_expand_all: "Expand all" , "Развернуть всё"; player_expand_all: "Expand all" , "Развернуть всё";
@@ -495,7 +559,7 @@ translations! {
player_no_plays_yet: "No plays yet" , "Прослушиваний пока нет"; player_no_plays_yet: "No plays yet" , "Прослушиваний пока нет";
player_page: "Page" , "Страница"; player_page: "Page" , "Страница";
player_of: "of" , "из"; player_of: "of" , "из";
player_choose_torrent: "Choose local files, paste a magnet link, or choose a .torrent file." , "Выберите локальные файлы, вставьте magnet-ссылку или выберите .torrent файл."; player_choose_torrent: "Paste a magnet link or choose a .torrent file." , "Вставьте magnet-ссылку или выберите .torrent файл.";
player_uploading_files: "Uploading files..." , "Загружаю файлы..."; player_uploading_files: "Uploading files..." , "Загружаю файлы...";
player_upload_complete: "Upload complete. Files are queued for processing." , "Загрузка завершена. Файлы поставлены в обработку."; player_upload_complete: "Upload complete. Files are queued for processing." , "Загрузка завершена. Файлы поставлены в обработку.";
player_upload_failed: "Upload failed" , "Загрузка не удалась"; player_upload_failed: "Upload failed" , "Загрузка не удалась";
@@ -505,8 +569,8 @@ translations! {
player_all_files_selected: "All files are selected by default. Clear or adjust the tree before download." , "Все файлы выбраны по умолчанию. Перед скачиванием можно очистить или изменить выбор."; player_all_files_selected: "All files are selected by default. Clear or adjust the tree before download." , "Все файлы выбраны по умолчанию. Перед скачиванием можно очистить или изменить выбор.";
player_opening_saved_torrent: "Opening saved torrent..." , "Открываю сохранённый торрент..."; player_opening_saved_torrent: "Opening saved torrent..." , "Открываю сохранённый торрент...";
player_saved_torrent_opened: "Saved torrent opened. Adjust files or resume download." , "Сохранённый торрент открыт. Можно изменить файлы или продолжить скачивание."; player_saved_torrent_opened: "Saved torrent opened. Adjust files or resume download." , "Сохранённый торрент открыт. Можно изменить файлы или продолжить скачивание.";
player_remove_torrent_confirm: "Remove this torrent from the client list? Downloaded files will stay on disk." , "Удалить этот торрент из списка клиента? Скачанные файлы останутся на диске."; player_remove_torrent_confirm: "Remove this torrent from history? Downloaded files will stay on disk." , "Удалить этот торрент из истории? Скачанные файлы останутся на диске.";
player_torrent_removed: "Torrent removed from the client list." , "Торрент удалён из списка клиента."; player_torrent_removed: "Torrent removed from history." , "Торрент удалён из истории.";
player_select_one_file: "Select at least one file." , "Выберите хотя бы один файл."; player_select_one_file: "Select at least one file." , "Выберите хотя бы один файл.";
player_starting_download: "Starting download..." , "Запускаю скачивание..."; player_starting_download: "Starting download..." , "Запускаю скачивание...";
player_download_started: "Download started. Files will move to inbox when complete." , "Скачивание началось. После завершения файлы будут перенесены во входящие."; player_download_started: "Download started. Files will move to inbox when complete." , "Скачивание началось. После завершения файлы будут перенесены во входящие.";
@@ -517,6 +581,6 @@ translations! {
player_pause_failed: "Pause failed" , "Не удалось поставить на паузу"; player_pause_failed: "Pause failed" , "Не удалось поставить на паузу";
player_load_torrents_failed: "Could not load torrents" , "Не удалось загрузить торренты"; player_load_torrents_failed: "Could not load torrents" , "Не удалось загрузить торренты";
player_open_torrent_failed: "Could not open torrent" , "Не удалось открыть торрент"; player_open_torrent_failed: "Could not open torrent" , "Не удалось открыть торрент";
player_delete_torrent_failed: "Could not delete torrent" , "Не удалось удалить торрент"; player_delete_torrent_failed: "Could not remove torrent from history" , "Не удалось удалить торрент из истории";
player_load_ai_queue_failed: "Could not load AI queue" , "Не удалось загрузить очередь ИИ"; player_load_ai_queue_failed: "Could not load AI queue" , "Не удалось загрузить очередь ИИ";
} }
+81 -16
View File
@@ -988,23 +988,59 @@ pub async fn finalize_approved(
})? })?
}; };
let media_file = MediaFile::create( let reusable_media_id: Option<i64> = sqlx::query_scalar(
db, r#"SELECT media.id
"audio", FROM furumusic__media_file media
&storage_path, WHERE media.file_type = 'audio'
original_filename, AND media.file_path = $1
mime_type, AND media.sha256_hash = $2
file_size, AND NOT EXISTS (
sha256, SELECT 1 FROM furumusic__track track
Some(ext), WHERE track.audio_file_id = media.id OR track.cover_file_id = media.id
audio_bitrate, )
audio_sample_rate, AND NOT EXISTS (
audio_bit_depth, SELECT 1 FROM furumusic__release release
uploaded_by_user_id, WHERE release.cover_file_id = media.id
Some(uploader_name), )
AND NOT EXISTS (
SELECT 1 FROM furumusic__artist artist
WHERE artist.image_file_id = media.id
)
AND NOT EXISTS (
SELECT 1 FROM furumusic__playlist playlist
WHERE playlist.cover_file_id = media.id
)
ORDER BY media.id
LIMIT 1"#,
) )
.await .bind(&storage_path)
.map_err(|e| anyhow::anyhow!("failed to create media file: {e}"))?; .bind(sha256)
.fetch_optional(pool)
.await?;
let media_file = if let Some(media_file_id) = reusable_media_id {
MediaFile::get_by_id(db, media_file_id)
.await
.map_err(|error| anyhow::anyhow!("failed to load reusable media file: {error}"))?
.ok_or_else(|| anyhow::anyhow!("reusable media file disappeared"))?
} else {
MediaFile::create(
db,
"audio",
&storage_path,
original_filename,
mime_type,
file_size,
sha256,
Some(ext),
audio_bitrate,
audio_sample_rate,
audio_bit_depth,
uploaded_by_user_id,
Some(uploader_name),
)
.await
.map_err(|e| anyhow::anyhow!("failed to create media file: {e}"))?
};
let track = Track::create( let track = Track::create(
db, db,
@@ -1020,6 +1056,35 @@ pub async fn finalize_approved(
.await .await
.map_err(|e| anyhow::anyhow!("failed to create track: {e}"))?; .map_err(|e| anyhow::anyhow!("failed to create track: {e}"))?;
if let Err(error) = sqlx::query(
r#"INSERT INTO furumusic__youtube_import_media (item_id, media_file_id)
SELECT DISTINCT item.id, $1
FROM furumusic__youtube_download_item item
JOIN furumusic__pending_review review
ON item.inbox_path IS NOT NULL
AND (review.input_path = item.inbox_path
OR left(review.input_path, length(item.inbox_path) + 1)
= item.inbox_path || '/')
WHERE review.context_json IS NOT NULL
AND substring(
review.context_json
from '"sha256"[[:space:]]*:[[:space:]]*"([0-9a-fA-F]{64})"'
) = $2
ON CONFLICT (item_id, media_file_id) DO NOTHING"#,
)
.bind(media_file.id_val())
.bind(sha256)
.execute(pool)
.await
{
tracing::warn!(
track_id = track.id_val(),
media_file_id = media_file.id_val(),
error = %error,
"failed to link imported media to its YouTube download item"
);
}
TrackArtist::create(db, track.id_val(), artist.id_val(), "main", 0) TrackArtist::create(db, track.id_val(), artist.id_val(), "main", 0)
.await .await
.map_err(|e| anyhow::anyhow!("failed to link track-artist: {e}"))?; .map_err(|e| anyhow::anyhow!("failed to link track-artist: {e}"))?;
+568
View File
@@ -0,0 +1,568 @@
use std::collections::HashSet;
use std::io::ErrorKind;
use std::path::PathBuf;
use anyhow::{Context, bail};
use sqlx::{FromRow, PgPool, Postgres, Transaction};
use uuid::Uuid;
#[derive(Debug, FromRow)]
struct MediaFileRow {
id: i64,
file_type: String,
file_path: String,
sha256_hash: String,
}
#[derive(Debug, FromRow)]
struct PlaybackStateRow {
id: i64,
current_track_id: Option<i64>,
position_ms: i32,
queue_json: String,
queue_position: i32,
}
#[derive(Debug)]
struct QuarantinedFile {
original: PathBuf,
quarantined: PathBuf,
}
#[derive(Debug, Default)]
struct Quarantine {
root: Option<PathBuf>,
files: Vec<QuarantinedFile>,
}
pub async fn delete_tracks(
pool: &PgPool,
requested_track_ids: &[i64],
storage_dir: &str,
) -> anyhow::Result<u64> {
delete_scope(pool, requested_track_ids, &[], storage_dir).await
}
pub async fn delete_releases(
pool: &PgPool,
requested_release_ids: &[i64],
storage_dir: &str,
) -> anyhow::Result<u64> {
let mut transaction = pool.begin().await?;
let release_ids: Vec<i64> = sqlx::query_scalar(
"SELECT id FROM furumusic__release WHERE id = ANY($1) ORDER BY id FOR UPDATE",
)
.bind(requested_release_ids)
.fetch_all(&mut *transaction)
.await?;
if release_ids.is_empty() {
transaction.rollback().await?;
return Ok(0);
}
let track_ids: Vec<i64> = sqlx::query_scalar(
"SELECT id FROM furumusic__track WHERE release_id = ANY($1) ORDER BY id FOR UPDATE",
)
.bind(&release_ids)
.fetch_all(&mut *transaction)
.await?;
delete_locked_scope(transaction, track_ids, release_ids, storage_dir, true).await
}
async fn delete_scope(
pool: &PgPool,
requested_track_ids: &[i64],
release_ids: &[i64],
storage_dir: &str,
) -> anyhow::Result<u64> {
let mut transaction = pool.begin().await?;
let track_ids: Vec<i64> = sqlx::query_scalar(
"SELECT id FROM furumusic__track WHERE id = ANY($1) ORDER BY id FOR UPDATE",
)
.bind(requested_track_ids)
.fetch_all(&mut *transaction)
.await?;
if track_ids.is_empty() {
transaction.rollback().await?;
return Ok(0);
}
delete_locked_scope(
transaction,
track_ids,
release_ids.to_vec(),
storage_dir,
false,
)
.await
}
async fn delete_locked_scope(
mut transaction: Transaction<'_, Postgres>,
track_ids: Vec<i64>,
release_ids: Vec<i64>,
storage_dir: &str,
delete_release_rows: bool,
) -> anyhow::Result<u64> {
let media_files = deletable_media_files(&mut transaction, &track_ids, &release_ids).await?;
let quarantine = match quarantine_media_files(storage_dir, &media_files).await {
Ok(quarantine) => quarantine,
Err(error) => {
transaction.rollback().await?;
return Err(error);
}
};
let deletion = delete_database_rows(
&mut transaction,
&track_ids,
&release_ids,
&media_files,
delete_release_rows,
)
.await;
let affected = match deletion {
Ok(affected) => affected,
Err(error) => {
transaction.rollback().await?;
restore_quarantine(&quarantine).await;
return Err(error);
}
};
if let Err(error) = transaction.commit().await {
restore_quarantine(&quarantine).await;
return Err(error.into());
}
purge_quarantine(&quarantine).await;
remove_empty_storage_parents(storage_dir, &quarantine.files).await;
Ok(affected)
}
async fn deletable_media_files(
transaction: &mut Transaction<'_, Postgres>,
track_ids: &[i64],
release_ids: &[i64],
) -> anyhow::Result<Vec<MediaFileRow>> {
Ok(sqlx::query_as(
r#"WITH seed_media(id) AS (
SELECT audio_file_id FROM furumusic__track WHERE id = ANY($1)
UNION
SELECT cover_file_id FROM furumusic__track
WHERE id = ANY($1) AND cover_file_id IS NOT NULL
UNION
SELECT cover_file_id FROM furumusic__release
WHERE id = ANY($2) AND cover_file_id IS NOT NULL
), candidate_media(id) AS (
SELECT id FROM seed_media
UNION
SELECT duplicate.id
FROM furumusic__media_file duplicate
JOIN furumusic__media_file seed
ON duplicate.file_path = seed.file_path
AND duplicate.sha256_hash = seed.sha256_hash
JOIN seed_media ON seed_media.id = seed.id
)
SELECT mf.id, mf.file_type::text AS file_type, mf.file_path,
mf.sha256_hash::text AS sha256_hash
FROM furumusic__media_file mf
JOIN candidate_media candidate ON candidate.id = mf.id
WHERE NOT EXISTS (
SELECT 1
FROM furumusic__track track
JOIN furumusic__media_file linked
ON linked.id = track.audio_file_id
OR linked.id = track.cover_file_id
WHERE linked.file_path = mf.file_path
AND linked.sha256_hash = mf.sha256_hash
AND NOT (track.id = ANY($1))
)
AND NOT EXISTS (
SELECT 1
FROM furumusic__release release
JOIN furumusic__media_file linked
ON linked.id = release.cover_file_id
WHERE linked.file_path = mf.file_path
AND linked.sha256_hash = mf.sha256_hash
AND NOT (release.id = ANY($2))
)
AND NOT EXISTS (
SELECT 1
FROM furumusic__artist artist
JOIN furumusic__media_file linked
ON linked.id = artist.image_file_id
WHERE linked.file_path = mf.file_path
AND linked.sha256_hash = mf.sha256_hash
)
AND NOT EXISTS (
SELECT 1
FROM furumusic__playlist playlist
JOIN furumusic__media_file linked
ON linked.id = playlist.cover_file_id
WHERE linked.file_path = mf.file_path
AND linked.sha256_hash = mf.sha256_hash
)
ORDER BY mf.id
FOR UPDATE OF mf"#,
)
.bind(track_ids)
.bind(release_ids)
.fetch_all(&mut **transaction)
.await?)
}
async fn quarantine_media_files(
storage_dir: &str,
media_files: &[MediaFileRow],
) -> anyhow::Result<Quarantine> {
if media_files.is_empty() {
return Ok(Quarantine::default());
}
if storage_dir.trim().is_empty() {
bail!("agent_storage_dir is not configured; refusing to leave deleted tracks on disk");
}
let storage_root = crate::media_paths::resolve_config_path_buf(storage_dir);
if storage_root.parent().is_none() {
bail!("agent_storage_dir must not be a filesystem root");
}
let quarantine_root = storage_root
.join(".furumusic-trash")
.join(Uuid::new_v4().to_string());
let mut quarantine = Quarantine {
root: Some(quarantine_root.clone()),
files: Vec::new(),
};
let mut seen = HashSet::new();
let result: anyhow::Result<()> =
async {
for media in media_files {
let original = checked_storage_path(storage_dir, &media.file_path)?;
let mut paths = vec![original.clone()];
if media.file_type == "cover_art" {
paths.extend(crate::agent::cover_variants::COVER_VARIANTS.iter().map(
|variant| crate::agent::cover_variants::variant_path(&original, *variant),
));
}
for (index, path) in paths.into_iter().enumerate() {
if !seen.insert(path.clone()) {
continue;
}
match tokio::fs::symlink_metadata(&path).await {
Ok(metadata) if metadata.is_file() || metadata.file_type().is_symlink() => {
}
Ok(_) => bail!("media path is not a regular file: {}", path.display()),
Err(error) if error.kind() == ErrorKind::NotFound => continue,
Err(error) => return Err(error.into()),
}
tokio::fs::create_dir_all(&quarantine_root).await?;
let extension = path
.extension()
.and_then(|value| value.to_str())
.unwrap_or("bin");
let quarantined = quarantine_root.join(format!(
"{}-{index}-{}.{}",
media.id,
Uuid::new_v4(),
extension
));
tokio::fs::rename(&path, &quarantined)
.await
.with_context(|| format!("failed to remove {}", path.display()))?;
quarantine.files.push(QuarantinedFile {
original: path,
quarantined,
});
}
}
Ok(())
}
.await;
match result {
Ok(()) => Ok(quarantine),
Err(error) => {
restore_quarantine(&quarantine).await;
Err(error)
}
}
}
fn checked_storage_path(storage_dir: &str, stored_path: &str) -> anyhow::Result<PathBuf> {
let resolved = crate::media_paths::resolve_media_file_path(storage_dir, stored_path);
crate::media_paths::path_for_root(storage_dir, &resolved).with_context(|| {
format!(
"refusing to delete media outside agent_storage_dir: {}",
resolved.display()
)
})?;
Ok(resolved)
}
async fn restore_quarantine(quarantine: &Quarantine) {
for file in quarantine.files.iter().rev() {
if let Some(parent) = file.original.parent() {
let _ = tokio::fs::create_dir_all(parent).await;
}
let _ = tokio::fs::rename(&file.quarantined, &file.original).await;
}
if let Some(root) = &quarantine.root {
let _ = tokio::fs::remove_dir_all(root).await;
}
}
async fn purge_quarantine(quarantine: &Quarantine) {
if let Some(root) = &quarantine.root
&& let Err(error) = tokio::fs::remove_dir_all(root).await
&& error.kind() != ErrorKind::NotFound
{
tracing::warn!(path = %root.display(), error = %error, "failed to purge deleted media quarantine");
}
if let Some(parent) = quarantine.root.as_deref().and_then(|root| root.parent()) {
let _ = tokio::fs::remove_dir(parent).await;
}
}
async fn remove_empty_storage_parents(storage_dir: &str, files: &[QuarantinedFile]) {
let storage_root = crate::media_paths::resolve_config_path_buf(storage_dir);
let mut seen = HashSet::new();
for file in files {
let mut current = file.original.parent();
while let Some(directory) = current {
if directory == storage_root || !directory.starts_with(&storage_root) {
break;
}
if !seen.insert(directory.to_path_buf()) {
break;
}
match tokio::fs::remove_dir(directory).await {
Ok(()) => current = directory.parent(),
Err(_) => break,
}
}
}
}
async fn delete_database_rows(
transaction: &mut Transaction<'_, Postgres>,
track_ids: &[i64],
release_ids: &[i64],
media_files: &[MediaFileRow],
delete_release_rows: bool,
) -> anyhow::Result<u64> {
cleanup_playback_states(transaction, track_ids).await?;
for table in [
"furumusic__playlist_track",
"furumusic__user_liked_track",
"furumusic__play_history",
"furumusic__track_popularity_history",
"furumusic__lastfm_scrobble_outbox",
"furumusic__track_genre",
"furumusic__track_artist",
"furumusic__track_embedding",
] {
let query = format!("DELETE FROM {table} WHERE track_id = ANY($1)");
sqlx::query(&query)
.bind(track_ids)
.execute(&mut **transaction)
.await?;
}
for table in [
"furumusic__entity_genre_tag",
"furumusic__external_metadata_id",
"furumusic__artwork_lookup_state",
] {
let query =
format!("DELETE FROM {table} WHERE entity_kind = 'track' AND entity_id = ANY($1)");
sqlx::query(&query)
.bind(track_ids)
.execute(&mut **transaction)
.await?;
}
for table in [
"furumusic__fed_state_like",
"furumusic__fed_state_playlist_item",
"furumusic__track_ref",
"furumusic__listen_event",
] {
let query =
format!("UPDATE {table} SET local_track_id = NULL WHERE local_track_id = ANY($1)");
sqlx::query(&query)
.bind(track_ids)
.execute(&mut **transaction)
.await?;
}
let tracks_deleted = sqlx::query("DELETE FROM furumusic__track WHERE id = ANY($1)")
.bind(track_ids)
.execute(&mut **transaction)
.await?
.rows_affected();
if delete_release_rows {
for table in [
"furumusic__entity_genre_tag",
"furumusic__external_metadata_id",
"furumusic__artwork_lookup_state",
] {
let query = format!(
"DELETE FROM {table} WHERE entity_kind = 'release' AND entity_id = ANY($1)"
);
sqlx::query(&query)
.bind(release_ids)
.execute(&mut **transaction)
.await?;
}
sqlx::query("DELETE FROM furumusic__release_artist WHERE release_id = ANY($1)")
.bind(release_ids)
.execute(&mut **transaction)
.await?;
sqlx::query("DELETE FROM furumusic__release WHERE id = ANY($1)")
.bind(release_ids)
.execute(&mut **transaction)
.await?;
}
let media_ids: Vec<i64> = media_files.iter().map(|media| media.id).collect();
if !media_ids.is_empty() {
let media_hashes: Vec<String> = media_files
.iter()
.map(|media| media.sha256_hash.clone())
.collect();
sqlx::query(
r#"UPDATE furumusic__youtube_download_item
SET status = 'failed', progress_percent = 0,
downloaded_bytes = 0, total_bytes = NULL,
speed_bytes_per_sec = NULL, eta_seconds = NULL,
error = 'Imported library files were deleted; this source can be imported again',
completed_at = NULL, updated_at = $2
WHERE id IN (
SELECT item_id
FROM furumusic__youtube_import_media
WHERE media_file_id = ANY($1)
)"#,
)
.bind(&media_ids)
.bind(chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string())
.execute(&mut **transaction)
.await?;
let review_ids: Vec<i64> = sqlx::query_scalar(
r#"SELECT id FROM furumusic__pending_review
WHERE context_json IS NOT NULL
AND substring(
context_json
from '"sha256"[[:space:]]*:[[:space:]]*"([0-9a-fA-F]{64})"'
) = ANY($1)"#,
)
.bind(&media_hashes)
.fetch_all(&mut **transaction)
.await?;
if !review_ids.is_empty() {
sqlx::query(
"DELETE FROM furumusic__processing_stats WHERE pending_review_id = ANY($1)",
)
.bind(&review_ids)
.execute(&mut **transaction)
.await?;
sqlx::query("DELETE FROM furumusic__pending_review WHERE id = ANY($1)")
.bind(&review_ids)
.execute(&mut **transaction)
.await?;
}
sqlx::query(
"DELETE FROM furumusic__federation_content_id_cache WHERE media_file_id = ANY($1)",
)
.bind(&media_ids)
.execute(&mut **transaction)
.await?;
sqlx::query("DELETE FROM furumusic__media_file WHERE id = ANY($1)")
.bind(&media_ids)
.execute(&mut **transaction)
.await?;
}
Ok(if delete_release_rows {
u64::try_from(release_ids.len()).unwrap_or(u64::MAX)
} else {
tracks_deleted
})
}
async fn cleanup_playback_states(
transaction: &mut Transaction<'_, Postgres>,
track_ids: &[i64],
) -> anyhow::Result<()> {
let deleted: HashSet<i64> = track_ids.iter().copied().collect();
let states: Vec<PlaybackStateRow> = sqlx::query_as(
"SELECT id, current_track_id, position_ms, queue_json, queue_position FROM furumusic__playback_state FOR UPDATE",
)
.fetch_all(&mut **transaction)
.await?;
for state in states {
let mut queue: Vec<i64> = serde_json::from_str(&state.queue_json).unwrap_or_default();
let original_queue = queue.clone();
queue.retain(|track_id| !deleted.contains(track_id));
let current_track_id = state.current_track_id.filter(|id| !deleted.contains(id));
if queue == original_queue && current_track_id == state.current_track_id {
continue;
}
let queue_position = current_track_id
.and_then(|current| queue.iter().position(|id| *id == current))
.map(|position| i32::try_from(position).unwrap_or(i32::MAX))
.unwrap_or_else(|| {
if queue.is_empty() {
0
} else {
state
.queue_position
.clamp(0, i32::try_from(queue.len() - 1).unwrap_or(i32::MAX))
}
});
let position_ms = if current_track_id.is_some() {
state.position_ms
} else {
0
};
let queue_json = serde_json::to_string(&queue)?;
sqlx::query(
r#"UPDATE furumusic__playback_state
SET current_track_id = $2, position_ms = $3,
queue_json = $4, queue_position = $5
WHERE id = $1"#,
)
.bind(state.id)
.bind(current_track_id)
.bind(position_ms)
.bind(queue_json)
.bind(queue_position)
.execute(&mut **transaction)
.await?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_media_paths_outside_storage() {
assert!(checked_storage_path("/srv/music", "/etc/passwd").is_err());
assert!(checked_storage_path("/srv/music", "../outside.flac").is_err());
assert_eq!(
checked_storage_path("/srv/music", "Artist/Album/01.flac").unwrap(),
PathBuf::from("/srv/music/Artist/Album/01.flac")
);
}
#[test]
fn deleted_track_ids_are_removed_from_saved_queue() {
let deleted = HashSet::from([2_i64, 4]);
let mut queue = vec![1_i64, 2, 3, 4, 5];
queue.retain(|track_id| !deleted.contains(track_id));
assert_eq!(queue, vec![1, 3, 5]);
let serialized: serde_json::Value =
serde_json::from_str(&serde_json::to_string(&queue).unwrap()).unwrap();
assert_eq!(serialized, serde_json::json!([1, 3, 5]));
}
}
+259
View File
@@ -0,0 +1,259 @@
use std::collections::HashMap;
use anyhow::{Context, bail};
use serde::Serialize;
use sqlx::{FromRow, PgPool};
const LOCAL_UPLOAD_LIST_LIMIT: i64 = 100;
#[derive(Debug, Clone, Serialize)]
pub struct LocalUploadDto {
pub id: String,
pub filename: String,
pub size_bytes: u64,
pub status: String,
pub error: Option<String>,
pub created_at: String,
pub updated_at: String,
pub completed_at: Option<String>,
}
#[derive(Debug, Clone, FromRow)]
struct LocalUploadRow {
id: String,
user_id: i64,
filename: String,
size_bytes: i64,
status: String,
inbox_path: String,
error: Option<String>,
created_at: String,
updated_at: String,
completed_at: Option<String>,
}
impl LocalUploadRow {
fn dto(&self) -> LocalUploadDto {
LocalUploadDto {
id: self.id.clone(),
filename: self.filename.clone(),
size_bytes: u64::try_from(self.size_bytes).unwrap_or(0),
status: self.status.clone(),
error: self.error.clone(),
created_at: self.created_at.clone(),
updated_at: self.updated_at.clone(),
completed_at: self.completed_at.clone(),
}
}
}
pub async fn create(
pool: &PgPool,
id: &str,
user_id: i64,
filename: &str,
size_bytes: u64,
inbox_path: &str,
) -> anyhow::Result<()> {
let now = now_string();
sqlx::query(
r#"INSERT INTO furumusic__local_upload
(id, user_id, filename, size_bytes, status, inbox_path, error,
created_at, updated_at, completed_at)
VALUES ($1, $2, $3, $4, 'uploading', $5, NULL, $6, $6, NULL)"#,
)
.bind(id)
.bind(user_id)
.bind(filename)
.bind(i64::try_from(size_bytes).unwrap_or(i64::MAX))
.bind(inbox_path)
.bind(now)
.execute(pool)
.await?;
Ok(())
}
pub async fn mark_queued(pool: &PgPool, id: &str, user_id: i64) -> anyhow::Result<LocalUploadDto> {
update_status(pool, id, user_id, "queued", None).await?;
load(pool, user_id, id).await.map(|row| row.dto())
}
pub async fn mark_failed(pool: &PgPool, id: &str, user_id: i64, error: &str) -> anyhow::Result<()> {
update_status(pool, id, user_id, "failed", Some(error)).await
}
pub async fn list(
pool: &PgPool,
user_id: i64,
inbox_dir: &str,
) -> anyhow::Result<Vec<LocalUploadDto>> {
sync_statuses(pool, user_id, inbox_dir).await?;
let rows: Vec<LocalUploadRow> = sqlx::query_as(
r#"SELECT id, user_id, filename, size_bytes, status, inbox_path, error,
created_at, updated_at, completed_at
FROM furumusic__local_upload
WHERE user_id = $1
ORDER BY created_at DESC, id DESC
LIMIT $2"#,
)
.bind(user_id)
.bind(LOCAL_UPLOAD_LIST_LIMIT)
.fetch_all(pool)
.await?;
Ok(rows.iter().map(LocalUploadRow::dto).collect())
}
pub async fn remove(pool: &PgPool, user_id: i64, id: &str) -> anyhow::Result<()> {
let result = sqlx::query("DELETE FROM furumusic__local_upload WHERE id = $1 AND user_id = $2")
.bind(id)
.bind(user_id)
.execute(pool)
.await?;
if result.rows_affected() == 0 {
bail!("file upload history entry not found");
}
Ok(())
}
async fn sync_statuses(pool: &PgPool, user_id: i64, inbox_dir: &str) -> anyhow::Result<()> {
let inbox_dir = inbox_dir.trim();
if inbox_dir.is_empty() {
bail!("agent_inbox_dir is not configured");
}
let inbox_root = crate::media_paths::resolve_config_path_buf(inbox_dir);
if !inbox_root.is_absolute() {
bail!("agent_inbox_dir must be an absolute path");
}
let rows: Vec<LocalUploadRow> = sqlx::query_as(
r#"SELECT id, user_id, filename, size_bytes, status, inbox_path, error,
created_at, updated_at, completed_at
FROM furumusic__local_upload
WHERE user_id = $1 AND status <> 'complete'"#,
)
.bind(user_id)
.fetch_all(pool)
.await?;
if rows.is_empty() {
return Ok(());
}
let inbox_paths: Vec<String> = rows.iter().map(|row| row.inbox_path.clone()).collect();
let state_rows: Vec<(String, String, i64)> = sqlx::query_as(
r#"SELECT input_path, status::text, COUNT(*)
FROM furumusic__pending_review
WHERE input_path = ANY($1)
GROUP BY input_path, status"#,
)
.bind(&inbox_paths)
.fetch_all(pool)
.await?;
let mut states_by_path: HashMap<String, HashMap<String, i64>> = HashMap::new();
for (input_path, status, total) in state_rows {
states_by_path
.entry(input_path)
.or_default()
.insert(status, total);
}
let error_rows: Vec<(String, String)> = sqlx::query_as(
r#"SELECT DISTINCT ON (input_path) input_path, error_message
FROM furumusic__pending_review
WHERE input_path = ANY($1) AND status = 'failed'
AND error_message IS NOT NULL
ORDER BY input_path, id DESC"#,
)
.bind(&inbox_paths)
.fetch_all(pool)
.await?;
let errors_by_path: HashMap<String, String> = error_rows.into_iter().collect();
for row in rows {
let counts = states_by_path
.get(&row.inbox_path)
.cloned()
.unwrap_or_default();
let total: i64 = counts.values().sum();
let mut terminal_error = None;
let next = if total == 0 {
if matches!(row.status.as_str(), "uploading" | "failed" | "needs_review") {
continue;
}
let full_path = crate::media_paths::resolve_path_from_root(inbox_dir, &row.inbox_path);
if tokio::fs::try_exists(full_path).await.unwrap_or(false) {
"queued"
} else {
"complete"
}
} else if count(&counts, "processing") > 0 {
"ai_processing"
} else if count(&counts, "queued") > 0 {
"queued"
} else if count(&counts, "failed") > 0 {
terminal_error = errors_by_path.get(&row.inbox_path).cloned();
"failed"
} else if count(&counts, "pending") > 0 || count(&counts, "rejected") > 0 {
"needs_review"
} else if count(&counts, "approved") > 0 || count(&counts, "auto_approved") > 0 {
"complete"
} else {
"queued"
};
if row.status != next || row.error != terminal_error {
update_status(pool, &row.id, row.user_id, next, terminal_error.as_deref()).await?;
}
}
Ok(())
}
async fn update_status(
pool: &PgPool,
id: &str,
user_id: i64,
status: &str,
error: Option<&str>,
) -> anyhow::Result<()> {
let now = now_string();
let completed_at =
matches!(status, "complete" | "failed" | "needs_review").then(|| now.clone());
sqlx::query(
r#"UPDATE furumusic__local_upload
SET status = $3, error = $4, updated_at = $5, completed_at = $6
WHERE id = $1 AND user_id = $2"#,
)
.bind(id)
.bind(user_id)
.bind(status)
.bind(error.map(trim_error))
.bind(&now)
.bind(completed_at)
.execute(pool)
.await?;
Ok(())
}
async fn load(pool: &PgPool, user_id: i64, id: &str) -> anyhow::Result<LocalUploadRow> {
sqlx::query_as(
r#"SELECT id, user_id, filename, size_bytes, status, inbox_path, error,
created_at, updated_at, completed_at
FROM furumusic__local_upload WHERE id = $1 AND user_id = $2"#,
)
.bind(id)
.bind(user_id)
.fetch_optional(pool)
.await?
.context("file upload history entry not found")
}
fn count(counts: &HashMap<String, i64>, status: &str) -> i64 {
counts.get(status).copied().unwrap_or(0)
}
fn trim_error(value: &str) -> String {
value.chars().take(4_000).collect()
}
fn now_string() -> String {
chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string()
}
+18 -1
View File
@@ -7,14 +7,18 @@ mod federation;
mod i18n; mod i18n;
mod jobs; mod jobs;
mod lastfm; mod lastfm;
mod library_cleanup;
mod local_uploads;
mod media_paths; mod media_paths;
mod metrics; mod metrics;
mod music; mod music;
mod oidc; mod oidc;
mod player; mod player;
mod scheduler; mod scheduler;
mod similarity;
mod torrents; mod torrents;
mod user; mod user;
mod youtube;
use std::sync::Arc; use std::sync::Arc;
@@ -87,7 +91,13 @@ async fn index(
return Ok(auth::redirect("/login")); return Ok(auth::redirect("/login"));
} }
}; };
let template = player::PlayerPageTemplate { t: i18n.t }; let (config, _) = AppConfig::load_with_db(&db).await;
let template = player::PlayerPageTemplate {
t: i18n.t,
downloads_enabled: config.downloads_enabled,
torrent_downloads_enabled: config.downloads_enabled && config.torrent_downloads_enabled,
youtube_downloads_enabled: config.downloads_enabled && config.youtube_downloads_enabled,
};
Html::new(template.render()?).into_response() Html::new(template.render()?).into_response()
} }
@@ -567,6 +577,13 @@ impl Project for FuruProject {
federation::handle().boot(&fed_config).await; federation::handle().boot(&fed_config).await;
}); });
// Embedding calculation is an independent, server-wide background
// service. It remains useful locally when federation is disabled.
let similarity_config = Arc::clone(&self.app_config);
tokio::spawn(async move {
similarity::handle().boot(&similarity_config).await;
});
apps.register(cot::session::db::SessionApp::new()); apps.register(cot::session::db::SessionApp::new());
apps.register_with_views( apps.register_with_views(
FuruApp { FuruApp {
+25 -1
View File
@@ -884,10 +884,18 @@ const KNOWN_HTTP_ROUTES: &[&str] = &[
"/api/player/lastfm/scrobble", "/api/player/lastfm/scrobble",
"/api/player/agent-queue", "/api/player/agent-queue",
"/api/player/offline/manifest", "/api/player/offline/manifest",
"/api/player/youtube",
"/api/player/youtube/preview",
"/api/player/youtube/start",
"/api/player/youtube/{id}/retry",
"/api/player/youtube/{id}/cancel",
"/api/player/youtube/{id}",
"/api/player/uploads/local",
"/api/player/uploads/local/history",
"/api/player/uploads/local/history/{id}",
"/api/player/torrents", "/api/player/torrents",
"/api/player/torrents/session/{id}", "/api/player/torrents/session/{id}",
"/api/player/torrents/preview", "/api/player/torrents/preview",
"/api/player/uploads/local",
"/api/player/uploads/tracks", "/api/player/uploads/tracks",
"/api/player/uploads/tracks/{track_id}", "/api/player/uploads/tracks/{track_id}",
"/api/player/uploads/bulk-tracks", "/api/player/uploads/bulk-tracks",
@@ -951,6 +959,22 @@ mod tests {
known_http_route("/share/release/42"), known_http_route("/share/release/42"),
Some("/share/release/{id}") Some("/share/release/{id}")
); );
assert_eq!(
known_http_route("/api/player/youtube/start"),
Some("/api/player/youtube/start")
);
assert_eq!(
known_http_route("/api/player/youtube/job-42/retry"),
Some("/api/player/youtube/{id}/retry")
);
assert_eq!(
known_http_route("/api/player/youtube/job-42/cancel"),
Some("/api/player/youtube/{id}/cancel")
);
assert_eq!(
known_http_route("/api/player/uploads/local/history/upload-42"),
Some("/api/player/uploads/local/history/{id}")
);
} }
#[test] #[test]
+311
View File
@@ -2476,6 +2476,312 @@ pub mod db_migrations {
&[Operation::custom(repair_legacy_listen_qualification).build()]; &[Operation::custom(repair_legacy_listen_qualification).build()];
} }
#[cot::db::migrations::migration_op]
async fn create_similarity_embeddings(
ctx: migrations::MigrationContext<'_>,
) -> cot::db::Result<()> {
ctx.db
.raw(
"CREATE TABLE IF NOT EXISTS furumusic__similarity_profile (
profile_id TEXT PRIMARY KEY,
model_id TEXT NOT NULL,
model_version TEXT NOT NULL,
model_sha256 TEXT NOT NULL,
preprocessing TEXT NOT NULL,
dimensions INTEGER NOT NULL,
active BOOLEAN NOT NULL DEFAULT FALSE,
created_at TEXT NOT NULL
)",
)
.await?;
ctx.db
.raw(
"CREATE UNIQUE INDEX IF NOT EXISTS idx_similarity_profile_active
ON furumusic__similarity_profile (active)
WHERE active = TRUE",
)
.await?;
ctx.db
.raw(
"CREATE TABLE IF NOT EXISTS furumusic__track_embedding (
track_id BIGINT NOT NULL REFERENCES furumusic__track(id)
ON DELETE CASCADE,
profile_id TEXT NOT NULL REFERENCES furumusic__similarity_profile(profile_id)
ON DELETE CASCADE,
dimensions INTEGER NOT NULL,
vector BYTEA NOT NULL,
source_sha256 TEXT NOT NULL,
source_content_id TEXT,
computed_at TEXT NOT NULL,
PRIMARY KEY (track_id, profile_id)
)",
)
.await?;
ctx.db
.raw(
"CREATE INDEX IF NOT EXISTS idx_track_embedding_profile
ON furumusic__track_embedding (profile_id, track_id)",
)
.await?;
Ok(())
}
#[derive(Debug, Copy, Clone)]
pub struct M0043CreateSimilarityEmbeddings;
impl migrations::Migration for M0043CreateSimilarityEmbeddings {
const APP_NAME: &'static str = "furumusic";
const MIGRATION_NAME: &'static str = "m_0043_create_similarity_embeddings";
const DEPENDENCIES: &'static [migrations::MigrationDependency] =
&[migrations::MigrationDependency::migration(
"furumusic",
"m_0042_repair_legacy_listen_qualification",
)];
const OPERATIONS: &'static [Operation] =
&[Operation::custom(create_similarity_embeddings).build()];
}
#[cot::db::migrations::migration_op]
async fn add_similarity_routing_signature(
ctx: migrations::MigrationContext<'_>,
) -> cot::db::Result<()> {
ctx.db
.raw(
"ALTER TABLE furumusic__track_embedding
ADD COLUMN IF NOT EXISTS routing_signature BYTEA",
)
.await?;
Ok(())
}
#[derive(Debug, Copy, Clone)]
pub struct M0044AddSimilarityRoutingSignature;
impl migrations::Migration for M0044AddSimilarityRoutingSignature {
const APP_NAME: &'static str = "furumusic";
const MIGRATION_NAME: &'static str = "m_0044_add_similarity_routing_signature";
const DEPENDENCIES: &'static [migrations::MigrationDependency] =
&[migrations::MigrationDependency::migration(
"furumusic",
"m_0043_create_similarity_embeddings",
)];
const OPERATIONS: &'static [Operation] =
&[Operation::custom(add_similarity_routing_signature).build()];
}
// -- M0045: persistent YouTube download jobs ----------------------------
#[cot::db::migrations::migration_op]
async fn create_youtube_downloads(
ctx: migrations::MigrationContext<'_>,
) -> cot::db::Result<()> {
ctx.db
.raw(
"CREATE TABLE IF NOT EXISTS furumusic__youtube_download (
id VARCHAR(36) PRIMARY KEY,
user_id BIGINT NOT NULL,
source_url TEXT NOT NULL,
title TEXT NOT NULL,
source_kind VARCHAR(32) NOT NULL,
status VARCHAR(32) NOT NULL,
total_items INTEGER NOT NULL DEFAULT 0,
completed_items INTEGER NOT NULL DEFAULT 0,
failed_items INTEGER NOT NULL DEFAULT 0,
review_items INTEGER NOT NULL DEFAULT 0,
error TEXT,
created_at VARCHAR(32) NOT NULL,
updated_at VARCHAR(32) NOT NULL,
completed_at VARCHAR(32)
)",
)
.await?;
ctx.db
.raw(
"CREATE TABLE IF NOT EXISTS furumusic__youtube_download_item (
id VARCHAR(36) PRIMARY KEY,
job_id VARCHAR(36) NOT NULL REFERENCES furumusic__youtube_download(id) ON DELETE CASCADE,
source_id VARCHAR(128) NOT NULL,
source_url TEXT NOT NULL,
title TEXT NOT NULL,
playlist_index INTEGER NOT NULL,
status VARCHAR(32) NOT NULL,
progress_percent DOUBLE PRECISION NOT NULL DEFAULT 0,
downloaded_bytes BIGINT NOT NULL DEFAULT 0,
total_bytes BIGINT,
speed_bytes_per_sec BIGINT,
eta_seconds BIGINT,
chapter_count INTEGER NOT NULL DEFAULT 0,
audio_file_count INTEGER NOT NULL DEFAULT 0,
inbox_path TEXT,
error TEXT,
created_at VARCHAR(32) NOT NULL,
updated_at VARCHAR(32) NOT NULL,
completed_at VARCHAR(32),
UNIQUE(job_id, source_id)
)",
)
.await?;
ctx.db
.raw(
"CREATE INDEX IF NOT EXISTS idx_youtube_download_user_updated
ON furumusic__youtube_download (user_id, updated_at DESC)",
)
.await?;
ctx.db
.raw(
"CREATE INDEX IF NOT EXISTS idx_youtube_download_user_status
ON furumusic__youtube_download (user_id, status)",
)
.await?;
ctx.db
.raw(
"CREATE INDEX IF NOT EXISTS idx_youtube_download_item_job_status
ON furumusic__youtube_download_item (job_id, status, playlist_index)",
)
.await?;
ctx.db
.raw(
"CREATE INDEX IF NOT EXISTS idx_youtube_download_item_source
ON furumusic__youtube_download_item (source_id)",
)
.await?;
Ok(())
}
#[derive(Debug, Copy, Clone)]
pub struct M0045CreateYouTubeDownloads;
impl migrations::Migration for M0045CreateYouTubeDownloads {
const APP_NAME: &'static str = "furumusic";
const MIGRATION_NAME: &'static str = "m_0045_create_youtube_downloads";
const DEPENDENCIES: &'static [migrations::MigrationDependency] =
&[migrations::MigrationDependency::migration(
"furumusic",
"m_0044_add_similarity_routing_signature",
)];
const OPERATIONS: &'static [Operation] =
&[Operation::custom(create_youtube_downloads).build()];
}
// -- M0046: persistent direct-file upload history -----------------------
#[cot::db::migrations::migration_op]
async fn create_local_upload_history(
ctx: migrations::MigrationContext<'_>,
) -> cot::db::Result<()> {
ctx.db
.raw(
"CREATE TABLE IF NOT EXISTS furumusic__local_upload (
id VARCHAR(36) PRIMARY KEY,
user_id BIGINT NOT NULL,
filename TEXT NOT NULL,
size_bytes BIGINT NOT NULL DEFAULT 0,
status VARCHAR(32) NOT NULL,
inbox_path TEXT NOT NULL,
error TEXT,
created_at VARCHAR(32) NOT NULL,
updated_at VARCHAR(32) NOT NULL,
completed_at VARCHAR(32)
)",
)
.await?;
ctx.db
.raw(
"CREATE INDEX IF NOT EXISTS idx_local_upload_user_updated
ON furumusic__local_upload (user_id, updated_at DESC)",
)
.await?;
ctx.db
.raw(
"CREATE INDEX IF NOT EXISTS idx_local_upload_user_status
ON furumusic__local_upload (user_id, status)",
)
.await?;
Ok(())
}
#[derive(Debug, Copy, Clone)]
pub struct M0046CreateLocalUploadHistory;
impl migrations::Migration for M0046CreateLocalUploadHistory {
const APP_NAME: &'static str = "furumusic";
const MIGRATION_NAME: &'static str = "m_0046_create_local_upload_history";
const DEPENDENCIES: &'static [migrations::MigrationDependency] =
&[migrations::MigrationDependency::migration(
"furumusic",
"m_0045_create_youtube_downloads",
)];
const OPERATIONS: &'static [Operation] =
&[Operation::custom(create_local_upload_history).build()];
}
// -- M0047: durable YouTube item -> imported media links ---------------
#[cot::db::migrations::migration_op]
async fn create_youtube_import_media_links(
ctx: migrations::MigrationContext<'_>,
) -> cot::db::Result<()> {
ctx.db
.raw(
"CREATE TABLE IF NOT EXISTS furumusic__youtube_import_media (
item_id VARCHAR(36) NOT NULL
REFERENCES furumusic__youtube_download_item(id) ON DELETE CASCADE,
media_file_id BIGINT NOT NULL
REFERENCES furumusic__media_file(id) ON DELETE CASCADE,
PRIMARY KEY (item_id, media_file_id)
)",
)
.await?;
ctx.db
.raw(
"CREATE INDEX IF NOT EXISTS idx_youtube_import_media_file
ON furumusic__youtube_import_media (media_file_id)",
)
.await?;
// Backfill links for existing imports through the inbox review hash.
ctx.db
.raw(
"INSERT INTO furumusic__youtube_import_media (item_id, media_file_id)
SELECT DISTINCT item.id, media.id
FROM furumusic__youtube_download_item item
JOIN furumusic__pending_review review
ON item.inbox_path IS NOT NULL
AND (review.input_path = item.inbox_path
OR left(review.input_path, length(item.inbox_path) + 1)
= item.inbox_path || '/')
JOIN furumusic__media_file media
ON media.sha256_hash::text = substring(
review.context_json
from '\"sha256\"[[:space:]]*:[[:space:]]*\"([0-9a-fA-F]{64})\"'
)
JOIN furumusic__track track ON track.audio_file_id = media.id
WHERE review.context_json IS NOT NULL
ON CONFLICT (item_id, media_file_id) DO NOTHING",
)
.await?;
Ok(())
}
#[derive(Debug, Copy, Clone)]
pub struct M0047CreateYouTubeImportMediaLinks;
impl migrations::Migration for M0047CreateYouTubeImportMediaLinks {
const APP_NAME: &'static str = "furumusic";
const MIGRATION_NAME: &'static str = "m_0047_create_youtube_import_media_links";
const DEPENDENCIES: &'static [migrations::MigrationDependency] = &[
migrations::MigrationDependency::migration(
"furumusic",
"m_0046_create_local_upload_history",
),
migrations::MigrationDependency::migration(
"furumusic",
"m_0027_create_processing_stats",
),
];
const OPERATIONS: &'static [Operation] =
&[Operation::custom(create_youtube_import_media_links).build()];
}
pub const MIGRATIONS: &[&SyncDynMigration] = &[ pub const MIGRATIONS: &[&SyncDynMigration] = &[
&M0006CreateMediaFile, &M0006CreateMediaFile,
&M0007CreateArtist, &M0007CreateArtist,
@@ -2509,5 +2815,10 @@ pub mod db_migrations {
&M0040CreateContentAddressedMusicRefs, &M0040CreateContentAddressedMusicRefs,
&M0041CreateSyncedListenHistory, &M0041CreateSyncedListenHistory,
&M0042RepairLegacyListenQualification, &M0042RepairLegacyListenQualification,
&M0043CreateSimilarityEmbeddings,
&M0044AddSimilarityRoutingSignature,
&M0045CreateYouTubeDownloads,
&M0046CreateLocalUploadHistory,
&M0047CreateYouTubeImportMediaLinks,
]; ];
} }
+995 -29
View File
File diff suppressed because it is too large Load Diff
+1569
View File
File diff suppressed because it is too large Load Diff
+70 -39
View File
@@ -373,7 +373,8 @@ impl TorrentJob {
pub struct TorrentService { pub struct TorrentService {
temp_root: PathBuf, temp_root: PathBuf,
session: OnceCell<Arc<Session>>, sessions: Mutex<HashMap<String, Arc<Session>>>,
job_sessions: Mutex<HashMap<String, Arc<Session>>>,
jobs: Mutex<HashMap<String, TorrentJob>>, jobs: Mutex<HashMap<String, TorrentJob>>,
resolving_jobs: Mutex<HashSet<String>>, resolving_jobs: Mutex<HashSet<String>>,
scheduler_handle: Arc<OnceCell<Arc<SchedulerHandle>>>, scheduler_handle: Arc<OnceCell<Arc<SchedulerHandle>>>,
@@ -383,36 +384,47 @@ impl TorrentService {
pub fn new(scheduler_handle: Arc<OnceCell<Arc<SchedulerHandle>>>) -> Self { pub fn new(scheduler_handle: Arc<OnceCell<Arc<SchedulerHandle>>>) -> Self {
Self { Self {
temp_root: std::env::temp_dir().join("furumusic").join("torrents"), temp_root: std::env::temp_dir().join("furumusic").join("torrents"),
session: OnceCell::new(), sessions: Mutex::new(HashMap::new()),
job_sessions: Mutex::new(HashMap::new()),
jobs: Mutex::new(HashMap::new()), jobs: Mutex::new(HashMap::new()),
resolving_jobs: Mutex::new(HashSet::new()), resolving_jobs: Mutex::new(HashSet::new()),
scheduler_handle, scheduler_handle,
} }
} }
async fn session(&self) -> anyhow::Result<Arc<Session>> { async fn session(&self, proxy_url: Option<&str>) -> anyhow::Result<Arc<Session>> {
let temp_root = self.temp_root.clone(); let key = proxy_url.unwrap_or_default().to_string();
self.session let mut sessions = self.sessions.lock().await;
.get_or_try_init(|| async move { if let Some(session) = sessions.get(&key) {
tokio::fs::create_dir_all(&temp_root).await?; return Ok(Arc::clone(session));
Session::new_with_opts( }
temp_root,
SessionOptions { tokio::fs::create_dir_all(&self.temp_root).await?;
disable_upload: true, let session = Session::new_with_opts(
enable_upnp_port_forwarding: false, self.temp_root.clone(),
..Default::default() SessionOptions {
}, // SOCKS is intentionally limited to peer TCP and HTTP(S)
) // tracker traffic. DHT and other UDP discovery stay direct.
.await disable_dht: false,
}) // Sessions are keyed by proxy and can coexist, so they cannot
.await // safely share one persisted DHT socket configuration.
.cloned() disable_dht_persistence: true,
disable_upload: true,
enable_upnp_port_forwarding: false,
socks_proxy_url: proxy_url.map(str::to_owned),
..Default::default()
},
)
.await?;
sessions.insert(key, Arc::clone(&session));
Ok(session)
} }
pub async fn list( pub async fn list(
self: &Arc<Self>, self: &Arc<Self>,
pool: &PgPool, pool: &PgPool,
user_id: i64, user_id: i64,
proxy_url: Option<String>,
) -> anyhow::Result<Vec<TorrentJobDto>> { ) -> anyhow::Result<Vec<TorrentJobDto>> {
let rows = sqlx::query_as::<_, TorrentSessionRow>( let rows = sqlx::query_as::<_, TorrentSessionRow>(
r#"SELECT id, user_id, name, info_hash, source_kind, source_label, torrent_bytes, r#"SELECT id, user_id, name, info_hash, source_kind, source_label, torrent_bytes,
@@ -445,6 +457,7 @@ impl TorrentService {
row.id.clone(), row.id.clone(),
magnet, magnet,
row.created_at.clone(), row.created_at.clone(),
proxy_url.clone(),
) )
.await; .await;
} }
@@ -483,8 +496,9 @@ impl TorrentService {
pool: &PgPool, pool: &PgPool,
user_id: i64, user_id: i64,
request: TorrentPreviewRequest, request: TorrentPreviewRequest,
proxy_url: Option<&str>,
) -> anyhow::Result<TorrentSessionDto> { ) -> anyhow::Result<TorrentSessionDto> {
let session = self.session().await?; let session = self.session(proxy_url).await?;
let id = Uuid::new_v4().to_string(); let id = Uuid::new_v4().to_string();
let output_dir = self.temp_root.join(&id).join("download"); let output_dir = self.temp_root.join(&id).join("download");
tokio::fs::create_dir_all(&output_dir).await?; tokio::fs::create_dir_all(&output_dir).await?;
@@ -511,8 +525,15 @@ impl TorrentService {
.unwrap_or_else(|| info_hash.clone()); .unwrap_or_else(|| info_hash.clone());
let now = now_string(); let now = now_string();
insert_pending_magnet(pool, &id, user_id, &name, &info_hash, &magnet, &now).await?; insert_pending_magnet(pool, &id, user_id, &name, &info_hash, &magnet, &now).await?;
self.spawn_resolve_pending_magnet(pool.clone(), user_id, id.clone(), magnet, now) self.spawn_resolve_pending_magnet(
.await; pool.clone(),
user_id,
id.clone(),
magnet,
now,
proxy_url.map(str::to_owned),
)
.await;
let row = load_row(pool, user_id, &id).await?; let row = load_row(pool, user_id, &id).await?;
return Ok(TorrentSessionDto { return Ok(TorrentSessionDto {
@@ -611,6 +632,7 @@ impl TorrentService {
id: String, id: String,
magnet: String, magnet: String,
created_at: String, created_at: String,
proxy_url: Option<String>,
) { ) {
{ {
let mut resolving = self.resolving_jobs.lock().await; let mut resolving = self.resolving_jobs.lock().await;
@@ -622,7 +644,14 @@ impl TorrentService {
let service = Arc::clone(self); let service = Arc::clone(self);
tokio::spawn(async move { tokio::spawn(async move {
let result = service let result = service
.resolve_pending_magnet(&pool, user_id, &id, &magnet, &created_at) .resolve_pending_magnet(
&pool,
user_id,
&id,
&magnet,
&created_at,
proxy_url.as_deref(),
)
.await; .await;
if let Err(err) = result { if let Err(err) = result {
update_resolving_error(&pool, &id, &err.to_string()).await; update_resolving_error(&pool, &id, &err.to_string()).await;
@@ -638,8 +667,9 @@ impl TorrentService {
id: &str, id: &str,
magnet: &str, magnet: &str,
created_at: &str, created_at: &str,
proxy_url: Option<&str>,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
let session = self.session().await?; let session = self.session(proxy_url).await?;
let output_dir = self.temp_root.join(id).join("download"); let output_dir = self.temp_root.join(id).join("download");
tokio::fs::create_dir_all(&output_dir).await?; tokio::fs::create_dir_all(&output_dir).await?;
let response = tokio::time::timeout( let response = tokio::time::timeout(
@@ -743,7 +773,7 @@ impl TorrentService {
jobs.remove(id).and_then(|job| job.handle) jobs.remove(id).and_then(|job| job.handle)
}; };
if let Some(handle) = removed { if let Some(handle) = removed {
self.stop_torrent(&handle).await; self.stop_torrent(id, &handle).await;
} }
let result = let result =
@@ -766,6 +796,7 @@ impl TorrentService {
selected_files: Vec<usize>, selected_files: Vec<usize>,
inbox_dir: String, inbox_dir: String,
uploader_user_id: i64, uploader_user_id: i64,
proxy_url: Option<&str>,
) -> anyhow::Result<TorrentJobDto> { ) -> anyhow::Result<TorrentJobDto> {
if selected_files.is_empty() { if selected_files.is_empty() {
bail!("select at least one file"); bail!("select at least one file");
@@ -810,7 +841,7 @@ impl TorrentService {
tokio::fs::create_dir_all(&output_dir).await?; tokio::fs::create_dir_all(&output_dir).await?;
mark_job_started(pool, id, &selected_files, &self.memory_job_dto(id).await?).await?; mark_job_started(pool, id, &selected_files, &self.memory_job_dto(id).await?).await?;
let session = self.session().await?; let session = self.session(proxy_url).await?;
let response = match session let response = match session
.add_torrent( .add_torrent(
AddTorrent::from_bytes(torrent_bytes), AddTorrent::from_bytes(torrent_bytes),
@@ -838,6 +869,10 @@ impl TorrentService {
return Err(err); return Err(err);
} }
}; };
self.job_sessions
.lock()
.await
.insert(id.to_string(), Arc::clone(&session));
let dto = { let dto = {
let mut jobs = self.jobs.lock().await; let mut jobs = self.jobs.lock().await;
@@ -856,7 +891,7 @@ impl TorrentService {
if service.is_paused(&id).await { if service.is_paused(&id).await {
return; return;
} }
service.stop_torrent(&handle).await; service.stop_torrent(&id, &handle).await;
service.fail_job(&pool, &id, err.to_string()).await; service.fail_job(&pool, &id, err.to_string()).await;
crate::metrics::record_torrent_download( crate::metrics::record_torrent_download(
"failed", "failed",
@@ -865,7 +900,7 @@ impl TorrentService {
); );
return; return;
} }
service.stop_torrent(&handle).await; service.stop_torrent(&id, &handle).await;
if let Err(err) = service if let Err(err) = service
.finalize_completed(&pool, &id, &inbox_dir, uploader_user_id) .finalize_completed(&pool, &id, &inbox_dir, uploader_user_id)
.await .await
@@ -911,7 +946,7 @@ impl TorrentService {
persist_progress(pool, &dto).await?; persist_progress(pool, &dto).await?;
if let Some(handle) = handle { if let Some(handle) = handle {
self.stop_torrent(&handle).await; self.stop_torrent(id, &handle).await;
} }
Ok(dto) Ok(dto)
} }
@@ -981,16 +1016,12 @@ impl TorrentService {
} }
} }
async fn stop_torrent(&self, handle: &Arc<ManagedTorrent>) { async fn stop_torrent(&self, id: &str, handle: &Arc<ManagedTorrent>) {
match self.session().await { let session = self.job_sessions.lock().await.remove(id);
Ok(session) => { if let Some(session) = session
if let Err(err) = session.delete(handle.id().into(), false).await { && let Err(err) = session.delete(handle.id().into(), false).await
tracing::warn!("failed to stop completed torrent: {err}"); {
} tracing::warn!("failed to stop completed torrent: {err}");
}
Err(err) => {
tracing::warn!("failed to access torrent session for shutdown: {err}");
}
} }
} }
+2090
View File
File diff suppressed because it is too large Load Diff
+679 -72
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -3,6 +3,7 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='14' fill='%23111827'/%3E%3Cpath d='M27 15v31.5a9 9 0 1 1-5-8.1V22l27-6v24.5a9 9 0 1 1-5-8.1V15.9L27 20.5' fill='%2367e8f9'/%3E%3C/svg%3E">
<title>{% block title %}{{ t.site_name }}{% endblock title %}</title> <title>{% block title %}{{ t.site_name }}{% endblock title %}</title>
{% block head_extra %}{% endblock head_extra %} {% block head_extra %}{% endblock head_extra %}
</head> </head>
+289 -29
View File
@@ -85,7 +85,7 @@
</div> </div>
</template> </template>
<!-- Torrent Import Modal --> <!-- Download Manager Modal -->
<template x-if="$store.torrents.modal"> <template x-if="$store.torrents.modal">
<div class="modal-overlay" @click.self="$store.torrents.close()"> <div class="modal-overlay" @click.self="$store.torrents.close()">
<div class="modal-box torrent-modal"> <div class="modal-box torrent-modal">
@@ -107,25 +107,47 @@
</button> </button>
<div class="torrent-client-status"> <div class="torrent-client-status">
<span class="torrent-status-pill" <span class="torrent-status-pill"
x-show="$store.torrents.sourceTab === 'torrents'"
:class="{ active: $store.torrents.activeCount() > 0 }" :class="{ active: $store.torrents.activeCount() > 0 }"
x-text="$store.torrents.clientSummary()"></span> x-text="$store.torrents.clientSummary()"></span>
<span class="torrent-status-pill"
x-show="$store.torrents.sourceTab === 'youtube'"
:class="{ active: $store.torrents.youtubeActiveCount() > 0 }"
x-text="$store.torrents.youtubeSummary()"></span>
<span class="torrent-status-pill torrent-agent-pill" <span class="torrent-status-pill torrent-agent-pill"
:class="{ active: $store.torrents.agentBusy() }"> :class="{ active: $store.torrents.agentBusy() }">
<span class="torrent-agent-dot"></span> <span class="torrent-agent-dot"></span>
<span x-text="$store.torrents.agentSummary()"></span> <span x-text="$store.torrents.agentSummary()"></span>
</span> </span>
<span class="torrent-status-pill" <span class="torrent-status-pill"
x-show="$store.torrents.sourceTab === 'torrents'"
x-text="$store.torrents.sessions.length + ' ' + T.saved"></span> x-text="$store.torrents.sessions.length + ' ' + T.saved"></span>
<span class="torrent-status-pill"
x-show="$store.torrents.sourceTab === 'youtube'"
x-text="$store.torrents.youtubeJobs.length + ' ' + T.saved"></span>
<span class="torrent-status-pill"
x-show="$store.torrents.sourceTab === 'files'"
x-text="$store.torrents.localUploadHistory.length + ' ' + T.saved"></span>
</div> </div>
</div> </div>
<div class="torrent-tabs"> <div class="torrent-tabs download-source-tabs">
{% if youtube_downloads_enabled %}
<button class="torrent-tab-btn" <button class="torrent-tab-btn"
:class="{ active: $store.torrents.activeTab === 'import' }" :class="{ active: $store.torrents.sourceTab === 'youtube' }"
@click="$store.torrents.showImportTab()">{{ t.player_import }}</button> @click="$store.torrents.showSourceTab('youtube')">{{ t.player_youtube }}</button>
{% endif %}
{% if torrent_downloads_enabled %}
<button class="torrent-tab-btn" <button class="torrent-tab-btn"
:class="{ active: $store.torrents.activeTab === 'uploads' }" :class="{ active: $store.torrents.sourceTab === 'torrents' }"
@click="$store.torrents.showUploadsTab()"> @click="$store.torrents.showSourceTab('torrents')">{{ t.player_torrents }}</button>
{% endif %}
<button class="torrent-tab-btn"
:class="{ active: $store.torrents.sourceTab === 'files' }"
@click="$store.torrents.showSourceTab('files')">{{ t.player_files }}</button>
<button class="torrent-tab-btn"
:class="{ active: $store.torrents.sourceTab === 'uploads' }"
@click="$store.torrents.showSourceTab('uploads')">
<span>{{ t.player_my_uploads }}</span> <span>{{ t.player_my_uploads }}</span>
<span class="torrent-tab-count" <span class="torrent-tab-count"
x-show="$store.torrents.uploadPendingTotal + $store.torrents.uploadQueuedTotal > 0" x-show="$store.torrents.uploadPendingTotal + $store.torrents.uploadQueuedTotal > 0"
@@ -133,7 +155,173 @@
</button> </button>
</div> </div>
<template x-if="$store.torrents.activeTab === 'import'"> <div class="youtube-manager-panel" x-show="$store.torrents.sourceTab === 'youtube'">
<form class="youtube-download-form" @submit.prevent="$store.torrents.previewYoutubeUrl()">
<label for="youtube-download-url">{{ t.player_youtube_url }}</label>
<div class="youtube-download-form-row">
<input id="youtube-download-url"
type="text"
inputmode="url"
autocomplete="url"
x-model="$store.torrents.youtubeUrl"
@input="$store.torrents.clearYoutubePreview()"
placeholder="https://www.youtube.com/watch?v=...">
<button type="submit"
class="modal-btn modal-btn-primary"
:disabled="$store.torrents.youtubePreviewLoading || $store.torrents.youtubeSubmitting || !$store.torrents.youtubeUrl.trim()">
<span x-text="$store.torrents.youtubePreviewLoading ? T.youtubeParsing : T.youtubeParse"></span>
</button>
</div>
<p class="youtube-download-hint">{{ t.player_youtube_url_hint }}</p>
</form>
<template x-if="$store.torrents.youtubePreview">
<section class="youtube-preview-card">
<div class="youtube-preview-head">
<div>
<h4>{{ t.player_youtube_preview_title }}</h4>
<p>
<strong x-text="$store.torrents.youtubePreview.title"></strong>
<span> · </span>
<span x-text="$store.torrents.youtubePreview.items.length + ' ' + T.youtubeItems"></span>
</p>
</div>
<div class="youtube-preview-controls">
<button type="button" class="modal-btn modal-btn-ghost"
@click="$store.torrents.selectAllYoutubePreview()">{{ t.player_youtube_select_all }}</button>
<button type="button" class="modal-btn modal-btn-ghost"
@click="$store.torrents.clearYoutubePreviewSelection()">{{ t.player_youtube_clear_selection }}</button>
</div>
</div>
<div class="youtube-preview-list">
<template x-for="item in $store.torrents.youtubePreview.items" :key="item.source_id">
<label class="youtube-preview-row"
:class="{ selected: $store.torrents.youtubePreviewIsSelected(item.source_id) }">
<input type="checkbox"
:checked="$store.torrents.youtubePreviewIsSelected(item.source_id)"
@change="$store.torrents.toggleYoutubePreviewItem(item.source_id)">
<span class="youtube-item-index" x-text="String(item.playlist_index).padStart(2, '0')"></span>
<span class="youtube-preview-item-title" x-text="item.title"></span>
</label>
</template>
</div>
<div class="youtube-preview-footer">
<span x-text="$store.torrents.youtubePreviewSelectedCount() + ' ' + T.youtubeSelectedCount"></span>
<div>
<button type="button" class="modal-btn modal-btn-ghost"
@click="$store.torrents.clearYoutubePreview()">{{ t.player_cancel }}</button>
<button type="button" class="modal-btn modal-btn-primary"
@click="$store.torrents.startYoutubeDownload()"
:disabled="$store.torrents.youtubeSubmitting || $store.torrents.youtubePreviewSelectedCount() === 0">
{{ t.player_youtube_start_import }}
</button>
</div>
</div>
</section>
</template>
<div class="youtube-download-list-head">
<span>{{ t.player_youtube_downloads }}</span>
<button class="modal-btn modal-btn-ghost"
@click="$store.torrents.loadYoutubeJobs()"
:disabled="$store.torrents.youtubeLoading">{{ t.player_refresh }}</button>
</div>
<div class="youtube-download-list">
<template x-if="!$store.torrents.youtubeLoading && $store.torrents.youtubeJobs.length === 0">
<div class="empty-state youtube-empty-state">
<p>{{ t.player_no_youtube_downloads }}</p>
</div>
</template>
<template x-for="job in $store.torrents.youtubeJobs" :key="job.id">
<article class="youtube-job-card">
<div class="youtube-job-head">
<div class="youtube-job-heading">
<div class="youtube-job-title" x-text="job.title"></div>
<div class="youtube-job-meta" x-text="$store.torrents.youtubeJobMeta(job)"></div>
</div>
<span class="torrent-status-badge"
:class="$store.torrents.youtubeStatusClass(job.status)"
x-text="$store.torrents.youtubeStatusLabel(job.status)"></span>
</div>
<div class="youtube-job-progress">
<div class="torrent-session-progress">
<div class="torrent-session-progress-bar"
:style="'width:' + $store.torrents.youtubeJobProgress(job) + '%'">
</div>
</div>
<span x-text="$store.torrents.youtubeJobProgressText(job)"></span>
</div>
<p class="youtube-job-error" x-show="job.error" x-text="job.error"></p>
<div class="youtube-item-list">
<template x-for="item in job.items" :key="item.id">
<div class="youtube-item-row" :class="{ failed: $store.torrents.youtubeIsError(item.status) }">
<div class="youtube-item-head">
<span class="youtube-item-index" x-text="String(item.playlist_index).padStart(2, '0')"></span>
<div class="youtube-item-main">
<div class="youtube-item-title" x-text="item.title"></div>
<div class="youtube-item-meta" x-text="$store.torrents.youtubeItemMeta(item)"></div>
</div>
<span class="torrent-status-badge"
:class="$store.torrents.youtubeStatusClass(item.status)"
x-text="$store.torrents.youtubeStatusLabel(item.status)"></span>
</div>
<div class="youtube-item-download-progress" x-show="item.status === 'downloading'">
<div class="torrent-session-progress">
<div class="torrent-session-progress-bar"
:style="'width:' + Number(item.progress_percent || 0) + '%'">
</div>
</div>
<span x-text="$store.torrents.youtubeDownloadMeta(item)"></span>
</div>
<div class="youtube-step-list" aria-label="{{ t.player_download_steps }}">
<span class="youtube-step" :class="$store.torrents.youtubeStepClass(item, 1)">
<i></i><b>{{ t.player_downloading }}</b>
</span>
<span class="youtube-step" :class="$store.torrents.youtubeStepClass(item, 2)">
<i></i><b>FFmpeg</b>
</span>
<span class="youtube-step" :class="$store.torrents.youtubeStepClass(item, 3)">
<i></i><b>{{ t.player_ai_prefix }}</b>
</span>
<span class="youtube-step" :class="$store.torrents.youtubeStepClass(item, 4)">
<i></i><b x-text="$store.torrents.youtubeFinalStepLabel(item)"></b>
</span>
</div>
<p class="youtube-item-error"
x-show="item.error"
x-text="item.error"></p>
</div>
</template>
</div>
<div class="youtube-job-actions">
<button class="modal-btn modal-btn-ghost"
x-show="job.review_items > 0 || job.items.some(item => item.status === 'ai_failed')"
@click="$store.torrents.openYoutubeReviews()">{{ t.player_my_uploads }}</button>
<button class="modal-btn modal-btn-pause"
x-show="$store.torrents.youtubeJobCancellable(job.status)"
:disabled="$store.torrents.youtubeCancellingIds.has(job.id)"
@click="$store.torrents.cancelYoutubeJob(job.id)">{{ t.player_youtube_stop }}</button>
<button class="modal-btn modal-btn-pause"
x-show="job.status !== 'cancelled' && (job.items.some(item => item.status === 'failed') || (job.status === 'failed' && job.total_items === 0))"
@click="$store.torrents.retryYoutubeJob(job.id)">{{ t.player_retry_failed }}</button>
<button class="modal-btn modal-btn-danger"
x-show="$store.torrents.youtubeJobTerminal(job.status)"
@click="$store.torrents.removeYoutubeJob(job.id)">{{ t.player_remove_from_history }}</button>
</div>
</article>
</template>
</div>
</div>
<div class="download-torrent-panel" x-show="$store.torrents.sourceTab === 'torrents'">
<div class="torrent-manager-layout"> <div class="torrent-manager-layout">
<aside class="torrent-manager-sidebar"> <aside class="torrent-manager-sidebar">
<div class="torrent-manager-title"> <div class="torrent-manager-title">
@@ -173,7 +361,7 @@
@click="$store.torrents.addNew()" @click="$store.torrents.addNew()"
:disabled="$store.torrents.loading"> :disabled="$store.torrents.loading">
<span class="torrent-session-add-icon">+</span> <span class="torrent-session-add-icon">+</span>
<span>{{ t.player_upload }}</span> <span>{{ t.player_add_torrent }}</span>
</button> </button>
</div> </div>
</aside> </aside>
@@ -188,12 +376,6 @@
<template x-if="$store.torrents.isImporting()"> <template x-if="$store.torrents.isImporting()">
<div class="torrent-import-panel"> <div class="torrent-import-panel">
<div class="torrent-modal-grid"> <div class="torrent-modal-grid">
<div>
<label for="local-file-input">{{ t.player_local_files }}</label>
<input id="local-file-input" type="file" multiple accept="audio/*,.mp3,.flac,.wav,.m4a,.ogg,.opus,.aac"
@change="$store.torrents.setLocalFiles($event.target.files)">
<div class="torrent-upload-summary" x-text="$store.torrents.localUploadSummary()"></div>
</div>
<div> <div>
<label for="torrent-magnet-input">{{ t.player_magnet_link }}</label> <label for="torrent-magnet-input">{{ t.player_magnet_link }}</label>
<input id="torrent-magnet-input" type="text" <input id="torrent-magnet-input" type="text"
@@ -206,17 +388,6 @@
@change="$store.torrents.file = $event.target.files[0] || null"> @change="$store.torrents.file = $event.target.files[0] || null">
</div> </div>
</div> </div>
<div class="torrent-upload-progress"
x-show="$store.torrents.uploadProgress > 0 || ($store.torrents.localFiles.length > 0 && $store.torrents.loading)">
<div class="torrent-progress-head">
<span x-text="$store.torrents.uploadProgress >= 100 ? T.uploadComplete : T.uploadingFiles"></span>
<span x-text="$store.torrents.uploadProgressText"></span>
</div>
<div class="torrent-progress-track">
<div class="torrent-progress-bar"
:style="'width:' + $store.torrents.uploadProgress + '%'"></div>
</div>
</div>
<div class="torrent-actions"> <div class="torrent-actions">
<button class="modal-btn modal-btn-primary" @click="$store.torrents.preview()" :disabled="$store.torrents.loading"> <button class="modal-btn modal-btn-primary" @click="$store.torrents.preview()" :disabled="$store.torrents.loading">
{{ t.player_upload_content }} {{ t.player_upload_content }}
@@ -282,7 +453,7 @@
<button class="modal-btn modal-btn-danger" <button class="modal-btn modal-btn-danger"
@click="$store.torrents.removeSession($store.torrents.previewData.id)" @click="$store.torrents.removeSession($store.torrents.previewData.id)"
:disabled="$store.torrents.loading"> :disabled="$store.torrents.loading">
{{ t.player_delete }} {{ t.player_remove_from_history }}
</button> </button>
</div> </div>
</div> </div>
@@ -341,9 +512,87 @@
</template> </template>
</section> </section>
</div> </div>
</template> </div>
<template x-if="$store.torrents.activeTab === 'uploads'"> <section class="file-upload-panel" x-show="$store.torrents.sourceTab === 'files'">
<input id="direct-audio-file-input"
class="file-upload-input"
type="file"
multiple
accept="audio/*,.mp3,.flac,.wav,.m4a,.ogg,.opus,.aac"
@change="$store.torrents.setLocalFiles($event.target.files); $event.target.value = ''">
<label class="file-drop-zone"
for="direct-audio-file-input"
:class="{ dragging: $store.torrents.localFilesDragging }"
@dragenter.prevent="$store.torrents.localFilesDragging = true"
@dragover.prevent="$store.torrents.localFilesDragging = true"
@dragleave.prevent="$store.torrents.leaveLocalFileDrop($event)"
@drop.prevent="$store.torrents.dropLocalFiles($event)">
<span class="file-drop-icon" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
<path d="M12 16V4"/><polyline points="7 9 12 4 17 9"/>
<path d="M5 14v4a2 2 0 002 2h10a2 2 0 002-2v-4"/>
</svg>
</span>
<strong>{{ t.player_drop_audio_title }}</strong>
<span>{{ t.player_drop_audio_hint }}</span>
<small>{{ t.player_drop_audio_formats }}</small>
</label>
<div class="file-upload-selection" x-show="$store.torrents.localFiles.length > 0">
<span x-text="$store.torrents.localUploadSummary()"></span>
<div>
<button type="button" class="modal-btn modal-btn-ghost"
@click="$store.torrents.clearLocalFiles()"
:disabled="$store.torrents.localFilesUploading">{{ t.player_cancel }}</button>
<button type="button" class="modal-btn modal-btn-primary"
@click="$store.torrents.uploadLocalFiles()"
:disabled="$store.torrents.localFilesUploading">{{ t.player_upload_selected_files }}</button>
</div>
</div>
<div class="torrent-upload-progress"
x-show="$store.torrents.localFilesUploading || $store.torrents.uploadProgress > 0">
<div class="torrent-progress-head">
<span x-text="$store.torrents.uploadProgress >= 100 ? T.uploadComplete : T.uploadingFiles"></span>
<span x-text="$store.torrents.uploadProgressText"></span>
</div>
<div class="torrent-progress-track">
<div class="torrent-progress-bar"
:style="'width:' + $store.torrents.uploadProgress + '%'"></div>
</div>
</div>
<div class="youtube-download-list-head file-upload-history-head">
<span>{{ t.player_upload_history }}</span>
<button class="modal-btn modal-btn-ghost"
@click="$store.torrents.loadLocalUploadHistory()"
:disabled="$store.torrents.localUploadHistoryLoading">{{ t.player_refresh }}</button>
</div>
<div class="file-upload-history">
<template x-if="!$store.torrents.localUploadHistoryLoading && $store.torrents.localUploadHistory.length === 0">
<div class="empty-state youtube-empty-state"><p>{{ t.player_no_file_uploads }}</p></div>
</template>
<template x-for="item in $store.torrents.localUploadHistory" :key="item.id">
<article class="file-upload-history-row">
<div class="file-upload-history-main">
<div class="file-upload-history-title" x-text="item.filename"></div>
<div class="file-upload-history-meta"
x-text="$store.torrents.bytes(item.size_bytes) + ' · ' + $store.torrents.formatUploadDate(item.created_at)"></div>
<p class="youtube-item-error" x-show="item.error" x-text="item.error"></p>
</div>
<span class="torrent-status-badge"
:class="$store.torrents.youtubeStatusClass(item.status)"
x-text="$store.torrents.youtubeStatusLabel(item.status)"></span>
<button class="modal-btn modal-btn-danger"
@click="$store.torrents.removeLocalUploadHistory(item.id)">{{ t.player_remove_from_history }}</button>
</article>
</template>
</div>
</section>
<template x-if="$store.torrents.sourceTab === 'uploads'">
<section class="upload-manager-panel"> <section class="upload-manager-panel">
<div class="upload-manager-head"> <div class="upload-manager-head">
<div> <div>
@@ -653,6 +902,17 @@
</button> </button>
</div> </div>
<section class="user-settings-section">
<div class="user-settings-section-head">
<div>
<h4>{{ t.player_interface_language }}</h4>
<p>{{ t.player_language_description }}</p>
</div>
<button class="settings-secondary-btn"
onclick="location.href='/set-lang?lang={% if t.lang.code() == "en" %}ru{% else %}en{% endif %}&next='+encodeURIComponent(location.pathname+location.search+location.hash)">{{ t.player_switch_language }}</button>
</div>
</section>
<section class="user-settings-section"> <section class="user-settings-section">
<div class="user-settings-section-head"> <div class="user-settings-section-head">
<div> <div>
@@ -814,7 +1074,7 @@
@click.stop="$store.history.playFrom(idx)" @click.stop="$store.history.playFrom(idx)"
:title="item.track?.title || item.track_title"> :title="item.track?.title || item.track_title">
<template x-if="item.track && item.track.cover_url"> <template x-if="item.track && item.track.cover_url">
<img :src="item.track.cover_url" :alt="item.track.title" loading="lazy"> <img :src="item.track.cover_url" alt="" aria-hidden="true" loading="lazy">
</template> </template>
<template x-if="!item.track || !item.track.cover_url"> <template x-if="!item.track || !item.track.cover_url">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="4"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="4"/></svg>
File diff suppressed because it is too large Load Diff
+116 -50
View File
@@ -17,6 +17,17 @@
<div class="user-role" x-text="$store.user.profile?.role || ''"></div> <div class="user-role" x-text="$store.user.profile?.role || ''"></div>
</div> </div>
<div class="user-widget-actions"> <div class="user-widget-actions">
<button class="user-logout-btn"
x-show="$store.user.profile?.role === 'admin'"
x-cloak
@click="window.location.href = '/admin/'"
title="{{ t.player_admin_panel }}"
aria-label="{{ t.player_admin_panel }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
<path d="M12 3l7 3v5c0 4.6-2.9 8.1-7 10-4.1-1.9-7-5.4-7-10V6l7-3z"/>
<path d="M9.5 12l1.7 1.7 3.6-4"/>
</svg>
</button>
<button class="user-logout-btn" @click="$store.user.openSettings()" title="User settings" aria-label="User settings"> <button class="user-logout-btn" @click="$store.user.openSettings()" title="User settings" aria-label="User settings">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
<circle cx="12" cy="12" r="3"/> <circle cx="12" cy="12" r="3"/>
@@ -80,7 +91,7 @@
@click="$store.library.openArtist(artist.id)"> @click="$store.library.openArtist(artist.id)">
<div class="following-avatar"> <div class="following-avatar">
<template x-if="artist.image_url"> <template x-if="artist.image_url">
<img :src="artist.image_url" :alt="artist.name" loading="lazy"> <img :src="artist.image_url" alt="" aria-hidden="true" loading="lazy">
</template> </template>
<template x-if="!artist.image_url"> <template x-if="!artist.image_url">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><circle cx="12" cy="8" r="4"/><path d="M20 21a8 8 0 10-16 0"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><circle cx="12" cy="8" r="4"/><path d="M20 21a8 8 0 10-16 0"/></svg>
@@ -143,9 +154,6 @@
</div> </div>
</template> </template>
</div> </div>
<div class="sidebar-bottom">
<a href="/admin/">{{ t.player_admin_panel }}</a>
</div>
</div> </div>
<template x-if="$store.mobile.libraryOpen"> <template x-if="$store.mobile.libraryOpen">
@@ -196,7 +204,7 @@
@click="$store.library.openArtist(artist.id); $store.mobile.closeLibrary()"> @click="$store.library.openArtist(artist.id); $store.mobile.closeLibrary()">
<div class="following-avatar"> <div class="following-avatar">
<template x-if="artist.image_url"> <template x-if="artist.image_url">
<img :src="artist.image_url" :alt="artist.name" loading="lazy"> <img :src="artist.image_url" alt="" aria-hidden="true" loading="lazy">
</template> </template>
<template x-if="!artist.image_url"> <template x-if="!artist.image_url">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><circle cx="12" cy="8" r="4"/><path d="M20 21a8 8 0 10-16 0"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><circle cx="12" cy="8" r="4"/><path d="M20 21a8 8 0 10-16 0"/></svg>
@@ -317,6 +325,7 @@
<span class="search-shortcut">Ctrl+K</span> <span class="search-shortcut">Ctrl+K</span>
</template> </template>
</div> </div>
{% if downloads_enabled %}
<button class="torrent-import-btn" <button class="torrent-import-btn"
@click="$store.torrents.open()" @click="$store.torrents.open()"
title="{{ t.player_import_torrent }}"> title="{{ t.player_import_torrent }}">
@@ -326,6 +335,7 @@
<line x1="12" y1="15" x2="12" y2="3"/> <line x1="12" y1="15" x2="12" y2="3"/>
</svg> </svg>
</button> </button>
{% endif %}
<button class="mobile-account-chip" <button class="mobile-account-chip"
x-show="$store.user.profile" x-show="$store.user.profile"
x-cloak x-cloak
@@ -359,6 +369,17 @@
</div> </div>
</div> </div>
<div class="mobile-account-actions"> <div class="mobile-account-actions">
<button class="user-logout-btn"
x-show="$store.user.profile?.role === 'admin'"
x-cloak
@click="window.location.href = '/admin/'"
title="{{ t.player_admin_panel }}"
aria-label="{{ t.player_admin_panel }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
<path d="M12 3l7 3v5c0 4.6-2.9 8.1-7 10-4.1-1.9-7-5.4-7-10V6l7-3z"/>
<path d="M9.5 12l1.7 1.7 3.6-4"/>
</svg>
</button>
<button class="user-logout-btn" <button class="user-logout-btn"
@click="$store.user.menuOpen = false; $store.user.openSettings()" @click="$store.user.menuOpen = false; $store.user.openSettings()"
title="User settings" title="User settings"
@@ -379,12 +400,35 @@
<!-- Search Results --> <!-- Search Results -->
<template x-if="$store.library.view === 'search'"> <template x-if="$store.library.view === 'search'">
<div> <div>
<div class="search-similarity-heading"
x-show="$store.library.similaritySearchLabel"
x-cloak>
<h2 class="search-similarity-title">
<span>{{ t.player_search_similar_to }}</span>
<strong x-text="$store.library.similaritySearchLabel"></strong>
</h2>
<div class="search-similarity-progress"
:class="{ loading: $store.library.similaritySearchStats.loading }">
<template x-if="$store.library.similaritySearchStats.loading">
<span class="search-progress-live"><i></i> Searching peers…</span>
</template>
<span x-text="`${$store.library.similaritySearchStats.tracks} tracks · ${$store.library.similaritySearchStats.artists} artists`"></span>
<template x-if="!$store.library.similaritySearchStats.loading">
<span x-text="`${$store.library.similaritySearchStats.peers} peers · ${$store.library.formatSearchDuration($store.library.similaritySearchStats.elapsed_ms)}`"></span>
</template>
</div>
</div>
<template x-if="$store.library.searchLoading"> <template x-if="$store.library.searchLoading">
<div class="loading-spinner"><div class="spinner"></div></div> <div class="loading-spinner"><div class="spinner"></div></div>
</template> </template>
<template x-if="!$store.library.searchLoading && $store.library.similaritySearchError">
<div class="empty-state">
<p x-text="$store.library.similaritySearchError"></p>
</div>
</template>
<template x-if="!$store.library.searchLoading && $store.library.searchResults"> <template x-if="!$store.library.searchLoading && $store.library.searchResults">
<div> <div :class="{ 'similarity-unified-results': $store.library.similaritySearchLabel }">
<template x-if="$store.library.searchResults.artists.length === 0 && $store.library.searchResults.releases.length === 0 && $store.library.searchResults.tracks.length === 0"> <template x-if="!$store.library.similaritySearchError && $store.library.searchResults.artists.length === 0 && $store.library.searchResults.releases.length === 0 && $store.library.searchResults.tracks.length === 0">
<div class="empty-state"> <div class="empty-state">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
<p>{{ t.player_no_results }}</p> <p>{{ t.player_no_results }}</p>
@@ -398,11 +442,9 @@
<template x-for="artist in $store.library.searchResults.artists" :key="artist.id"> <template x-for="artist in $store.library.searchResults.artists" :key="artist.id">
<div class="search-artist-card" @click="$store.library.openArtist(artist.id)"> <div class="search-artist-card" @click="$store.library.openArtist(artist.id)">
<div class="search-artist-img"> <div class="search-artist-img">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="12" cy="8" r="4"/><path d="M20 21a8 8 0 10-16 0"/></svg>
<template x-if="artist.image_url"> <template x-if="artist.image_url">
<img :src="artist.image_url" :alt="artist.name" loading="lazy"> <img class="artwork-image" :src="artist.image_url" alt="" aria-hidden="true" loading="lazy" @load="$event.currentTarget.classList.add('artwork-loaded')" @error="$event.currentTarget.classList.remove('artwork-loaded')">
</template>
<template x-if="!artist.image_url">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="12" cy="8" r="4"/><path d="M20 21a8 8 0 10-16 0"/></svg>
</template> </template>
</div> </div>
<div class="search-artist-name" x-text="artist.name"></div> <div class="search-artist-name" x-text="artist.name"></div>
@@ -419,11 +461,9 @@
<template x-for="release in $store.library.searchResults.releases" :key="release.id"> <template x-for="release in $store.library.searchResults.releases" :key="release.id">
<div class="search-release-card" @click="$store.library.openRelease(release.id)" style="position:relative"> <div class="search-release-card" @click="$store.library.openRelease(release.id)" style="position:relative">
<div class="search-release-cover" style="position:relative"> <div class="search-release-cover" style="position:relative">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="4"/></svg>
<template x-if="release.cover_url"> <template x-if="release.cover_url">
<img :src="release.cover_url" :alt="release.title" loading="lazy"> <img class="artwork-image" :src="release.cover_url" alt="" aria-hidden="true" loading="lazy" @load="$event.currentTarget.classList.add('artwork-loaded')" @error="$event.currentTarget.classList.remove('artwork-loaded')">
</template>
<template x-if="!release.cover_url">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="4"/></svg>
</template> </template>
<button class="card-info-btn" @click.stop="$store.library.openReleaseInfo(release)" :title="$store.library.releaseInfo(release)" aria-label="{{ t.player_release_info }}"> <button class="card-info-btn" @click.stop="$store.library.openReleaseInfo(release)" :title="$store.library.releaseInfo(release)" aria-label="{{ t.player_release_info }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
@@ -453,7 +493,8 @@
<template x-for="(track, idx) in $store.library.searchResults.tracks" :key="track.id"> <template x-for="(track, idx) in $store.library.searchResults.tracks" :key="track.id">
<div class="track-row" <div class="track-row"
:class="{ playing: $store.player.currentTrack && $store.player.currentTrack.id === track.id }" :class="{ playing: $store.player.currentTrack && $store.player.currentTrack.id === track.id }"
@dblclick="$store.library.playSearchTrack(idx)"> :style="$store.library.similaritySearchLabel ? `order:${$store.library.similarityTrackOrder(track)}` : ''"
@dblclick="$store.library.similaritySearchLabel ? $store.library.playSimilarityResult(track) : $store.library.playSearchTrack(idx)">
<span class="track-num" x-text="idx + 1"></span> <span class="track-num" x-text="idx + 1"></span>
<div class="track-info"> <div class="track-info">
<div class="track-title" x-text="track.title"></div> <div class="track-title" x-text="track.title"></div>
@@ -498,8 +539,9 @@
</template> </template>
</div> </div>
</template> </template>
<div class="search-section federation-search-section"> <div class="search-section federation-search-section"
<h2 class="search-section-title"> :class="{ 'similarity-federation-merged': $store.library.similaritySearchLabel }">
<h2 class="search-section-title" x-show="!$store.library.similaritySearchLabel">
Federation Federation
<span class="federation-live-badge" <span class="federation-live-badge"
x-show="$store.library.federationSearch.loading" x-show="$store.library.federationSearch.loading"
@@ -509,11 +551,11 @@
<div class="federation-search-status error" <div class="federation-search-status error"
x-text="$store.library.federationSearch.error"></div> x-text="$store.library.federationSearch.error"></div>
</template> </template>
<template x-if="$store.library.federationSearch.loading && $store.library.federationSearch.tracks.length === 0"> <template x-if="!$store.library.similaritySearchLabel && $store.library.federationSearch.loading && $store.library.federationSearch.tracks.length === 0">
<div class="federation-search-status">Searching peers…</div> <div class="federation-search-status">Searching peers…</div>
</template> </template>
<div class="search-artists-row" <div class="search-artists-row"
x-show="$store.library.federationSearch.artists.length > 0" x-show="!$store.library.similaritySearchLabel && $store.library.federationSearch.artists.length > 0"
x-cloak> x-cloak>
<template x-for="artist in $store.library.federationSearch.artists" <template x-for="artist in $store.library.federationSearch.artists"
:key="artist.key.normalized_name"> :key="artist.key.normalized_name">
@@ -521,10 +563,12 @@
@click="$store.library.openFederatedArtist(artist)"> @click="$store.library.openFederatedArtist(artist)">
<div class="search-artist-img"> <div class="search-artist-img">
<img x-show="$store.library.federationArtistImage(artist)" <img x-show="$store.library.federationArtistImage(artist)"
class="artwork-image"
:src="$store.library.federationArtistImage(artist)" :src="$store.library.federationArtistImage(artist)"
:alt="artist.name" alt="" aria-hidden="true"
loading="lazy" loading="lazy"
@error="$event.currentTarget.style.display = 'none'"> @load="$event.currentTarget.classList.add('artwork-loaded')"
@error="$event.currentTarget.classList.remove('artwork-loaded'); $store.library.federationArtistImageFailed(artist)">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<circle cx="12" cy="8" r="4"/><path d="M20 21a8 8 0 10-16 0"/> <circle cx="12" cy="8" r="4"/><path d="M20 21a8 8 0 10-16 0"/>
</svg> </svg>
@@ -536,18 +580,21 @@
</template> </template>
</div> </div>
<div class="search-releases-row" <div class="search-releases-row"
x-show="$store.library.federationSearch.releases.length > 0" x-show="!$store.library.similaritySearchLabel && $store.library.federationSearch.releases.length > 0"
x-cloak> x-cloak>
<template x-for="release in $store.library.federationSearch.releases" <template x-for="release in $store.library.federationSearch.releases"
:key="JSON.stringify(release.key)"> :key="JSON.stringify(release.key)">
<div class="search-release-card federation-entity-card"> <div class="search-release-card federation-entity-card"
@click="$store.library.openFederatedRelease($store.library.hydrateFederationSearchRelease(release))">
<div class="search-release-cover"> <div class="search-release-cover">
<img x-show="release.cover_url" <img x-show="$store.library.federationReleaseCover(release)"
:src="release.cover_url" class="artwork-image"
:alt="release.title" :src="$store.library.federationReleaseCover(release)"
loading="lazy"> alt="" aria-hidden="true"
<svg x-show="!release.cover_url" loading="lazy"
viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"> @load="$event.currentTarget.classList.add('artwork-loaded')"
@error="$event.currentTarget.classList.remove('artwork-loaded'); $store.library.federationReleaseCoverFailed(release, $event.currentTarget.getAttribute('src'))">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="4"/> <rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="4"/>
</svg> </svg>
</div> </div>
@@ -560,7 +607,8 @@
<template x-for="(track, idx) in $store.library.federationSearch.tracks" <template x-for="(track, idx) in $store.library.federationSearch.tracks"
:key="track.key.content_id"> :key="track.key.content_id">
<div class="track-row federation-track-row" <div class="track-row federation-track-row"
@dblclick="$store.library.playFederatedTrack(track)"> :style="$store.library.similaritySearchLabel ? `order:${$store.library.similarityTrackOrder(track)}` : ''"
@dblclick="$store.library.similaritySearchLabel ? $store.library.playSimilarityResult($store.library.federationQueueTrack(track)) : $store.library.playFederatedTrack(track)">
<span class="track-num federation-track-status"> <span class="track-num federation-track-status">
<template x-if="!$store.library.federationDownload(track.key.content_id) && !$store.library.federationFailure(track.key.content_id) && !$store.library.isTrackLocal(track)"> <template x-if="!$store.library.federationDownload(track.key.content_id) && !$store.library.federationFailure(track.key.content_id) && !$store.library.isTrackLocal(track)">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
@@ -634,6 +682,12 @@
x-text="formatTime(track.metadata.duration_seconds)"></span> x-text="formatTime(track.metadata.duration_seconds)"></span>
</div> </div>
</template> </template>
<div class="similarity-search-inline-progress"
x-show="$store.library.similaritySearchLabel && $store.library.similaritySearchStats.loading"
x-cloak>
<span class="similarity-search-inline-spinner" aria-hidden="true"></span>
<span>Searching federation for more similar tracks…</span>
</div>
</div> </div>
</div> </div>
</template> </template>
@@ -655,7 +709,7 @@
<div class="card" @click="$store.library.openArtist(artist.id)"> <div class="card" @click="$store.library.openArtist(artist.id)">
<div class="card-img"> <div class="card-img">
<template x-if="artist.image_url"> <template x-if="artist.image_url">
<img :src="artist.image_url" :alt="artist.name" loading="lazy"> <img :src="artist.image_url" alt="" aria-hidden="true" loading="lazy">
</template> </template>
<template x-if="!artist.image_url"> <template x-if="!artist.image_url">
<span class="placeholder-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="12" cy="8" r="4"/><path d="M20 21a8 8 0 10-16 0"/></svg></span> <span class="placeholder-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="12" cy="8" r="4"/><path d="M20 21a8 8 0 10-16 0"/></svg></span>
@@ -711,7 +765,7 @@
<div class="artist-img"> <div class="artist-img">
<template x-if="$store.library.currentArtist.image_url"> <template x-if="$store.library.currentArtist.image_url">
<img :src="$store.library.currentArtist.image_url" <img :src="$store.library.currentArtist.image_url"
:alt="$store.library.currentArtist.name" alt="" aria-hidden="true"
@error="$store.library.currentArtist.image_url = null"> @error="$store.library.currentArtist.image_url = null">
</template> </template>
<template x-if="!$store.library.currentArtist.image_url"> <template x-if="!$store.library.currentArtist.image_url">
@@ -757,8 +811,22 @@
</div> </div>
</div> </div>
<template x-if="$store.library.currentArtist.top_tracks && $store.library.currentArtist.top_tracks.length > 0"> <template x-if="$store.library.currentArtist.top_tracks && $store.library.currentArtist.top_tracks.length > 0">
<section class="artist-release-group"> <section class="artist-release-group" x-data="{ expanded: false }">
<h2 class="artist-release-group-title">{{ t.player_top_tracks }}</h2> <div class="artist-release-group-heading">
<h2 class="artist-release-group-title">{{ t.player_top_tracks }}</h2>
<button class="artist-top-tracks-toggle"
type="button"
x-show="$store.library.currentArtist.top_tracks.length > 5"
@click="expanded = !expanded"
:aria-expanded="expanded"
x-cloak>
<span x-text="expanded ? '{{ t.player_collapse }}' : '{{ t.player_expand_all }}'"></span>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
:class="{ expanded: expanded }">
<polyline points="6 9 12 15 18 9"/>
</svg>
</button>
</div>
<div class="track-list-header"> <div class="track-list-header">
<span>#</span> <span>#</span>
<span>{{ t.player_title }}</span> <span>{{ t.player_title }}</span>
@@ -766,7 +834,9 @@
<span></span> <span></span>
<span style="text-align:right">{{ t.player_duration }}</span> <span style="text-align:right">{{ t.player_duration }}</span>
</div> </div>
<template x-for="(track, idx) in $store.library.currentArtist.top_tracks" :key="track.id"> <template x-for="(track, idx) in (expanded
? $store.library.currentArtist.top_tracks
: $store.library.currentArtist.top_tracks.slice(0, 5))" :key="track.id">
<div class="track-row artist-appearance-row" <div class="track-row artist-appearance-row"
:class="{ playing: $store.player.currentTrack && $store.player.currentTrack.id === track.id }" :class="{ playing: $store.player.currentTrack && $store.player.currentTrack.id === track.id }"
@dblclick="$store.queue.playRelease($store.library.currentArtist.top_tracks, idx)"> @dblclick="$store.queue.playRelease($store.library.currentArtist.top_tracks, idx)">
@@ -778,7 +848,7 @@
:title="track.release_title" :title="track.release_title"
aria-label="{{ t.player_release }}"> aria-label="{{ t.player_release }}">
<template x-if="track.cover_url"> <template x-if="track.cover_url">
<img :src="track.cover_url" :alt="track.release_title" loading="lazy"> <img :src="track.cover_url" alt="" aria-hidden="true" loading="lazy">
</template> </template>
<template x-if="!track.cover_url"> <template x-if="!track.cover_url">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="4"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="4"/></svg>
@@ -841,7 +911,7 @@
<div class="card" @click="$store.library.openRelease(release.id)"> <div class="card" @click="$store.library.openRelease(release.id)">
<div class="card-img"> <div class="card-img">
<template x-if="release.cover_url"> <template x-if="release.cover_url">
<img :src="release.cover_url" :alt="release.title" <img :src="release.cover_url" alt="" aria-hidden="true"
loading="lazy" @error="release.cover_url = null"> loading="lazy" @error="release.cover_url = null">
</template> </template>
<template x-if="!release.cover_url"> <template x-if="!release.cover_url">
@@ -877,7 +947,7 @@
@click="$store.library.openFederatedRelease(release)"> @click="$store.library.openFederatedRelease(release)">
<div class="card-img"> <div class="card-img">
<template x-if="release.cover_url"> <template x-if="release.cover_url">
<img :src="release.cover_url" :alt="release.title" <img :src="release.cover_url" alt="" aria-hidden="true"
loading="lazy" @error="release.cover_url = null"> loading="lazy" @error="release.cover_url = null">
</template> </template>
<template x-if="!release.cover_url"> <template x-if="!release.cover_url">
@@ -1007,7 +1077,7 @@
:title="track.release_title" :title="track.release_title"
aria-label="{{ t.player_release }}"> aria-label="{{ t.player_release }}">
<template x-if="track.cover_url"> <template x-if="track.cover_url">
<img :src="track.cover_url" :alt="track.release_title" loading="lazy"> <img :src="track.cover_url" alt="" aria-hidden="true" loading="lazy">
</template> </template>
<template x-if="!track.cover_url"> <template x-if="!track.cover_url">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="4"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="4"/></svg>
@@ -1081,7 +1151,7 @@
<div class="release-header"> <div class="release-header">
<div class="release-cover"> <div class="release-cover">
<template x-if="$store.library.currentRelease.cover_url"> <template x-if="$store.library.currentRelease.cover_url">
<img :src="$store.library.currentRelease.cover_url" :alt="$store.library.currentRelease.title"> <img :src="$store.library.currentRelease.cover_url" alt="" aria-hidden="true">
</template> </template>
<template x-if="!$store.library.currentRelease.cover_url"> <template x-if="!$store.library.currentRelease.cover_url">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="4"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="4"/></svg>
@@ -1459,11 +1529,9 @@
<svg viewBox="0 0 24 24" fill="currentColor"><circle cx="9" cy="6" r="1.5"/><circle cx="15" cy="6" r="1.5"/><circle cx="9" cy="12" r="1.5"/><circle cx="15" cy="12" r="1.5"/><circle cx="9" cy="18" r="1.5"/><circle cx="15" cy="18" r="1.5"/></svg> <svg viewBox="0 0 24 24" fill="currentColor"><circle cx="9" cy="6" r="1.5"/><circle cx="15" cy="6" r="1.5"/><circle cx="9" cy="12" r="1.5"/><circle cx="15" cy="12" r="1.5"/><circle cx="9" cy="18" r="1.5"/><circle cx="15" cy="18" r="1.5"/></svg>
</div> </div>
<div class="queue-track-cover"> <div class="queue-track-cover">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
<template x-if="item.track.cover_url"> <template x-if="item.track.cover_url">
<img :src="item.track.cover_url" :alt="item.track.title" loading="lazy"> <img class="artwork-image" :src="item.track.cover_url" alt="" aria-hidden="true" loading="lazy" @load="$event.currentTarget.classList.add('artwork-loaded')" @error="$event.currentTarget.classList.remove('artwork-loaded')">
</template>
<template x-if="!item.track.cover_url">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
</template> </template>
<span class="queue-federation-status federation-track-status" <span class="queue-federation-status federation-track-status"
x-show="item.track.federation_pending" x-show="item.track.federation_pending"
@@ -1543,7 +1611,7 @@
<div class="player-cover" <div class="player-cover"
@click.stop="$store.mobile.openPlayerFullscreen()"> @click.stop="$store.mobile.openPlayerFullscreen()">
<template x-if="$store.player.currentTrack.cover_url"> <template x-if="$store.player.currentTrack.cover_url">
<img :src="$store.player.currentTrack.cover_url" :alt="$store.player.currentTrack.title"> <img :src="$store.player.currentTrack.cover_url" alt="" aria-hidden="true">
</template> </template>
<template x-if="!$store.player.currentTrack.cover_url"> <template x-if="!$store.player.currentTrack.cover_url">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
@@ -1841,11 +1909,9 @@
type="button" type="button"
@click="item.index >= 0 ? $store.queue.playFromIndex(item.index) : $store.player.play(item.track)"> @click="item.index >= 0 ? $store.queue.playFromIndex(item.index) : $store.player.play(item.track)">
<div class="mobile-expanded-queue-cover"> <div class="mobile-expanded-queue-cover">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
<template x-if="item.track.cover_url"> <template x-if="item.track.cover_url">
<img :src="item.track.cover_url" :alt="item.track.title" loading="lazy"> <img class="artwork-image" :src="item.track.cover_url" alt="" aria-hidden="true" loading="lazy" @load="$event.currentTarget.classList.add('artwork-loaded')" @error="$event.currentTarget.classList.remove('artwork-loaded')">
</template>
<template x-if="!item.track.cover_url">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
</template> </template>
</div> </div>
<div class="mobile-expanded-queue-info"> <div class="mobile-expanded-queue-info">
+678 -18
View File
@@ -450,22 +450,6 @@ button.user-stat:hover {
letter-spacing: 0.3px; letter-spacing: 0.3px;
} }
.sidebar-bottom {
padding: 12px 16px;
border-top: 1px solid var(--border-color);
}
.sidebar-bottom a {
color: var(--text-subdued);
text-decoration: none;
font-size: 12px;
display: flex;
align-items: center;
gap: 6px;
}
.sidebar-bottom a:hover { color: var(--text-secondary); }
/* Center Content */ /* Center Content */
.center-content { .center-content {
flex: 1; flex: 1;
@@ -676,6 +660,42 @@ button.user-stat:hover {
margin-bottom: 14px; margin-bottom: 14px;
text-transform: capitalize; text-transform: capitalize;
} }
.artist-release-group-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
margin-bottom: 14px;
}
.artist-release-group-heading .artist-release-group-title {
margin-bottom: 0;
}
.artist-top-tracks-toggle {
border: 0;
background: transparent;
color: var(--text-subdued);
display: inline-flex;
align-items: center;
gap: 6px;
padding: 5px 7px;
border-radius: 5px;
font: inherit;
font-size: 12px;
font-weight: 700;
cursor: pointer;
}
.artist-top-tracks-toggle:hover {
color: var(--text-primary);
background: var(--bg-hover);
}
.artist-top-tracks-toggle svg {
width: 15px;
height: 15px;
transition: transform 0.18s ease;
}
.artist-top-tracks-toggle svg.expanded {
transform: rotate(180deg);
}
/* Release detail header */ /* Release detail header */
.release-header { .release-header {
@@ -1375,7 +1395,7 @@ button.user-stat:hover {
justify-content: center; justify-content: center;
} }
.queue-track-cover img { width: 100%; height: 100%; object-fit: cover; border-radius: inherit; } .queue-track-cover img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; border-radius: inherit; }
.queue-track-cover svg { width: 20px; height: 20px; color: var(--text-subdued); } .queue-track-cover svg { width: 20px; height: 20px; color: var(--text-subdued); }
.queue-track-cover .queue-federation-status { .queue-track-cover .queue-federation-status {
@@ -2715,6 +2735,41 @@ button.user-stat:hover {
border-top: 1px solid var(--border); border-top: 1px solid var(--border);
padding-top: 18px; padding-top: 18px;
} }
.federation-search-section.similarity-federation-merged {
margin-top: -24px;
padding-top: 0;
border-top: 0;
}
.similarity-unified-results {
display: flex;
flex-direction: column;
}
.similarity-unified-results > .search-section {
display: contents;
}
.similarity-unified-results .search-section-title { order: -1000002; }
.similarity-unified-results .track-list-header { order: -1000001; }
.similarity-unified-results .federation-search-status { order: 1000001; }
.similarity-search-inline-progress {
order: 1000000;
display: flex;
align-items: center;
justify-content: center;
gap: 9px;
min-height: 42px;
margin-top: 4px;
border-top: 1px solid var(--border);
color: var(--text-muted);
font-size: 12px;
}
.similarity-search-inline-spinner {
width: 14px;
height: 14px;
border: 2px solid rgba(255, 255, 255, .16);
border-top-color: var(--accent);
border-radius: 999px;
animation: federation-progress-spin .8s linear infinite;
}
.federation-live-badge { .federation-live-badge {
margin-left: 8px; margin-left: 8px;
color: var(--accent); color: var(--accent);
@@ -2836,6 +2891,65 @@ button.user-stat:hover {
margin-bottom: 12px; margin-bottom: 12px;
} }
.search-similarity-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
margin: 0 0 20px;
}
.search-similarity-title {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 8px;
min-width: 0;
margin: 0;
color: var(--text-muted);
font-size: 16px;
font-weight: 500;
}
.search-similarity-title strong {
color: var(--text);
font-size: 20px;
}
.search-similarity-progress {
flex: 0 0 auto;
display: flex;
align-items: center;
gap: 10px;
min-height: 30px;
padding: 5px 10px;
border: 1px solid var(--border);
border-radius: 7px;
background: var(--bg-secondary);
color: var(--text-muted);
font-size: 11px;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.search-similarity-progress.loading { border-color: rgba(29, 185, 84, .38); }
.search-progress-live {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--accent);
}
.search-progress-live i {
width: 7px;
height: 7px;
border-radius: 999px;
background: currentColor;
animation: similarity-search-pulse 1.1s ease-in-out infinite;
}
@keyframes similarity-search-pulse {
50% { opacity: .3; transform: scale(.75); }
}
@media (max-width: 720px) {
.search-similarity-heading { align-items: flex-start; flex-direction: column; }
.search-similarity-progress { max-width: 100%; flex-wrap: wrap; white-space: normal; }
}
.search-artists-row { .search-artists-row {
display: flex; display: flex;
gap: 16px; gap: 16px;
@@ -2908,6 +3022,7 @@ button.user-stat:hover {
.search-release-card:hover { background: var(--bg-elevated); } .search-release-card:hover { background: var(--bg-elevated); }
.search-release-cover { .search-release-cover {
position: relative;
width: 100%; width: 100%;
aspect-ratio: 1; aspect-ratio: 1;
border-radius: 6px; border-radius: 6px;
@@ -2919,9 +3034,12 @@ button.user-stat:hover {
justify-content: center; justify-content: center;
} }
.search-release-cover img { width: 100%; height: 100%; object-fit: cover; } .search-release-cover img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
.search-release-cover svg { width: 40px; height: 40px; color: var(--text-subdued); } .search-release-cover svg { width: 40px; height: 40px; color: var(--text-subdued); }
.artwork-image { z-index: 1; opacity: 0; }
.artwork-image.artwork-loaded { opacity: 1; }
/* Like button */ /* Like button */
.like-btn { .like-btn {
background: none; background: none;
@@ -3297,6 +3415,487 @@ button.user-stat:hover {
font-size: 11px; font-size: 11px;
} }
.download-source-tabs {
padding-bottom: 10px;
border-bottom: 1px solid var(--border-color);
}
.download-source-tabs .torrent-tab-btn {
min-width: 112px;
justify-content: center;
}
.download-torrent-panel,
.youtube-manager-panel {
min-height: 0;
flex: 1 1 auto;
}
.file-upload-panel {
min-height: 0;
flex: 1 1 auto;
display: flex;
flex-direction: column;
gap: 12px;
overflow: hidden;
}
.file-upload-input {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
clip-path: inset(50%);
white-space: nowrap;
}
.file-drop-zone {
min-height: 176px;
flex: 0 0 auto;
display: flex !important;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 6px;
margin: 0 !important;
padding: 24px;
border: 2px dashed var(--border-color);
border-radius: 12px;
background: var(--bg-primary);
color: var(--text-subdued);
text-align: center;
cursor: pointer;
transition: border-color 150ms ease, background 150ms ease, transform 150ms ease;
}
.file-drop-zone:hover,
.file-drop-zone.dragging {
border-color: var(--accent);
background: rgba(29,185,84,0.08);
}
.file-drop-zone.dragging {
transform: scale(0.995);
}
.file-drop-zone strong {
color: var(--text-primary);
font-size: 15px;
}
.file-drop-zone span {
font-size: 12px;
}
.file-drop-zone small {
margin-top: 2px;
color: var(--text-muted);
font-size: 10px;
}
.file-drop-icon {
width: 42px;
height: 42px;
display: inline-flex;
align-items: center;
justify-content: center;
margin-bottom: 4px;
border-radius: 50%;
background: rgba(29,185,84,0.14);
color: #7ee29e;
}
.file-drop-icon svg {
width: 23px;
height: 23px;
}
.file-upload-selection {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 10px 12px;
border: 1px solid var(--border-color);
border-radius: 8px;
background: var(--bg-primary);
color: var(--text-secondary);
font-size: 12px;
font-weight: 700;
}
.file-upload-selection > div {
display: flex;
gap: 7px;
}
.file-upload-history-head {
margin-top: 2px;
}
.file-upload-history {
min-height: 0;
flex: 1 1 auto;
display: flex;
flex-direction: column;
gap: 8px;
overflow-y: auto;
padding-right: 4px;
}
.file-upload-history-row {
display: grid;
grid-template-columns: minmax(0, 1fr) auto auto;
gap: 10px;
align-items: center;
padding: 11px 12px;
border: 1px solid var(--border-color);
border-radius: 8px;
background: var(--bg-primary);
}
.file-upload-history-main {
min-width: 0;
}
.file-upload-history-title {
overflow: hidden;
color: var(--text-primary);
font-size: 12px;
font-weight: 750;
text-overflow: ellipsis;
white-space: nowrap;
}
.file-upload-history-meta {
margin-top: 3px;
color: var(--text-subdued);
font-size: 10px;
}
.download-torrent-panel {
display: flex;
flex-direction: column;
}
.youtube-manager-panel {
display: flex;
flex-direction: column;
gap: 12px;
overflow: hidden;
}
.youtube-download-form {
flex: 0 0 auto;
padding: 14px;
border: 1px solid var(--border-color);
border-radius: 9px;
background: var(--bg-primary);
}
.youtube-download-form-row {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 10px;
align-items: center;
}
.torrent-modal .youtube-download-form-row input[type="text"] {
margin: 0;
}
.youtube-download-hint {
margin: 8px 0 0;
color: var(--text-subdued);
font-size: 11px;
line-height: 1.45;
}
.youtube-preview-card {
min-height: 0;
flex: 0 1 360px;
display: flex;
flex-direction: column;
gap: 10px;
padding: 14px;
border: 1px solid rgba(29,185,84,0.35);
border-radius: 9px;
background: var(--bg-primary);
}
.youtube-preview-head,
.youtube-preview-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.youtube-preview-head h4 {
margin: 0 0 4px;
color: var(--text-primary);
font-size: 13px;
}
.youtube-preview-head p {
margin: 0;
color: var(--text-subdued);
font-size: 11px;
}
.youtube-preview-head strong {
color: var(--text-secondary);
}
.youtube-preview-controls,
.youtube-preview-footer > div {
display: flex;
align-items: center;
gap: 7px;
flex: 0 0 auto;
}
.youtube-preview-list {
min-height: 72px;
overflow-y: auto;
border: 1px solid var(--border-color);
border-radius: 7px;
background: var(--bg-secondary);
}
.youtube-preview-row {
display: grid;
grid-template-columns: auto 30px minmax(0, 1fr);
gap: 8px;
align-items: center;
min-height: 38px;
padding: 6px 10px;
border-bottom: 1px solid var(--border-color);
color: var(--text-secondary);
cursor: pointer;
}
.youtube-preview-row:last-child {
border-bottom: 0;
}
.youtube-preview-row:hover,
.youtube-preview-row.selected {
background: var(--bg-hover);
color: var(--text-primary);
}
.youtube-preview-row input[type="checkbox"] {
width: 15px;
height: 15px;
margin: 0;
accent-color: #1db954;
}
.youtube-preview-item-title {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 12px;
font-weight: 650;
}
.youtube-preview-footer {
color: var(--text-subdued);
font-size: 11px;
font-weight: 700;
}
.youtube-download-list-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
flex: 0 0 auto;
color: var(--text-secondary);
font-size: 12px;
font-weight: 800;
text-transform: uppercase;
}
.youtube-download-list {
min-height: 0;
display: flex;
flex-direction: column;
gap: 10px;
overflow-y: auto;
padding-right: 4px;
}
.youtube-empty-state {
min-height: 180px;
border: 1px dashed var(--border-color);
border-radius: 9px;
}
.youtube-job-card {
flex: 0 0 auto;
padding: 13px;
border: 1px solid var(--border-color);
border-radius: 9px;
background: var(--bg-primary);
}
.youtube-job-head,
.youtube-item-head {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: start;
gap: 10px;
}
.youtube-job-heading,
.youtube-item-main {
min-width: 0;
}
.youtube-job-title,
.youtube-item-title {
overflow: hidden;
color: var(--text-primary);
font-weight: 800;
text-overflow: ellipsis;
white-space: nowrap;
}
.youtube-job-title { font-size: 14px; }
.youtube-item-title { font-size: 12px; }
.youtube-job-meta,
.youtube-item-meta {
margin-top: 3px;
color: var(--text-subdued);
font-size: 11px;
line-height: 1.35;
}
.youtube-job-progress {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: center;
gap: 10px;
margin-top: 9px;
color: var(--text-subdued);
font-size: 11px;
}
.youtube-job-progress .torrent-session-progress,
.youtube-item-download-progress .torrent-session-progress {
margin-top: 0;
}
.youtube-job-error,
.youtube-item-error {
margin: 8px 0 0;
color: #ffb9b9;
font-size: 11px;
line-height: 1.4;
overflow-wrap: anywhere;
}
.youtube-item-list {
display: flex;
flex-direction: column;
gap: 7px;
margin-top: 11px;
}
.youtube-item-row {
padding: 10px;
border: 1px solid rgba(255,255,255,0.07);
border-radius: 7px;
background: var(--bg-elevated);
}
.youtube-item-row.failed {
border-color: rgba(229,96,96,0.3);
}
.youtube-item-head {
grid-template-columns: 28px minmax(0, 1fr) auto;
align-items: center;
}
.youtube-item-index {
color: var(--text-muted);
font-size: 10px;
font-weight: 900;
text-align: center;
}
.youtube-item-download-progress {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 10px;
align-items: center;
margin-top: 8px;
color: var(--text-subdued);
font-size: 10px;
}
.youtube-step-list {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 4px;
margin-top: 9px;
}
.youtube-step {
min-width: 0;
display: flex;
align-items: center;
gap: 5px;
color: var(--text-muted);
font-size: 9px;
text-transform: uppercase;
}
.youtube-step i {
width: 7px;
height: 7px;
flex: 0 0 7px;
border-radius: 50%;
border: 1px solid var(--border-color);
background: var(--bg-secondary);
}
.youtube-step b {
min-width: 0;
overflow: hidden;
font: inherit;
font-weight: 800;
text-overflow: ellipsis;
white-space: nowrap;
}
.youtube-step.done { color: #9ff0b9; }
.youtube-step.done i { border-color: var(--accent); background: var(--accent); }
.youtube-step.active { color: #ffd78a; }
.youtube-step.active i {
border-color: #f0b84d;
background: #f0b84d;
box-shadow: 0 0 0 3px rgba(240,184,77,0.13);
}
.youtube-step.failed { color: #ffb9b9; }
.youtube-step.failed i { border-color: #e56060; background: #e56060; }
.youtube-step.cancelled { color: #ffd78a; }
.youtube-step.cancelled i { border-color: #f0b84d; background: #f0b84d; }
.youtube-job-actions {
display: flex;
justify-content: flex-end;
flex-wrap: wrap;
gap: 7px;
margin-top: 10px;
}
.torrent-manager-layout { .torrent-manager-layout {
display: grid; display: grid;
grid-template-columns: minmax(260px, 320px) minmax(0, 1fr); grid-template-columns: minmax(260px, 320px) minmax(0, 1fr);
@@ -5534,6 +6133,7 @@ button.user-stat:hover {
} }
.mobile-expanded-queue-cover { .mobile-expanded-queue-cover {
position: relative;
width: 42px; width: 42px;
height: 42px; height: 42px;
border-radius: 5px; border-radius: 5px;
@@ -5545,6 +6145,8 @@ button.user-stat:hover {
} }
.mobile-expanded-queue-cover img { .mobile-expanded-queue-cover img {
position: absolute;
inset: 0;
width: 100%; width: 100%;
height: 100%; height: 100%;
object-fit: cover; object-fit: cover;
@@ -5895,6 +6497,64 @@ button.user-stat:hover {
padding-bottom: 2px; padding-bottom: 2px;
} }
.youtube-manager-panel {
overflow-y: auto;
}
.file-upload-panel {
overflow-y: auto;
}
.file-upload-history {
overflow: visible;
}
.file-upload-history-row {
grid-template-columns: minmax(0, 1fr) auto;
}
.file-upload-history-row .modal-btn-danger {
grid-column: 1 / -1;
justify-self: start;
}
.file-upload-selection {
align-items: flex-start;
flex-direction: column;
}
.youtube-download-form-row {
grid-template-columns: 1fr;
}
.youtube-download-form-row .modal-btn {
justify-self: start;
}
.youtube-preview-card {
flex-basis: auto;
max-height: 330px;
}
.youtube-preview-head,
.youtube-preview-footer {
align-items: flex-start;
flex-direction: column;
}
.youtube-preview-controls {
flex-wrap: wrap;
}
.youtube-download-list {
overflow: visible;
}
.youtube-step-list {
grid-template-columns: repeat(2, minmax(0, 1fr));
row-gap: 7px;
}
.upload-manager-panel { .upload-manager-panel {
overflow-y: auto; overflow-y: auto;
} }