From 87315d96791e07866bfb8feb83040c9b10454da6 Mon Sep 17 00:00:00 2001 From: 1xDed Date: Tue, 1 Dec 2026 12:56:53 +0300 Subject: [PATCH] feat(downloads): add qBittorrent integration - Rust client for the WebUI API: password/API-key auth, categories, magnet and .torrent add, sync polling, pause/resume/delete - downloads page with progress, speed, ETA, filters, notifications and per-torrent actions - settings page with OS keyring storage, self-signed TLS, Jellyfin refresh and polling options - cross-platform keyring setup for Windows, macOS and Linux --- docs/qbittorrent-integration-plan.md | 20 +- src-tauri/Cargo.lock | 469 ++++++++++++++++- src-tauri/Cargo.toml | 21 + src-tauri/src/main.rs | 23 +- src-tauri/src/qbittorrent/client.rs | 496 ++++++++++++++++++ src-tauri/src/qbittorrent/mod.rs | 486 +++++++++++++++++ src-tauri/src/qbittorrent/types.rs | 369 +++++++++++++ src/components/appBar/appBar.scss | 1 + src/components/appBar/appBar.tsx | 10 + src/components/appBar/navigationDrawer.tsx | 7 + src/components/downloads/addTorrentDialog.tsx | 288 ++++++++++ src/components/downloads/torrentRow.tsx | 139 +++++ src/routeTree.gen.ts | 42 ++ src/routes/_api/downloads.scss | 494 +++++++++++++++++ src/routes/_api/downloads.tsx | 456 ++++++++++++++++ src/routes/_api/settings.tsx | 6 + src/routes/_api/settings/downloads.tsx | 383 ++++++++++++++ src/utils/qbittorrent/api.ts | 70 +++ src/utils/qbittorrent/format.ts | 129 +++++ src/utils/qbittorrent/hooks.ts | 38 ++ src/utils/qbittorrent/index.ts | 4 + src/utils/qbittorrent/types.ts | 101 ++++ 22 files changed, 4031 insertions(+), 21 deletions(-) create mode 100644 src-tauri/src/qbittorrent/client.rs create mode 100644 src-tauri/src/qbittorrent/mod.rs create mode 100644 src-tauri/src/qbittorrent/types.rs create mode 100644 src/components/downloads/addTorrentDialog.tsx create mode 100644 src/components/downloads/torrentRow.tsx create mode 100644 src/routes/_api/downloads.scss create mode 100644 src/routes/_api/downloads.tsx create mode 100644 src/routes/_api/settings/downloads.tsx create mode 100644 src/utils/qbittorrent/api.ts create mode 100644 src/utils/qbittorrent/format.ts create mode 100644 src/utils/qbittorrent/hooks.ts create mode 100644 src/utils/qbittorrent/index.ts create mode 100644 src/utils/qbittorrent/types.ts diff --git a/docs/qbittorrent-integration-plan.md b/docs/qbittorrent-integration-plan.md index 9ffd549..f1138f3 100644 --- a/docs/qbittorrent-integration-plan.md +++ b/docs/qbittorrent-integration-plan.md @@ -1,8 +1,22 @@ # Интеграция qBittorrent в Blink — план -> Статус: **только план**. Код не пишется до получения новой версии клиента. -> Пути к файлам указаны по текущей структуре проекта и могут измениться после -> обновления кода. +> Статус: **реализовано** (Rust-клиент, страница «Загрузки», настройки). +> Проверено на qBittorrent 5.3.0 / WebAPI 2.16.2; совместимость с 4.x +> заложена в клиент, но на живой 4.x не прогонялась. + +## 0. Заметки по реализации + +- qBittorrent 5.x принимает параметр `stopped` при добавлении раздачи, 4.x — + `paused`. Клиент отправляет оба: каждая версия читает свой и игнорирует + чужой. +- `sync/maindata` **не повторяет `hash` внутри объекта торрента** — хеш является + ключом словаря. Без подстановки ключа строки получали пустой hash, ломая + действия; в `QbTorrentRaw::from_value` хеш берётся из ключа. +- Для API-ключа заголовок `Authorization: Bearer …` нужно добавлять и к + multipart-запросу `torrents/add`; без него qB отвечает `403` (при этом + обычные GET/POST-формы работают). +- Секрет хранится в системном keyring (`blink-qbittorrent` / `default`) либо + только в памяти до закрытия приложения; в `qbittorrent.json` его нет. ## 1. Цель и рамки diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index c5dc775..f0b3d99 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -8,6 +8,17 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + [[package]] name = "aho-corasick" version = "1.1.5" @@ -115,6 +126,18 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "async-compression" +version = "0.4.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ad47a740fb906fffdd891e8b6d5fde2511600f7bfaebd68939fa08a14999459" +dependencies = [ + "compression-codecs", + "compression-core", + "pin-project-lite", + "tokio", +] + [[package]] name = "async-executor" version = "1.14.0" @@ -309,8 +332,10 @@ dependencies = [ name = "blink" version = "1.0.0-alpha.4" dependencies = [ + "keyring", "log", "portpicker", + "reqwest 0.12.28", "serde", "serde_json", "tauri", @@ -341,6 +366,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-padding" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" +dependencies = [ + "generic-array", +] + [[package]] name = "block2" version = "0.5.1" @@ -503,6 +537,15 @@ dependencies = [ "toml 1.1.8+spec-1.1.0", ] +[[package]] +name = "cbc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" +dependencies = [ + "cipher", +] + [[package]] name = "cc" version = "1.9.0" @@ -581,6 +624,16 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901" +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + [[package]] name = "clipboard-win" version = "5.4.1" @@ -610,6 +663,23 @@ dependencies = [ "memchr", ] +[[package]] +name = "compression-codecs" +version = "0.4.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e41632c2efd201c62f1432f7cbee121b97878eab579da9d85676573d1fd33b9" +dependencies = [ + "compression-core", + "flate2", + "memchr", +] + +[[package]] +name = "compression-core" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ebdda89edc534bf8d5dd2857562633b6495557e5846552ade994b99ed13c36a" + [[package]] name = "concurrent-queue" version = "2.5.0" @@ -644,10 +714,29 @@ version = "0.18.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87" dependencies = [ + "percent-encoding", "time", "version_check", ] +[[package]] +name = "cookie_store" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206" +dependencies = [ + "cookie", + "document-features", + "idna", + "log", + "publicsuffix", + "serde", + "serde_derive", + "serde_json", + "time", + "url", +] + [[package]] name = "core-foundation" version = "0.9.4" @@ -842,6 +931,25 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "dbus-secret-service" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f09471353f53b2f583ca422638cfe48a375050cdcb9e46a442b04123e74163f5" +dependencies = [ + "aes", + "block-padding", + "cbc", + "dbus", + "fastrand", + "hkdf", + "libc", + "num", + "once_cell", + "sha2", + "zeroize", +] + [[package]] name = "defmt" version = "1.2.0" @@ -911,6 +1019,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", + "subtle", ] [[package]] @@ -989,6 +1098,15 @@ dependencies = [ "const-random", ] +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + [[package]] name = "dom_query" version = "0.28.0" @@ -1785,6 +1903,24 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + [[package]] name = "html5ever" version = "0.39.0" @@ -2093,6 +2229,16 @@ dependencies = [ "cfb", ] +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "block-padding", + "generic-array", +] + [[package]] name = "ipnet" version = "2.12.2" @@ -2329,6 +2475,22 @@ dependencies = [ "serde", ] +[[package]] +name = "keyring" +version = "3.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c" +dependencies = [ + "byteorder", + "dbus-secret-service", + "log", + "secret-service", + "security-framework 2.11.1", + "security-framework 3.7.0", + "windows-sys 0.60.2", + "zeroize", +] + [[package]] name = "lazy_static" version = "1.5.1" @@ -2405,6 +2567,12 @@ version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + [[package]] name = "lock_api" version = "0.4.14" @@ -2472,6 +2640,16 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + [[package]] name = "minisign-verify" version = "0.3.0" @@ -2582,6 +2760,19 @@ version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" +[[package]] +name = "nix" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", + "memoffset", +] + [[package]] name = "nix" version = "0.31.3" @@ -2614,7 +2805,40 @@ dependencies = [ "mac-notification-sys", "serde", "tauri-winrt-notification", - "zbus", + "zbus 5.19.0", +] + +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "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", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", ] [[package]] @@ -2623,6 +2847,36 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "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]] name = "num-traits" version = "0.2.19" @@ -3471,6 +3725,22 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "psl-types" +version = "2.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33cb294fe86a74cbcf50d4445b37da762029549ebeea341421c7c70370f86cac" + +[[package]] +name = "publicsuffix" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f42ea446cab60335f76979ec15e12619a2165b5ae2c12166bef27d283a9fadf" +dependencies = [ + "idna", + "psl-types", +] + [[package]] name = "pxfm" version = "0.1.30" @@ -3756,6 +4026,8 @@ checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" dependencies = [ "base64 0.22.1", "bytes", + "cookie", + "cookie_store", "futures-core", "futures-util", "http", @@ -3766,6 +4038,7 @@ dependencies = [ "hyper-util", "js-sys", "log", + "mime_guess", "percent-encoding", "pin-project-lite", "quinn", @@ -3927,7 +4200,7 @@ dependencies = [ "openssl-probe", "rustls-pki-types", "schannel", - "security-framework", + "security-framework 3.7.0", ] [[package]] @@ -3955,7 +4228,7 @@ dependencies = [ "rustls-native-certs", "rustls-platform-verifier-android", "rustls-webpki", - "security-framework", + "security-framework 3.7.0", "security-framework-sys", "webpki-root-certs", "windows-sys 0.61.2", @@ -4065,6 +4338,38 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "secret-service" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4d35ad99a181be0a60ffcbe85d680d98f87bdc4d7644ade319b87076b9dbfd4" +dependencies = [ + "aes", + "cbc", + "futures-util", + "generic-array", + "hkdf", + "num", + "once_cell", + "rand 0.8.8", + "serde", + "sha2", + "zbus 4.4.0", +] + +[[package]] +name = "security-framework" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.9.4", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -4440,6 +4745,12 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + [[package]] name = "static_vcruntime" version = "3.0.0" @@ -4954,7 +5265,7 @@ dependencies = [ "thiserror 2.0.21", "time", "url", - "zbus", + "zbus 5.19.0", ] [[package]] @@ -5544,12 +5855,17 @@ version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" dependencies = [ + "async-compression", "bitflags 2.13.2", "bytes", + "futures-core", "futures-util", "http", "http-body", + "http-body-util", "pin-project-lite", + "tokio", + "tokio-util", "tower", "tower-layer", "tower-service", @@ -5702,6 +6018,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + [[package]] name = "unicode-ident" version = "1.0.27" @@ -6688,6 +7010,16 @@ dependencies = [ "rustix", ] +[[package]] +name = "xdg-home" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec1cdab258fb55c0da61328dc52c8764709b249011b2cad0454c72f0bf10a1f6" +dependencies = [ + "libc", + "windows-sys 0.59.0", +] + [[package]] name = "xkeysym" version = "0.2.1" @@ -6717,6 +7049,38 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zbus" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb97012beadd29e654708a0fdb4c84bc046f537aecfde2c3ee0a9e4b4d48c725" +dependencies = [ + "async-broadcast", + "async-process", + "async-recursion", + "async-trait", + "enumflags2", + "event-listener", + "futures-core", + "futures-sink", + "futures-util", + "hex", + "nix 0.29.0", + "ordered-stream", + "rand 0.8.8", + "serde", + "serde_repr", + "sha1", + "static_assertions", + "tracing", + "uds_windows", + "windows-sys 0.52.0", + "xdg-home", + "zbus_macros 4.4.0", + "zbus_names 3.0.0", + "zvariant 4.2.0", +] + [[package]] name = "zbus" version = "5.19.0" @@ -6747,9 +7111,22 @@ dependencies = [ "uuid", "windows-sys 0.61.2", "winnow 1.0.4", - "zbus_macros", - "zbus_names", - "zvariant", + "zbus_macros 5.19.0", + "zbus_names 4.3.5", + "zvariant 5.15.1", +] + +[[package]] +name = "zbus_macros" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "267db9407081e90bbfa46d841d3cbc60f59c0351838c4bc65199ecd79ab1983e" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", + "zvariant_utils 2.1.0", ] [[package]] @@ -6762,9 +7139,20 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.9", - "zbus_names", - "zvariant", - "zvariant_utils", + "zbus_names 4.3.5", + "zvariant 5.15.1", + "zvariant_utils 4.2.0", +] + +[[package]] +name = "zbus_names" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b9b1fef7d021261cc16cba64c351d291b715febe0fa10dc3a443ac5a5022e6c" +dependencies = [ + "serde", + "static_assertions", + "zvariant 4.2.0", ] [[package]] @@ -6775,7 +7163,7 @@ checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" dependencies = [ "serde", "winnow 1.0.4", - "zvariant", + "zvariant 5.15.1", ] [[package]] @@ -6833,6 +7221,20 @@ name = "zeroize" version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] [[package]] name = "zerotrie" @@ -6876,7 +7278,7 @@ dependencies = [ "crc32fast", "indexmap 2.14.2", "memchr", - "nix", + "nix 0.31.3", "typed-path", ] @@ -6907,6 +7309,19 @@ dependencies = [ "zune-core", ] +[[package]] +name = "zvariant" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2084290ab9a1c471c38fc524945837734fbf124487e105daec2bb57fd48c81fe" +dependencies = [ + "endi", + "enumflags2", + "serde", + "static_assertions", + "zvariant_derive 4.2.0", +] + [[package]] name = "zvariant" version = "5.15.1" @@ -6918,8 +7333,21 @@ dependencies = [ "serde", "winnow 1.0.4", "zcheapstr", - "zvariant_derive", - "zvariant_utils", + "zvariant_derive 5.15.1", + "zvariant_utils 4.2.0", +] + +[[package]] +name = "zvariant_derive" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73e2ba546bda683a90652bac4a279bc146adad1386f25379cf73200d2002c449" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", + "zvariant_utils 2.1.0", ] [[package]] @@ -6932,7 +7360,18 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.9", - "zvariant_utils", + "zvariant_utils 4.2.0", +] + +[[package]] +name = "zvariant_utils" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c51bcff7cc3dbb5055396bcf774748c3dab426b4b8659046963523cee4808340" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 86340d6..0450e60 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -33,6 +33,13 @@ tauri-plugin-shell = "2.3.5" tauri-plugin-websocket = "2.5.0" tauri-plugin-deep-link = "2.6.3" tauri-plugin-mcp-bridge = { version = "0.13.2", optional = true } +reqwest = { version = "0.12", default-features = false, features = [ + "cookies", + "json", + "multipart", + "gzip", + "rustls-tls", +] } [features] # by default Tauri runs in production mode @@ -47,3 +54,17 @@ custom-protocol = [ "tauri/custom-protocol" ] [target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies] tauri-plugin-global-shortcut = "2" tauri-plugin-window-state = "2" + +# Keep each OS on its native secret store without pulling the others' system +# libraries into every build. +[target.'cfg(target_os = "windows")'.dependencies] +keyring = { version = "3", default-features = false, features = ["windows-native"] } + +[target.'cfg(target_os = "macos")'.dependencies] +keyring = { version = "3", default-features = false, features = ["apple-native"] } + +[target.'cfg(target_os = "linux")'.dependencies] +keyring = { version = "3", default-features = false, features = [ + "sync-secret-service", + "crypto-rust", +] } diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index c082f56..32c4bc2 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -1,7 +1,10 @@ #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] +use tauri::Manager; use tauri_plugin_log::{fern::colors::ColoredLevelConfig, Target, TargetKind}; +mod qbittorrent; + fn main() { let builder = tauri::Builder::default(); @@ -14,18 +17,32 @@ fn main() { ); builder - .setup(|_app| { + .setup(|app| { + app.manage(qbittorrent::QbState::load(app.handle())); + // Frameless window outside macOS. macOS uses the native overlay // titlebar with its traffic lights. #[cfg(not(target_os = "macos"))] { - use tauri::Manager; - if let Some(window) = _app.get_webview_window("main") { + if let Some(window) = app.get_webview_window("main") { window.set_decorations(false)?; } } Ok(()) }) + .invoke_handler(tauri::generate_handler![ + qbittorrent::qb_get_settings, + qbittorrent::qb_save_settings, + qbittorrent::qb_forget_secret, + qbittorrent::qb_test_connection, + qbittorrent::qb_categories, + qbittorrent::qb_add_torrent, + qbittorrent::qb_poll, + qbittorrent::qb_pause, + qbittorrent::qb_resume, + qbittorrent::qb_delete, + qbittorrent::qb_set_category, + ]) .plugin(tauri_plugin_shell::init()) .plugin(tauri_plugin_global_shortcut::Builder::new().build()) .plugin(tauri_plugin_window_state::Builder::new().build()) diff --git a/src-tauri/src/qbittorrent/client.rs b/src-tauri/src/qbittorrent/client.rs new file mode 100644 index 0000000..888dfcb --- /dev/null +++ b/src-tauri/src/qbittorrent/client.rs @@ -0,0 +1,496 @@ +use std::collections::HashMap; +use std::path::Path; +use std::time::Duration; + +use reqwest::header::{ORIGIN, REFERER}; +use reqwest::multipart::{Form, Part}; +use reqwest::{Client, RequestBuilder, Response, StatusCode}; +use serde_json::Value; + +use super::types::{QbAddResponse, QbAddResult, QbCategory, QbConnectionInfo, QbError, QbSettings}; + +const CONNECT_TIMEOUT: Duration = Duration::from_secs(5); +const REQUEST_TIMEOUT: Duration = Duration::from_secs(20); +const UPLOAD_TIMEOUT: Duration = Duration::from_secs(60); + +pub struct AddTorrentInput { + pub magnet: Option, + pub file_name: Option, + pub file_bytes: Option>, + pub category: Option, + pub paused: bool, + pub auto_tmm: bool, +} + +/// Trim, validate and normalise a WebUI address. +/// +/// Accepts `host:port`, `http(s)://host:port`, a trailing slash, and a pasted +/// `.../api/v2` URL, because those are the shapes users actually copy around. +pub fn normalize_base_url(raw: &str) -> Result { + let mut url = raw.trim().trim_end_matches('/').to_string(); + if url.is_empty() { + return Err(QbError::config("Укажите адрес qBittorrent WebUI")); + } + if !url.starts_with("http://") && !url.starts_with("https://") { + url = format!("http://{url}"); + } + if let Some(stripped) = url.strip_suffix("/api/v2") { + url = stripped.trim_end_matches('/').to_string(); + } + if url.is_empty() { + return Err(QbError::config("Укажите адрес qBittorrent WebUI")); + } + + let parsed = reqwest::Url::parse(&url) + .map_err(|_| QbError::config("Некорректный адрес qBittorrent WebUI"))?; + if parsed.scheme() != "http" && parsed.scheme() != "https" { + return Err(QbError::config( + "Адрес qBittorrent должен начинаться с http:// или https://", + )); + } + if parsed.host_str().is_none() { + return Err(QbError::config("В адресе qBittorrent нет имени хоста")); + } + + Ok(url) +} + +fn map_reqwest(err: reqwest::Error) -> QbError { + let text = err.to_string(); + let lower = text.to_lowercase(); + + if lower.contains("certificate") || lower.contains("tls") || lower.contains("ssl") { + return QbError::new( + "tls", + "Сертификат qBittorrent не принят. Если используется самоподписанный \ + сертификат, включите соответствующую настройку.", + ); + } + if err.is_timeout() { + return QbError::new("unreachable", "qBittorrent не ответил вовремя"); + } + if err.is_connect() || lower.contains("connection refused") { + return QbError::new( + "unreachable", + "Не удалось подключиться к qBittorrent. Проверьте адрес и что WebUI запущен.", + ); + } + + QbError::new("http", text) +} + +fn http_error(status: StatusCode) -> QbError { + let code = status.as_u16(); + match code { + 401 => QbError::with_status( + "auth", + "qBittorrent отклонил сессию. Проверьте логин и пароль.", + code, + ), + 403 => QbError::with_status( + "auth", + "qBittorrent запретил запрос (403). Проверьте вход и адрес WebUI; \ + после нескольких неудачных попыток qBittorrent временно блокирует IP.", + code, + ), + 404 => QbError::with_status( + "http", + "Метод qBittorrent не найден (404). Возможно, версия qBittorrent слишком старая.", + code, + ), + 415 => QbError::with_status("torrent", "qBittorrent не принял файл торрента", code), + _ => QbError::with_status("http", format!("qBittorrent вернул ошибку {code}"), code), + } +} + +fn join_hashes(hashes: &[String]) -> String { + if hashes.is_empty() { + "all".to_string() + } else { + hashes.join("|") + } +} + +#[derive(Clone)] +pub struct QbClient { + pub http: Client, + pub base_url: String, + username: String, + secret: String, + use_api_key: bool, + /// Minor part of the WebAPI version (`2.11` -> `11`); 0 until connected. + pub api_minor: u32, +} + +impl QbClient { + pub fn new(settings: &QbSettings, secret: &str) -> Result { + let base_url = normalize_base_url(&settings.base_url)?; + let http = Client::builder() + .cookie_store(true) + .connect_timeout(CONNECT_TIMEOUT) + .timeout(REQUEST_TIMEOUT) + .user_agent(concat!("Blink/", env!("CARGO_PKG_VERSION"))) + .danger_accept_invalid_certs(settings.allow_invalid_certs) + .build() + .map_err(map_reqwest)?; + + Ok(Self { + http, + base_url, + username: settings.username.trim().to_string(), + secret: secret.to_string(), + use_api_key: settings.use_api_key, + api_minor: 0, + }) + } + + /// Create a client, authenticate it and read its WebAPI version. + pub async fn connect(settings: &QbSettings, secret: &str) -> Result { + let mut client = Self::new(settings, secret)?; + if !client.use_api_key { + client.login().await?; + } + let version = client.get_text("/api/v2/app/webapiVersion").await?; + client.api_minor = version + .trim() + .split('.') + .nth(1) + .and_then(|minor| minor.parse().ok()) + .unwrap_or(0); + Ok(client) + } + + fn url(&self, path: &str) -> String { + format!("{}{}", self.base_url, path) + } + + fn decorate(&self, request: RequestBuilder) -> RequestBuilder { + let request = request + .header(REFERER, &self.base_url) + .header(ORIGIN, &self.base_url); + if self.use_api_key { + request.bearer_auth(&self.secret) + } else { + request + } + } + + async fn send(&self, build: F) -> Result + where + F: Fn() -> RequestBuilder, + { + let first = self.decorate(build()).send().await.map_err(map_reqwest)?; + + // The WebUI session can expire while the app is open. Re-login once + // and repeat the request instead of surfacing a spurious auth error. + if matches!(first.status().as_u16(), 401 | 403) && !self.use_api_key { + drop(first); + self.login().await?; + return self.decorate(build()).send().await.map_err(map_reqwest); + } + + Ok(first) + } + + async fn login(&self) -> Result<(), QbError> { + let response = self + .http + .post(self.url("/api/v2/auth/login")) + .header(REFERER, &self.base_url) + .header(ORIGIN, &self.base_url) + .form(&[ + ("username", self.username.as_str()), + ("password", self.secret.as_str()), + ]) + .send() + .await + .map_err(map_reqwest)?; + + let status = response.status(); + match status.as_u16() { + 200 => { + let body = response.text().await.unwrap_or_default(); + if body.trim().eq_ignore_ascii_case("Fails.") { + Err(QbError::with_status( + "auth", + "Неверный логин или пароль qBittorrent", + 200, + )) + } else { + Ok(()) + } + } + 204 => Ok(()), + 401 => Err(QbError::with_status( + "auth", + "Неверный логин или пароль qBittorrent", + 401, + )), + 403 => Err(QbError::with_status( + "banned", + "qBittorrent заблокировал вход с этого IP. Подождите и попробуйте снова.", + 403, + )), + _ => Err(http_error(status)), + } + } + + async fn get_text(&self, path: &str) -> Result { + let url = self.url(path); + let response = self.send(|| self.http.get(&url)).await?; + let status = response.status(); + if !status.is_success() { + return Err(http_error(status)); + } + response.text().await.map_err(map_reqwest) + } + + async fn get_json(&self, path: &str) -> Result + where + T: serde::de::DeserializeOwned, + { + let text = self.get_text(path).await?; + serde_json::from_str(&text) + .map_err(|err| QbError::new("http", format!("Некорректный ответ qBittorrent: {err}"))) + } + + async fn post_form(&self, path: &str, form: Vec<(String, String)>) -> Result<(), QbError> { + let url = self.url(path); + let response = self + .send(|| self.http.post(&url).form(&form)) + .await + .map_err(|err| err)?; + let status = response.status(); + if status.is_success() { + Ok(()) + } else { + Err(http_error(status)) + } + } + + pub async fn connection_info(&self) -> Result { + let app_version = self.get_text("/api/v2/app/version").await?; + let api_version = self.get_text("/api/v2/app/webapiVersion").await?; + let default_save_path = self.get_text("/api/v2/app/defaultSavePath").await?; + + Ok(QbConnectionInfo { + app_version: app_version.trim().to_string(), + api_version: api_version.trim().to_string(), + default_save_path: default_save_path.trim().to_string(), + }) + } + + pub async fn categories(&self) -> Result, QbError> { + let categories: HashMap = + self.get_json("/api/v2/torrents/categories").await?; + + let mut list: Vec = categories + .into_iter() + .map(|(name, mut category)| { + if category.name.is_empty() { + category.name = name; + } + category + }) + .collect(); + list.sort_by_key(|category| category.name.to_lowercase()); + Ok(list) + } + + pub async fn add_torrent(&self, input: AddTorrentInput) -> Result { + let url = self.url("/api/v2/torrents/add"); + let magnet = input.magnet.clone(); + let file_name = input.file_name.clone(); + let file_bytes = input.file_bytes.clone(); + let category = input.category.clone(); + let paused = input.paused; + let auto_tmm = input.auto_tmm; + + // Build the multipart body on every attempt: a Form cannot be cloned, + // and send() may retry once after re-login. + let build_form = || { + let mut form = Form::new() + // qBittorrent 4.x spells this `paused`, 5.x `stopped`; both + // ignore the other key, so sending both keeps every version. + .text("paused", if paused { "true" } else { "false" }) + .text("stopped", if paused { "true" } else { "false" }) + .text("autoTMM", if auto_tmm { "true" } else { "false" }); + + if let Some(category) = category.as_ref().filter(|value| !value.is_empty()) { + form = form.text("category", category.clone()); + } + if let Some(magnet) = magnet.as_ref().filter(|value| !value.is_empty()) { + form = form.text("urls", magnet.clone()); + } + if let (Some(name), Some(bytes)) = (file_name.as_ref(), file_bytes.as_ref()) { + let part = Part::bytes(bytes.clone()) + .file_name(name.clone()) + .mime_str("application/x-bittorrent") + .unwrap_or_else(|_| Part::bytes(bytes.clone())); + form = form.part("torrents", part); + } + form + }; + + let response = self + .decorate( + self.http + .post(&url) + .timeout(UPLOAD_TIMEOUT) + .multipart(build_form()), + ) + .send() + .await + .map_err(map_reqwest)?; + + if matches!(response.status().as_u16(), 401 | 403) && !self.use_api_key { + self.login().await?; + let retry = self + .decorate( + self.http + .post(&url) + .timeout(UPLOAD_TIMEOUT) + .multipart(build_form()), + ) + .send() + .await + .map_err(map_reqwest)?; + return parse_add_response(retry).await; + } + + parse_add_response(response).await + } + + pub async fn stop(&self, hashes: &[String]) -> Result<(), QbError> { + self.control(hashes, true).await + } + + pub async fn start(&self, hashes: &[String]) -> Result<(), QbError> { + self.control(hashes, false).await + } + + async fn control(&self, hashes: &[String], stop: bool) -> Result<(), QbError> { + let action = if stop { "stop" } else { "start" }; + let fallback = if stop { "pause" } else { "resume" }; + let form = vec![("hashes".to_string(), join_hashes(hashes))]; + + let result = self + .post_form(&format!("/api/v2/torrents/{action}"), form.clone()) + .await; + + match result { + Ok(()) => Ok(()), + // qBittorrent 5.0 renamed pause/resume to stop/start (WebAPI + // 2.11). If the server is older than reported, fall back once. + Err(err) if err.status == Some(404) => { + self.post_form(&format!("/api/v2/torrents/{fallback}"), form) + .await + } + Err(err) => Err(err), + } + } + + pub async fn delete(&self, hashes: &[String], delete_files: bool) -> Result<(), QbError> { + let form = vec![ + ("hashes".to_string(), join_hashes(hashes)), + ( + "deleteFiles".to_string(), + if delete_files { "true" } else { "false" }.to_string(), + ), + ]; + self.post_form("/api/v2/torrents/delete", form).await + } + + pub async fn set_category(&self, hashes: &[String], category: &str) -> Result<(), QbError> { + let form = vec![ + ("hashes".to_string(), join_hashes(hashes)), + ("category".to_string(), category.to_string()), + ]; + self.post_form("/api/v2/torrents/setCategory", form).await + } + + pub async fn sync(&self, rid: i64) -> Result { + self.get_json(&format!("/api/v2/sync/maindata?rid={rid}")) + .await + } + + /// Read a local `.torrent` file for upload. + pub fn read_torrent_file(path: &str) -> Result<(String, Vec), QbError> { + let path = Path::new(path); + let name = path + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or("torrent.torrent") + .to_string(); + let metadata = std::fs::metadata(path) + .map_err(|err| QbError::new("torrent", format!("Не удалось открыть файл: {err}")))?; + if metadata.len() > 10 * 1024 * 1024 { + return Err(QbError::new( + "torrent", + "Файл торрента больше 10 МБ — это не похоже на обычный .torrent", + )); + } + let bytes = std::fs::read(path) + .map_err(|err| QbError::new("torrent", format!("Не удалось прочитать файл: {err}")))?; + Ok((name, bytes)) + } +} + +async fn parse_add_response(response: Response) -> Result { + let status = response.status(); + let text = response.text().await.unwrap_or_default(); + let trimmed = text.trim(); + + if status == StatusCode::UNSUPPORTED_MEDIA_TYPE { + return Ok(QbAddResult::new( + "invalid", + Vec::new(), + Some("qBittorrent не принял файл: это не корректный .torrent".to_string()), + )); + } + if status == StatusCode::CONFLICT { + return Ok(QbAddResult::new( + "duplicate", + Vec::new(), + Some("qBittorrent не добавил раздачу: она уже есть или отклонена".to_string()), + )); + } + if !status.is_success() { + return Err(http_error(status)); + } + + if trimmed.starts_with('{') { + if let Ok(parsed) = serde_json::from_str::(trimmed) { + let hashes = parsed.added_torrent_ids.clone(); + if parsed.success_count > 0 { + return Ok(QbAddResult::new("added", hashes, None)); + } + if parsed.pending_count > 0 { + return Ok(QbAddResult::new( + "pending", + hashes, + Some("qBittorrent обрабатывает раздачу".to_string()), + )); + } + let message = if parsed.failure_count > 0 { + format!( + "qBittorrent не добавил раздачу (ошибок: {})", + parsed.failure_count + ) + } else { + "qBittorrent не добавил раздачу: она уже есть или отклонена".to_string() + }; + return Ok(QbAddResult::new("duplicate", hashes, Some(message))); + } + } + + if trimmed.eq_ignore_ascii_case("Fails.") { + return Ok(QbAddResult::new( + "duplicate", + Vec::new(), + Some("qBittorrent не добавил раздачу: она уже есть или отклонена".to_string()), + )); + } + + Ok(QbAddResult::new("added", Vec::new(), None)) +} diff --git a/src-tauri/src/qbittorrent/mod.rs b/src-tauri/src/qbittorrent/mod.rs new file mode 100644 index 0000000..7e7dc3e --- /dev/null +++ b/src-tauri/src/qbittorrent/mod.rs @@ -0,0 +1,486 @@ +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::{Mutex, MutexGuard}; + +use serde_json::{Map, Value}; +use tauri::{AppHandle, Manager, State}; + +pub mod client; +pub mod types; + +use client::{normalize_base_url, AddTorrentInput, QbClient}; +use types::{ + QbAddRequest, QbAddResult, QbCategory, QbConnectionInfo, QbError, QbServerState, + QbServerStateRaw, QbSettings, QbSnapshot, QbTorrent, QbTorrentRaw, +}; + +const KEYRING_SERVICE: &str = "blink-qbittorrent"; +const KEYRING_USER: &str = "default"; +const SETTINGS_FILE: &str = "qbittorrent.json"; + +struct Inner { + settings: QbSettings, + /// Password or API key, kept in memory for this run even when the user + /// chose not to write it to the OS keyring. + secret: Option, + secret_saved: bool, + client: Option, + torrents: HashMap, + server_state: Value, + rid: i64, + synced: bool, +} + +impl Default for Inner { + fn default() -> Self { + Self { + settings: QbSettings::default(), + secret: None, + secret_saved: false, + client: None, + torrents: HashMap::new(), + server_state: Value::Null, + rid: 0, + synced: false, + } + } +} + +pub struct QbState { + inner: Mutex, +} + +impl QbState { + pub fn load(app: &AppHandle) -> Self { + let settings = read_settings(app); + let stored_secret = if settings.remember_secret { + keyring_read() + } else { + None + }; + + Self { + inner: Mutex::new(Inner { + settings, + secret_saved: stored_secret.is_some(), + secret: stored_secret, + ..Inner::default() + }), + } + } + + fn lock(&self) -> Result, QbError> { + self.inner + .lock() + .map_err(|_| QbError::new("internal", "Внутреннее состояние qBittorrent повреждено")) + } +} + +fn keyring_entry() -> Result { + keyring::Entry::new(KEYRING_SERVICE, KEYRING_USER).map_err(|err| { + QbError::new( + "config", + format!("Системное хранилище секретов недоступно: {err}"), + ) + }) +} + +fn keyring_read() -> Option { + keyring_entry() + .ok() + .and_then(|entry| entry.get_password().ok()) + .filter(|secret| !secret.is_empty()) +} + +fn keyring_write(secret: &str) -> bool { + keyring_entry() + .and_then(|entry| { + entry.set_password(secret).map_err(|err| { + QbError::new("config", format!("Не удалось сохранить секрет: {err}")) + }) + }) + .is_ok() +} + +fn keyring_delete() { + if let Ok(entry) = keyring_entry() { + let _ = entry.delete_credential(); + } +} + +fn settings_path(app: &AppHandle) -> Result { + let directory = app.path().app_config_dir().map_err(|err| { + QbError::new( + "config", + format!("Не удалось определить каталог настроек: {err}"), + ) + })?; + std::fs::create_dir_all(&directory).map_err(|err| { + QbError::new( + "config", + format!("Не удалось создать каталог настроек: {err}"), + ) + })?; + Ok(directory.join(SETTINGS_FILE)) +} + +fn read_settings(app: &AppHandle) -> QbSettings { + let Ok(path) = settings_path(app) else { + return QbSettings::default(); + }; + let Ok(text) = std::fs::read_to_string(path) else { + return QbSettings::default(); + }; + serde_json::from_str(&text).unwrap_or_default() +} + +fn write_settings(app: &AppHandle, settings: &QbSettings) -> Result<(), QbError> { + let path = settings_path(app)?; + let mut persisted = settings.clone(); + persisted.secret_saved = false; + persisted.has_secret = false; + let json = serde_json::to_string_pretty(&persisted) + .map_err(|err| QbError::new("config", format!("Не удалось сохранить настройки: {err}")))?; + std::fs::write(path, json) + .map_err(|err| QbError::new("config", format!("Не удалось сохранить настройки: {err}"))) +} + +fn public_settings(inner: &Inner) -> QbSettings { + let mut settings = inner.settings.clone(); + settings.secret_saved = inner.secret_saved; + settings.has_secret = inner.secret.is_some(); + settings +} + +fn reset_session(inner: &mut Inner) { + inner.client = None; + inner.torrents.clear(); + inner.server_state = Value::Null; + inner.rid = 0; + inner.synced = false; +} + +fn merge_json(base: &mut Value, patch: &Value) { + if let (Some(base), Some(patch)) = (base.as_object_mut(), patch.as_object()) { + for (key, value) in patch { + base.insert(key.clone(), value.clone()); + } + } +} + +fn apply_sync(inner: &mut Inner, data: &Value) { + let full_update = data + .get("full_update") + .and_then(Value::as_bool) + .unwrap_or(false); + if full_update { + inner.torrents.clear(); + inner.server_state = Value::Null; + } + + if let Some(torrents) = data.get("torrents").and_then(Value::as_object) { + for (hash, patch) in torrents { + if !patch.is_object() { + continue; + } + let entry = inner + .torrents + .entry(hash.clone()) + .or_insert_with(|| Value::Object(Map::new())); + merge_json(entry, patch); + } + } + + if let Some(removed) = data.get("torrents_removed").and_then(Value::as_array) { + for hash in removed { + if let Some(hash) = hash.as_str() { + inner.torrents.remove(hash); + } + } + } + + if let Some(server_state) = data.get("server_state") { + if server_state.is_object() { + if inner.server_state.is_null() { + inner.server_state = Value::Object(Map::new()); + } + merge_json(&mut inner.server_state, server_state); + } + } + + if let Some(rid) = data.get("rid").and_then(Value::as_i64) { + inner.rid = rid; + } + inner.synced = true; +} + +fn snapshot(inner: &Inner) -> QbSnapshot { + let mut torrents: Vec = inner + .torrents + .iter() + .filter(|(_, value)| value.is_object()) + .map(|(hash, value)| QbTorrent::from(QbTorrentRaw::from_value(value, hash))) + .collect(); + // Newest first; the UI groups by state on top of that. + torrents.sort_by(|left, right| right.added_on.cmp(&left.added_on)); + + let server_state = QbServerState::from(QbServerStateRaw::from_value(&inner.server_state)); + QbSnapshot { + torrents, + server_state, + synced: inner.synced, + } +} + +async fn client_and_settings(state: &QbState) -> Result<(QbClient, QbSettings), QbError> { + let (settings, secret, cached) = { + let inner = state.lock()?; + ( + inner.settings.clone(), + inner.secret.clone(), + inner.client.clone(), + ) + }; + + if let Some(client) = cached { + return Ok((client, settings)); + } + + let secret = secret.ok_or_else(|| { + QbError::new( + "auth", + "Пароль qBittorrent не задан. Откройте «Настройки → Загрузки».", + ) + })?; + + let client = QbClient::connect(&settings, &secret).await?; + { + let mut inner = state.lock()?; + // Another command may have connected while this one awaited. + if inner.client.is_none() { + inner.client = Some(client.clone()); + } + } + Ok((client, settings)) +} + +#[tauri::command] +pub fn qb_get_settings(state: State<'_, QbState>) -> Result { + let inner = state.lock()?; + Ok(public_settings(&inner)) +} + +#[tauri::command] +pub fn qb_save_settings( + app: AppHandle, + state: State<'_, QbState>, + mut settings: QbSettings, + secret: Option, +) -> Result { + settings.base_url = normalize_base_url(&settings.base_url)?; + settings.username = settings.username.trim().to_string(); + settings.poll_interval_ms = settings.poll_interval_ms.clamp(1000, 60_000); + settings.default_category = settings.default_category.trim().to_string(); + + let new_secret = secret.and_then(|value| { + let value = value.trim().to_string(); + if value.is_empty() { + None + } else { + Some(value) + } + }); + let secret_changed = new_secret.is_some(); + + let mut inner = state.lock()?; + if let Some(secret) = new_secret { + inner.secret = Some(secret); + } + + if settings.remember_secret { + inner.secret_saved = inner.secret.as_deref().map(keyring_write).unwrap_or(false); + } else { + keyring_delete(); + inner.secret_saved = false; + } + + let connection_changed = inner.settings.base_url != settings.base_url + || inner.settings.username != settings.username + || inner.settings.use_api_key != settings.use_api_key + || inner.settings.allow_invalid_certs != settings.allow_invalid_certs; + + inner.settings = settings.clone(); + if connection_changed || secret_changed { + reset_session(&mut inner); + } + + let public = public_settings(&inner); + write_settings(&app, &settings)?; + Ok(public) +} + +#[tauri::command] +pub fn qb_forget_secret(app: AppHandle, state: State<'_, QbState>) -> Result { + let mut inner = state.lock()?; + keyring_delete(); + inner.secret = None; + inner.secret_saved = false; + reset_session(&mut inner); + + let public = public_settings(&inner); + write_settings(&app, &inner.settings)?; + Ok(public) +} + +#[tauri::command] +pub async fn qb_test_connection( + state: State<'_, QbState>, + mut settings: QbSettings, + secret: Option, +) -> Result { + settings.base_url = normalize_base_url(&settings.base_url)?; + + let provided = secret.and_then(|value| { + let value = value.trim().to_string(); + if value.is_empty() { + None + } else { + Some(value) + } + }); + let secret = match provided { + Some(secret) => secret, + None => state.lock()?.secret.clone().ok_or_else(|| { + QbError::new( + "auth", + "Введите пароль qBittorrent (или API-ключ), чтобы проверить соединение", + ) + })?, + }; + + let client = QbClient::connect(&settings, &secret).await?; + client.connection_info().await +} + +#[tauri::command] +pub async fn qb_categories(state: State<'_, QbState>) -> Result, QbError> { + let (client, _settings) = client_and_settings(&state).await?; + client.categories().await +} + +#[tauri::command] +pub async fn qb_add_torrent( + state: State<'_, QbState>, + request: QbAddRequest, +) -> Result { + let magnet = request + .magnet + .map(|value| value.trim().to_string()) + .filter(|value| !value.is_empty()); + let file_path = request + .file_path + .map(|value| value.trim().to_string()) + .filter(|value| !value.is_empty()); + + if magnet.is_some() && file_path.is_some() { + return Err(QbError::config( + "Выберите что-то одно: magnet-ссылку или .torrent файл", + )); + } + if magnet.is_none() && file_path.is_none() { + return Err(QbError::config( + "Вставьте magnet-ссылку или выберите .torrent", + )); + } + if let Some(magnet) = magnet.as_deref() { + if !magnet.starts_with("magnet:?") { + return Err(QbError::config("Ссылка не похожа на magnet-ссылку")); + } + } + + let (file_name, file_bytes) = match file_path.as_deref() { + Some(path) => { + let (name, bytes) = QbClient::read_torrent_file(path)?; + (Some(name), Some(bytes)) + } + None => (None, None), + }; + + let (client, settings) = client_and_settings(&state).await?; + let category = request + .category + .map(|value| value.trim().to_string()) + .filter(|value| !value.is_empty()) + .or_else(|| { + let default = settings.default_category.trim().to_string(); + if default.is_empty() { + None + } else { + Some(default) + } + }); + + let result = client + .add_torrent(AddTorrentInput { + magnet, + file_name, + file_bytes, + category, + paused: request.paused.unwrap_or(settings.add_paused), + auto_tmm: request.auto_tmm.unwrap_or(settings.auto_tmm), + }) + .await?; + + // The torrent list is now stale; the next poll would receive an empty diff + // if we kept the old rid. Force a full update. + if result.status == "added" || result.status == "pending" { + let mut inner = state.lock()?; + inner.rid = 0; + inner.synced = false; + } + + Ok(result) +} + +#[tauri::command] +pub async fn qb_poll(state: State<'_, QbState>) -> Result { + let (client, _settings) = client_and_settings(&state).await?; + let rid = state.lock()?.rid; + let data = client.sync(rid).await?; + + let mut inner = state.lock()?; + apply_sync(&mut inner, &data); + Ok(snapshot(&inner)) +} + +#[tauri::command] +pub async fn qb_pause(state: State<'_, QbState>, hashes: Vec) -> Result<(), QbError> { + let (client, _settings) = client_and_settings(&state).await?; + client.stop(&hashes).await +} + +#[tauri::command] +pub async fn qb_resume(state: State<'_, QbState>, hashes: Vec) -> Result<(), QbError> { + let (client, _settings) = client_and_settings(&state).await?; + client.start(&hashes).await +} + +#[tauri::command] +pub async fn qb_delete( + state: State<'_, QbState>, + hashes: Vec, + delete_files: bool, +) -> Result<(), QbError> { + let (client, _settings) = client_and_settings(&state).await?; + client.delete(&hashes, delete_files).await +} + +#[tauri::command] +pub async fn qb_set_category( + state: State<'_, QbState>, + hashes: Vec, + category: String, +) -> Result<(), QbError> { + let (client, _settings) = client_and_settings(&state).await?; + client.set_category(&hashes, category.trim()).await +} diff --git a/src-tauri/src/qbittorrent/types.rs b/src-tauri/src/qbittorrent/types.rs new file mode 100644 index 0000000..c7cf3f1 --- /dev/null +++ b/src-tauri/src/qbittorrent/types.rs @@ -0,0 +1,369 @@ +use serde::{Deserialize, Serialize}; + +/// qBittorrent connection settings. +/// +/// Stored as `qbittorrent.json` in the app config directory. The password (or +/// API key) is never part of this struct: it lives in the OS secret store and +/// only its presence is reported back to the UI. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct QbSettings { + pub base_url: String, + pub username: String, + /// `true` when the secret is a qBittorrent API key (WebAPI 2.17+) instead + /// of the WebUI password. + pub use_api_key: bool, + /// Persist the secret in the OS keyring. + pub remember_secret: bool, + pub default_category: String, + /// Pass `autoTMM=true` when adding a torrent, so the category save path is + /// honoured. + pub auto_tmm: bool, + pub add_paused: bool, + pub allow_invalid_certs: bool, + pub refresh_jellyfin: bool, + pub notify_on_complete: bool, + pub poll_interval_ms: u64, + /// Read-only flags for the UI; recomputed on every load/save. + #[serde(default)] + pub secret_saved: bool, + #[serde(default)] + pub has_secret: bool, +} + +impl Default for QbSettings { + fn default() -> Self { + Self { + base_url: "http://127.0.0.1:8080".to_string(), + username: "admin".to_string(), + use_api_key: false, + remember_secret: false, + default_category: String::new(), + auto_tmm: true, + add_paused: false, + allow_invalid_certs: false, + refresh_jellyfin: false, + notify_on_complete: true, + poll_interval_ms: 2000, + secret_saved: false, + has_secret: false, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase", default)] +pub struct QbCategory { + pub name: String, + pub save_path: String, + pub download_path: Option, +} + +#[derive(Debug, Clone, Default)] +pub struct QbTorrentRaw { + pub hash: String, + pub name: String, + pub category: String, + pub size: i64, + pub completed: i64, + pub downloaded: i64, + pub progress: f64, + pub dlspeed: i64, + pub upspeed: i64, + pub eta: i64, + pub state: String, + pub save_path: String, + pub content_path: String, + pub added_on: i64, + pub completion_on: i64, + pub ratio: f64, + pub num_seeds: i64, + pub num_leechs: i64, + pub error: Option, + pub tags: String, + pub seeding_time: i64, + pub time_active: i64, + pub amount_left: i64, + pub tracker: String, +} + +impl QbTorrentRaw { + /// `hash` is the key of the `sync/maindata` torrents map; qBittorrent does + /// not repeat it inside the value. + pub fn from_value(value: &serde_json::Value, hash: &str) -> Self { + let text = |key: &str| -> String { + value + .get(key) + .and_then(serde_json::Value::as_str) + .unwrap_or_default() + .to_string() + }; + let number = |key: &str| -> i64 { + value + .get(key) + .and_then(serde_json::Value::as_i64) + .unwrap_or_default() + }; + let float = |key: &str| -> f64 { + value + .get(key) + .and_then(serde_json::Value::as_f64) + .unwrap_or_default() + }; + + Self { + hash: hash.to_string(), + name: text("name"), + category: text("category"), + size: number("size"), + completed: number("completed"), + downloaded: number("downloaded"), + progress: float("progress"), + dlspeed: number("dlspeed"), + upspeed: number("upspeed"), + eta: number("eta"), + state: text("state"), + save_path: text("save_path"), + content_path: text("content_path"), + added_on: number("added_on"), + completion_on: number("completion_on"), + ratio: float("ratio"), + num_seeds: number("num_seeds"), + num_leechs: number("num_leechs"), + error: value + .get("error") + .and_then(serde_json::Value::as_str) + .filter(|message| !message.is_empty()) + .map(str::to_string), + tags: text("tags"), + seeding_time: number("seeding_time"), + time_active: number("time_active"), + amount_left: number("amount_left"), + tracker: text("tracker"), + } + } +} + +#[derive(Debug, Clone, Serialize, Default)] +#[serde(rename_all = "camelCase")] +pub struct QbTorrent { + pub hash: String, + pub name: String, + pub category: String, + pub size: i64, + pub completed: i64, + pub downloaded: i64, + pub progress: f64, + pub dlspeed: i64, + pub upspeed: i64, + pub eta: i64, + pub state: String, + pub save_path: String, + pub content_path: String, + pub added_on: i64, + pub completion_on: i64, + pub ratio: f64, + pub num_seeds: i64, + pub num_leechs: i64, + pub error: Option, + pub tags: String, + pub seeding_time: i64, + pub time_active: i64, + pub amount_left: i64, + pub tracker: String, +} + +impl From for QbTorrent { + fn from(raw: QbTorrentRaw) -> Self { + Self { + hash: raw.hash, + name: raw.name, + category: raw.category, + size: raw.size, + completed: raw.completed, + downloaded: raw.downloaded, + progress: raw.progress, + dlspeed: raw.dlspeed, + upspeed: raw.upspeed, + eta: raw.eta, + state: raw.state, + save_path: raw.save_path, + content_path: raw.content_path, + added_on: raw.added_on, + completion_on: raw.completion_on, + ratio: raw.ratio, + num_seeds: raw.num_seeds, + num_leechs: raw.num_leechs, + error: raw.error, + tags: raw.tags, + seeding_time: raw.seeding_time, + time_active: raw.time_active, + amount_left: raw.amount_left, + tracker: raw.tracker, + } + } +} + +#[derive(Debug, Clone, Default)] +pub struct QbServerStateRaw { + pub dl_info_speed: i64, + pub up_info_speed: i64, + pub dl_info_data: i64, + pub up_info_data: i64, + pub free_space_on_disk: i64, + pub connection_status: String, + pub queueing: bool, + pub dht_nodes: i64, +} + +impl QbServerStateRaw { + pub fn from_value(value: &serde_json::Value) -> Self { + let number = |key: &str| -> i64 { + value + .get(key) + .and_then(serde_json::Value::as_i64) + .unwrap_or_default() + }; + let text = |key: &str| -> String { + value + .get(key) + .and_then(serde_json::Value::as_str) + .unwrap_or_default() + .to_string() + }; + + Self { + dl_info_speed: number("dl_info_speed"), + up_info_speed: number("up_info_speed"), + dl_info_data: number("dl_info_data"), + up_info_data: number("up_info_data"), + free_space_on_disk: number("free_space_on_disk"), + connection_status: text("connection_status"), + queueing: value + .get("queueing") + .and_then(serde_json::Value::as_bool) + .unwrap_or_default(), + dht_nodes: number("dht_nodes"), + } + } +} + +#[derive(Debug, Clone, Serialize, Default)] +#[serde(rename_all = "camelCase")] +pub struct QbServerState { + pub dl_info_speed: i64, + pub up_info_speed: i64, + pub dl_info_data: i64, + pub up_info_data: i64, + pub free_space_on_disk: i64, + pub connection_status: String, + pub queueing: bool, + pub dht_nodes: i64, +} + +impl From for QbServerState { + fn from(raw: QbServerStateRaw) -> Self { + Self { + dl_info_speed: raw.dl_info_speed, + up_info_speed: raw.up_info_speed, + dl_info_data: raw.dl_info_data, + up_info_data: raw.up_info_data, + free_space_on_disk: raw.free_space_on_disk, + connection_status: raw.connection_status, + queueing: raw.queueing, + dht_nodes: raw.dht_nodes, + } + } +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct QbSnapshot { + pub torrents: Vec, + pub server_state: QbServerState, + pub synced: bool, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct QbAddResult { + /// `added`, `pending`, `duplicate` or `invalid`. + pub status: String, + pub added_hashes: Vec, + pub message: Option, +} + +impl QbAddResult { + pub fn new(status: &str, added_hashes: Vec, message: Option) -> Self { + Self { + status: status.to_string(), + added_hashes, + message, + } + } +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct QbConnectionInfo { + pub app_version: String, + pub api_version: String, + pub default_save_path: String, +} + +/// Error returned by every qBittorrent command. +/// +/// `kind` is a stable machine-readable value: +/// `unreachable`, `auth`, `banned`, `tls`, `duplicate`, `torrent`, `http`, +/// `config` or `internal`. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct QbError { + pub kind: String, + pub message: String, + pub status: Option, +} + +impl QbError { + pub fn new(kind: &str, message: impl Into) -> Self { + Self { + kind: kind.to_string(), + message: message.into(), + status: None, + } + } + + pub fn with_status(kind: &str, message: impl Into, status: u16) -> Self { + Self { + kind: kind.to_string(), + message: message.into(), + status: Some(status), + } + } + + pub fn config(message: impl Into) -> Self { + Self::new("config", message) + } +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct QbAddRequest { + pub magnet: Option, + pub file_path: Option, + pub category: Option, + pub paused: Option, + pub auto_tmm: Option, +} + +#[derive(Debug, Deserialize, Default)] +pub struct QbAddResponse { + #[serde(default)] + pub success_count: i64, + #[serde(default)] + pub pending_count: i64, + #[serde(default)] + pub failure_count: i64, + #[serde(default)] + pub added_torrent_ids: Vec, +} diff --git a/src/components/appBar/appBar.scss b/src/components/appBar/appBar.scss index 181065e..bd784c0 100644 --- a/src/components/appBar/appBar.scss +++ b/src/components/appBar/appBar.scss @@ -204,6 +204,7 @@ .appBar-groups, .appBar-cast, .appBar-favorite, + .appBar-downloads, [aria-label="Главная"] { display: none !important; } diff --git a/src/components/appBar/appBar.tsx b/src/components/appBar/appBar.tsx index 42f140a..75054ef 100644 --- a/src/components/appBar/appBar.tsx +++ b/src/components/appBar/appBar.tsx @@ -76,6 +76,7 @@ const AppBarContent = () => { const fallbackTitle = (() => { const path = location.pathname; if (path === "/favorite") return "Избранное"; + if (path === "/downloads") return "Загрузки"; if (path.startsWith("/music/")) return "Музыка"; if (path.startsWith("/player/audio")) return "Сейчас играет"; return ""; @@ -148,6 +149,15 @@ const AppBarContent = () => { search + + navigate({ to: "/downloads" })} + aria-label="Загрузки" + > + download + + navigate({ to: "/remote" })} diff --git a/src/components/appBar/navigationDrawer.tsx b/src/components/appBar/navigationDrawer.tsx index 2d490f8..f64c7e0 100644 --- a/src/components/appBar/navigationDrawer.tsx +++ b/src/components/appBar/navigationDrawer.tsx @@ -99,6 +99,13 @@ export const NavigationDrawer = ({ open, onClose }: NavigationDrawerProps) => { primary="Пульт" onClick={onClose} /> + void; + settings: QbSettings; + onAdded: (result: QbAddResult) => void; + /** Used to preselect the category of a torrent being retried. */ + torrent?: QbTorrent | null; +}; + +type TabValue = "magnet" | "file"; + +export default function AddTorrentDialog({ + open: isOpen, + onClose, + settings, + onAdded, + torrent, +}: Props) { + const [tab, setTab] = useState("magnet"); + const [magnet, setMagnet] = useState(""); + const [filePath, setFilePath] = useState(null); + const [fileName, setFileName] = useState(null); + const [category, setCategory] = useState(settings.defaultCategory ?? ""); + const [paused, setPaused] = useState(settings.addPaused); + const [autoTmm, setAutoTmm] = useState(settings.autoTmm); + + const categories = useQuery(qbCategoriesQueryOptions(isOpen)); + + useEffect(() => { + if (!isOpen) return; + setTab("magnet"); + setMagnet(""); + setFilePath(null); + setFileName(null); + setCategory(torrent?.category || settings.defaultCategory || ""); + setPaused(settings.addPaused); + setAutoTmm(settings.autoTmm); + }, [isOpen, torrent, settings]); + + const pickFile = async () => { + try { + const selected = await open({ + multiple: false, + directory: false, + filters: [{ name: "Torrent", extensions: ["torrent"] }], + }); + if (typeof selected === "string") { + setFilePath(selected); + setFileName(selected.split(/[\\/]/).pop() ?? selected); + } + } catch (error) { + enqueueSnackbar(`Не удалось открыть диалог файла: ${error}`, { + variant: "error", + }); + } + }; + + const add = useMutation({ + mutationFn: () => + qbAddTorrent({ + magnet: tab === "magnet" ? magnet.trim() : null, + filePath: tab === "file" ? filePath : null, + category: category || null, + paused, + autoTmm, + }), + onSuccess: (result) => { + if (result.status === "duplicate") { + enqueueSnackbar( + result.message ?? "Такая раздача уже добавлена в qBittorrent", + { variant: "warning" }, + ); + return; + } + if (result.status === "invalid") { + enqueueSnackbar( + result.message ?? "qBittorrent не принял этот торрент", + { variant: "error" }, + ); + return; + } + enqueueSnackbar( + result.status === "pending" + ? "Раздача добавлена, qBittorrent получает метаданные" + : "Раздача добавлена", + { variant: "success" }, + ); + onAdded(result); + onClose(); + }, + onError: (error) => { + enqueueSnackbar(toQbError(error).message, { variant: "error" }); + }, + }); + + const magnetValid = magnet.trim().startsWith("magnet:?"); + const canSubmit = + !add.isPending && + ((tab === "magnet" && magnetValid) || (tab === "file" && !!filePath)); + + const selectedCategory = categories.data?.find( + (item) => item.name === category, + ); + + return ( + + + + + download + + + Добавить раздачу + + + + + setTab(value)} + variant="fullWidth" + sx={{ mb: 2, minHeight: 40 }} + > + + + + + {tab === "magnet" ? ( + setMagnet(event.target.value)} + error={magnet.length > 0 && !magnetValid} + helperText={ + magnet.length > 0 && !magnetValid + ? "Ссылка должна начинаться с magnet:?" + : "Например, magnet:?xt=urn:btih:…" + } + /> + ) : ( + + + + Файл отправится в qBittorrent как есть; категория и папка + применятся на стороне сервера. + + + )} + + setCategory(event.target.value)} + sx={{ mt: 2 }} + disabled={categories.isLoading} + helperText={ + categories.isError + ? "Не удалось загрузить категории qBittorrent" + : selectedCategory + ? `Папка: ${selectedCategory.savePath || "по умолчанию"}` + : "Без категории — папка qBittorrent по умолчанию" + } + > + Без категории + {(categories.data ?? []).map((item) => ( + + {item.name} + + ))} + + + + setPaused(checked)} + /> + } + label="Добавить на паузе" + /> + setAutoTmm(checked)} + /> + } + label="Автоуправление категорией" + /> + + + + + + + + ); +} diff --git a/src/components/downloads/torrentRow.tsx b/src/components/downloads/torrentRow.tsx new file mode 100644 index 0000000..e7ad141 --- /dev/null +++ b/src/components/downloads/torrentRow.tsx @@ -0,0 +1,139 @@ +import { Chip, IconButton, Tooltip, Typography } from "@mui/material"; +import React from "react"; +import { + formatBytes, + formatEta, + formatPercent, + formatSpeed, + getTorrentState, +} from "@/utils/qbittorrent/format"; +import type { QbTorrent } from "@/utils/qbittorrent/types"; + +type Props = { + torrent: QbTorrent; + busy?: boolean; + onPause: (torrent: QbTorrent) => void; + onResume: (torrent: QbTorrent) => void; + onDelete: (torrent: QbTorrent) => void; +}; + +export default function TorrentRow({ + torrent, + busy, + onPause, + onResume, + onDelete, +}: Props) { + const info = getTorrentState(torrent.state); + const percent = Math.min(100, Math.max(0, torrent.progress * 100)); + const showEta = !info.done && !info.error; + + return ( +
+
+
+ + {torrent.name || "Без названия"} + + +
+ +
+ {torrent.category ? ( + + label + {torrent.category} + + ) : ( + + Без категории + + )} + {formatBytes(torrent.size)} + {torrent.numSeeds > 0 && ( + + ▲ {torrent.numSeeds} + {torrent.numLeeches > 0 && ( + ▼ {torrent.numLeeches} + )} + + )} + {info.done && torrent.ratio > 0 && ( + Рейтинг {torrent.ratio.toFixed(2).replace(".", ",")} + )} +
+ + {torrent.error && ( +
+ error + {torrent.error} +
+ )} + + + +
+ + + + info.paused ? onResume(torrent) : onPause(torrent) + } + > + + {info.paused ? "play_arrow" : "pause"} + + + + + + + onDelete(torrent)} + > + delete + + + +
+
+ ); +} diff --git a/src/routeTree.gen.ts b/src/routeTree.gen.ts index 9a95cc0..62e1554 100644 --- a/src/routeTree.gen.ts +++ b/src/routeTree.gen.ts @@ -11,6 +11,7 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' import { Route as ApiRouteImport } from './routes/_api' +import { Route as ApiDownloadsRouteImport } from './routes/_api/downloads' import { Route as ApiLoginRouteImport } from './routes/_api/login' import { Route as ApiRemoteRouteImport } from './routes/_api/remote' import { Route as ApiSettingsRouteImport } from './routes/_api/settings' @@ -26,6 +27,7 @@ import { Route as ApiPlayerAudioRouteImport } from './routes/_api/player/audio' import { Route as ApiPlayerPhotosRouteImport } from './routes/_api/player/photos' import { Route as ApiSearchIndexRouteImport } from './routes/_api/search/index' import { Route as ApiSettingsAboutRouteImport } from './routes/_api/settings/about' +import { Route as ApiSettingsDownloadsRouteImport } from './routes/_api/settings/downloads' import { Route as ApiSettingsPreferencesRouteImport } from './routes/_api/settings/preferences' import { Route as SetupServerAddRouteImport } from './routes/setup/server.add' import { Route as SetupServerErrorRouteImport } from './routes/setup/server.error' @@ -45,6 +47,11 @@ const ApiRoute = ApiRouteImport.update({ id: '/_api', getParentRoute: () => rootRouteImport, } as any) +const ApiDownloadsRoute = ApiDownloadsRouteImport.update({ + id: '/downloads', + path: '/downloads', + getParentRoute: () => ApiRoute, +} as any) const ApiLoginRoute = ApiLoginRouteImport.update({ id: '/login', path: '/login', @@ -120,6 +127,11 @@ const ApiSettingsAboutRoute = ApiSettingsAboutRouteImport.update({ path: '/about', getParentRoute: () => ApiSettingsRoute, } as any) +const ApiSettingsDownloadsRoute = ApiSettingsDownloadsRouteImport.update({ + id: '/downloads', + path: '/downloads', + getParentRoute: () => ApiSettingsRoute, +} as any) const ApiSettingsPreferencesRoute = ApiSettingsPreferencesRouteImport.update({ id: '/preferences', path: '/preferences', @@ -169,6 +181,7 @@ const ApiSettingsChangeServerIndexRoute = export interface FileRoutesByFullPath { '/': typeof IndexRoute + '/downloads': typeof ApiDownloadsRoute '/login': typeof ApiLoginRouteWithChildren '/remote': typeof ApiRemoteRoute '/settings': typeof ApiSettingsRouteWithChildren @@ -180,6 +193,7 @@ export interface FileRoutesByFullPath { '/player/audio': typeof ApiPlayerAudioRoute '/player/photos': typeof ApiPlayerPhotosRoute '/settings/about': typeof ApiSettingsAboutRoute + '/settings/downloads': typeof ApiSettingsDownloadsRoute '/settings/preferences': typeof ApiSettingsPreferencesRoute '/setup/server/add': typeof SetupServerAddRoute '/setup/server/error': typeof SetupServerErrorRoute @@ -196,6 +210,7 @@ export interface FileRoutesByFullPath { } export interface FileRoutesByTo { '/': typeof IndexRoute + '/downloads': typeof ApiDownloadsRoute '/login': typeof ApiLoginRouteWithChildren '/remote': typeof ApiRemoteRoute '/settings': typeof ApiSettingsRouteWithChildren @@ -207,6 +222,7 @@ export interface FileRoutesByTo { '/player/audio': typeof ApiPlayerAudioRoute '/player/photos': typeof ApiPlayerPhotosRoute '/settings/about': typeof ApiSettingsAboutRoute + '/settings/downloads': typeof ApiSettingsDownloadsRoute '/settings/preferences': typeof ApiSettingsPreferencesRoute '/setup/server/add': typeof SetupServerAddRoute '/setup/server/error': typeof SetupServerErrorRoute @@ -225,6 +241,7 @@ export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute '/_api': typeof ApiRouteWithChildren + '/_api/downloads': typeof ApiDownloadsRoute '/_api/login': typeof ApiLoginRouteWithChildren '/_api/remote': typeof ApiRemoteRoute '/_api/settings': typeof ApiSettingsRouteWithChildren @@ -236,6 +253,7 @@ export interface FileRoutesById { '/_api/player/audio': typeof ApiPlayerAudioRoute '/_api/player/photos': typeof ApiPlayerPhotosRoute '/_api/settings/about': typeof ApiSettingsAboutRoute + '/_api/settings/downloads': typeof ApiSettingsDownloadsRoute '/_api/settings/preferences': typeof ApiSettingsPreferencesRoute '/setup/server/add': typeof SetupServerAddRoute '/setup/server/error': typeof SetupServerErrorRoute @@ -254,6 +272,7 @@ export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath fullPaths: | '/' + | '/downloads' | '/login' | '/remote' | '/settings' @@ -265,6 +284,7 @@ export interface FileRouteTypes { | '/player/audio' | '/player/photos' | '/settings/about' + | '/settings/downloads' | '/settings/preferences' | '/setup/server/add' | '/setup/server/error' @@ -281,6 +301,7 @@ export interface FileRouteTypes { fileRoutesByTo: FileRoutesByTo to: | '/' + | '/downloads' | '/login' | '/remote' | '/settings' @@ -292,6 +313,7 @@ export interface FileRouteTypes { | '/player/audio' | '/player/photos' | '/settings/about' + | '/settings/downloads' | '/settings/preferences' | '/setup/server/add' | '/setup/server/error' @@ -309,6 +331,7 @@ export interface FileRouteTypes { | '__root__' | '/' | '/_api' + | '/_api/downloads' | '/_api/login' | '/_api/remote' | '/_api/settings' @@ -320,6 +343,7 @@ export interface FileRouteTypes { | '/_api/player/audio' | '/_api/player/photos' | '/_api/settings/about' + | '/_api/settings/downloads' | '/_api/settings/preferences' | '/setup/server/add' | '/setup/server/error' @@ -360,6 +384,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiRouteImport parentRoute: typeof rootRouteImport } + '/_api/downloads': { + id: '/_api/downloads' + path: '/downloads' + fullPath: '/downloads' + preLoaderRoute: typeof ApiDownloadsRouteImport + parentRoute: typeof ApiRoute + } '/_api/login': { id: '/_api/login' path: '/login' @@ -465,6 +496,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiSettingsAboutRouteImport parentRoute: typeof ApiSettingsRoute } + '/_api/settings/downloads': { + id: '/_api/settings/downloads' + path: '/downloads' + fullPath: '/settings/downloads' + preLoaderRoute: typeof ApiSettingsDownloadsRouteImport + parentRoute: typeof ApiSettingsRoute + } '/_api/settings/preferences': { id: '/_api/settings/preferences' path: '/preferences' @@ -549,12 +587,14 @@ const ApiLoginRouteWithChildren = ApiLoginRoute._addFileChildren( interface ApiSettingsRouteChildren { ApiSettingsAboutRoute: typeof ApiSettingsAboutRoute + ApiSettingsDownloadsRoute: typeof ApiSettingsDownloadsRoute ApiSettingsPreferencesRoute: typeof ApiSettingsPreferencesRoute ApiSettingsChangeServerIndexRoute: typeof ApiSettingsChangeServerIndexRoute } const ApiSettingsRouteChildren: ApiSettingsRouteChildren = { ApiSettingsAboutRoute: ApiSettingsAboutRoute, + ApiSettingsDownloadsRoute: ApiSettingsDownloadsRoute, ApiSettingsPreferencesRoute: ApiSettingsPreferencesRoute, ApiSettingsChangeServerIndexRoute: ApiSettingsChangeServerIndexRoute, } @@ -564,6 +604,7 @@ const ApiSettingsRouteWithChildren = ApiSettingsRoute._addFileChildren( ) interface ApiRouteChildren { + ApiDownloadsRoute: typeof ApiDownloadsRoute ApiLoginRoute: typeof ApiLoginRouteWithChildren ApiRemoteRoute: typeof ApiRemoteRoute ApiSettingsRoute: typeof ApiSettingsRouteWithChildren @@ -581,6 +622,7 @@ interface ApiRouteChildren { } const ApiRouteChildren: ApiRouteChildren = { + ApiDownloadsRoute: ApiDownloadsRoute, ApiLoginRoute: ApiLoginRouteWithChildren, ApiRemoteRoute: ApiRemoteRoute, ApiSettingsRoute: ApiSettingsRouteWithChildren, diff --git a/src/routes/_api/downloads.scss b/src/routes/_api/downloads.scss new file mode 100644 index 0000000..87309e3 --- /dev/null +++ b/src/routes/_api/downloads.scss @@ -0,0 +1,494 @@ +@use "../../styles/variables.scss" as *; + +.downloads-page { + max-width: 1180px; + margin: 0 auto; + padding-bottom: 4rem; + box-sizing: border-box; + + &--centered { + display: flex; + align-items: center; + justify-content: center; + min-height: 60vh; + } +} + +.downloads-header { + display: flex; + align-items: flex-end; + justify-content: space-between; + gap: 1rem; + flex-wrap: wrap; + + .downloads-heading { + display: flex; + flex-direction: column; + gap: 0.15rem; + + h4 { + font-size: clamp(1.8rem, 3vw, 2.4rem); + font-weight: 700; + letter-spacing: -0.02em; + line-height: 1.1; + margin: 0; + } + } + + .downloads-subtitle { + color: rgb(255 255 255 / 0.5); + font-size: 0.85rem; + } + + .downloads-actions { + display: flex; + align-items: center; + gap: 0.75rem; + } +} + +.downloads-summary { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 0.9rem; + margin: 1.4rem 0 1rem; +} + +.downloads-stat { + display: flex; + align-items: center; + gap: 0.85rem; + padding: 0.95rem 1.1rem; + border-radius: 18px; + background: rgb(255 255 255 / 0.04); + border: 1px solid rgb(255 255 255 / 0.07); + min-width: 0; + + > .material-symbols-rounded { + font-size: 1.6rem; + color: $clr-accent-default; + opacity: 0.9; + flex: 0 0 auto; + } + + &-value { + font-family: var(--font-mono); + font-size: 1rem; + font-weight: 600; + color: rgb(255 255 255 / 0.9); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + &-label { + font-size: 0.72rem; + color: rgb(255 255 255 / 0.45); + margin-top: 0.1rem; + } +} + +.downloads-banner { + display: flex; + align-items: center; + gap: 0.7rem; + padding: 0.65rem 0.9rem; + border-radius: 14px; + background: rgb(255 160 80 / 0.1); + border: 1px solid rgb(255 160 80 / 0.25); + color: #ffc08a; + font-size: 0.84rem; + margin-bottom: 0.9rem; + + .material-symbols-rounded { + font-size: 1.15rem; + } + + span:nth-child(2) { + flex: 1; + min-width: 0; + } +} + +.downloads-filters { + display: flex; + gap: 0.5rem; + overflow-x: auto; + padding: 0.25rem 0 1rem; + scrollbar-width: none; + + &::-webkit-scrollbar { + display: none; + } +} + +.downloads-filter { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.5rem 1rem; + border-radius: 999px; + border: 1px solid rgb(255 255 255 / 0.1); + background: transparent; + color: rgb(255 255 255 / 0.62); + font: inherit; + font-size: 0.86rem; + font-weight: 500; + white-space: nowrap; + cursor: pointer; + transition: + background-color 0.18s ease, + border-color 0.18s ease, + color 0.18s ease; + + &:hover { + background: rgb(255 255 255 / 0.06); + color: rgb(255 255 255 / 0.85); + } + + &--active { + background: rgba($clr-accent-default, 0.16); + border-color: rgba($clr-accent-default, 0.45); + color: #fff; + } +} + +.downloads-filter-count { + min-width: 1.5em; + padding: 0.05em 0.4em; + border-radius: 999px; + background: rgb(255 255 255 / 0.08); + font-size: 0.7rem; + font-family: var(--font-mono); + text-align: center; +} + +.downloads-list { + display: flex; + flex-direction: column; + gap: 0.75rem; +} + +.qb-row { + display: flex; + align-items: stretch; + gap: 1rem; + padding: 1rem 1.1rem; + border-radius: 18px; + background: rgb(255 255 255 / 0.04); + border: 1px solid rgb(255 255 255 / 0.07); + transition: + background-color 0.18s ease, + border-color 0.18s ease; + + &:hover { + background: rgb(255 255 255 / 0.06); + } + + &--error { + border-color: rgb(255 110 110 / 0.28); + background: rgb(255 90 90 / 0.05); + } + + &-body { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: 0.45rem; + } + + &-head { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 0.75rem; + } + + &-name { + font-size: 0.96rem !important; + font-weight: 600 !important; + line-height: 1.35 !important; + color: rgb(255 255 255 / 0.92) !important; + overflow: hidden; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + word-break: break-word; + } + + &-meta { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 0.3rem 0.9rem; + font-size: 0.76rem; + color: rgb(255 255 255 / 0.5); + } + + &-category { + display: inline-flex; + align-items: center; + gap: 0.25rem; + color: rgb(255 255 255 / 0.72); + + .material-symbols-rounded { + font-size: 0.95rem; + opacity: 0.55; + } + + &--muted { + opacity: 0.5; + } + } + + &-peers { + display: inline-flex; + gap: 0.5rem; + font-family: var(--font-mono); + } + + &-error { + display: flex; + align-items: center; + gap: 0.35rem; + font-size: 0.77rem; + color: #ff8a8a; + + .material-symbols-rounded { + font-size: 1rem; + } + } + + &-progress { + height: 6px; + border-radius: 999px; + background: rgb(255 255 255 / 0.08); + overflow: hidden; + } + + &-progress-fill { + height: 100%; + border-radius: inherit; + background: linear-gradient(90deg, $clr-accent-default, #8a7dff); + transition: width 0.5s ease; + } + + &--seeding &-progress-fill { + background: linear-gradient(90deg, #3fbf85, #7ee2a8); + } + + &--error &-progress-fill { + background: #ff6b6b; + } + + &--paused &-progress-fill { + background: rgb(255 255 255 / 0.35); + } + + &-stats { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 0.3rem 0.9rem; + font-family: var(--font-mono); + font-size: 0.73rem; + color: rgb(255 255 255 / 0.5); + } + + &-percent { + color: rgb(255 255 255 / 0.88); + font-weight: 600; + } + + &-speed { + color: #7ee2a8; + + &--up { + color: #9bb7ff; + } + } + + &-eta { + color: rgb(255 255 255 / 0.42); + } + + &-actions { + display: flex; + align-items: center; + gap: 0.1rem; + align-self: center; + + .MuiIconButton-root { + color: rgb(255 255 255 / 0.55); + + &:hover { + color: #fff; + background: rgb(255 255 255 / 0.08); + } + } + } +} + +.qb-state { + height: 22px !important; + font-size: 0.7rem !important; + font-weight: 600 !important; + background: rgb(255 255 255 / 0.08) !important; + color: rgb(255 255 255 / 0.78) !important; + flex: 0 0 auto; + + &--downloading { + background: rgba($clr-accent-default, 0.16) !important; + color: #ffb3d1 !important; + } + + &--seeding { + background: rgb(80 210 150 / 0.14) !important; + color: #7ee2a8 !important; + } + + &--paused { + background: rgb(255 255 255 / 0.07) !important; + color: rgb(255 255 255 / 0.55) !important; + } + + &--error { + background: rgb(255 90 90 / 0.16) !important; + color: #ff8a8a !important; + } +} + +.qb-seed { + color: #7ee2a8; +} + +.qb-leech { + color: #ffb27a; +} + +.downloads-state { + display: flex; + flex-direction: column; + align-items: center; + text-align: center; + gap: 0.9rem; + padding: clamp(2rem, 8vh, 5rem) 1.5rem; + margin-top: 1.5rem; + border-radius: 24px; + border: 1px dashed rgb(255 255 255 / 0.12); + background: rgb(255 255 255 / 0.025); + + &-icon { + font-size: 3rem !important; + color: $clr-accent-default; + opacity: 0.9; + } + + &-text { + max-width: 46ch; + color: rgb(255 255 255 / 0.58); + font-size: 0.88rem; + } + + &--small { + padding: 2.5rem 1.5rem; + margin-top: 1rem; + } + + &--error &-icon { + color: #ff8a8a; + } +} + +.downloads-delete-name { + font-weight: 600 !important; + margin-bottom: 0.75rem !important; + word-break: break-word; +} + +.downloads-settings-result { + display: flex; + align-items: flex-start; + gap: 0.75rem; + padding: 0.9rem 1rem; + border-radius: 14px; + background: rgb(80 210 150 / 0.08); + border: 1px solid rgb(80 210 150 / 0.22); + font-size: 0.86rem; + line-height: 1.5; + + .material-symbols-rounded { + color: #7ee2a8; + font-size: 1.2rem; + } + + &--error { + background: rgb(255 90 90 / 0.08); + border-color: rgb(255 90 90 / 0.25); + + .material-symbols-rounded { + color: #ff8a8a; + } + } +} + +@media (max-width: 900px) { + .downloads-summary { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + .downloads-stat:last-child { + grid-column: 1 / -1; + } +} + +@media (max-width: 640px) { + .downloads-page { + padding-bottom: 6.5rem; + } + + .downloads-header { + align-items: flex-start; + + .downloads-actions { + width: 100%; + justify-content: flex-end; + } + } + + .downloads-summary { + grid-template-columns: 1fr; + gap: 0.6rem; + margin-top: 1rem; + } + + .downloads-stat:last-child { + grid-column: auto; + } + + .qb-row { + padding: 0.85rem; + gap: 0.5rem; + + &-head { + flex-direction: column; + gap: 0.35rem; + } + + &-stats { + font-size: 0.7rem; + gap: 0.25rem 0.65rem; + } + + &-actions { + flex-direction: column; + align-self: flex-start; + } + } + + .downloads-state { + padding: 2.25rem 1rem; + margin-top: 1rem; + } +} diff --git a/src/routes/_api/downloads.tsx b/src/routes/_api/downloads.tsx new file mode 100644 index 0000000..71454dc --- /dev/null +++ b/src/routes/_api/downloads.tsx @@ -0,0 +1,456 @@ +import { getLibraryApi } from "@jellyfin/sdk/lib/utils/api/library-api"; +import { + Button, + Checkbox, + CircularProgress, + Dialog, + DialogActions, + DialogContent, + DialogTitle, + FormControlLabel, + IconButton, + Stack, + Tooltip, + Typography, +} from "@mui/material"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { createFileRoute, useNavigate } from "@tanstack/react-router"; +import { + isPermissionGranted, + requestPermission, + sendNotification, +} from "@tauri-apps/plugin-notification"; +import { enqueueSnackbar } from "notistack"; +import React, { useEffect, useMemo, useRef, useState } from "react"; +import AddTorrentDialog from "@/components/downloads/addTorrentDialog"; +import TorrentRow from "@/components/downloads/torrentRow"; +import { + qbDelete, + qbPause, + qbResume, + qbSettingsQueryOptions, + qbSnapshotQueryOptions, + toQbError, +} from "@/utils/qbittorrent"; +import { + compareTorrents, + formatBytes, + formatSpeed, + getTorrentState, + matchesFilter, + type TorrentFilter, +} from "@/utils/qbittorrent/format"; +import type { QbTorrent } from "@/utils/qbittorrent/types"; +import { useApiInContext } from "@/utils/store/api"; + +import "./downloads.scss"; + +export const Route = createFileRoute("/_api/downloads")({ + component: DownloadsPage, +}); + +const FILTERS: { value: TorrentFilter; label: string }[] = [ + { value: "all", label: "Все" }, + { value: "downloading", label: "Скачиваются" }, + { value: "completed", label: "Завершённые" }, + { value: "error", label: "Ошибки" }, +]; + +const prettyHost = (url: string) => + url.replace(/^https?:\/\//, "").replace(/\/+$/, ""); + +const notifyCompletion = async (name: string) => { + try { + let granted = await isPermissionGranted(); + if (!granted) { + granted = (await requestPermission()) === "granted"; + } + if (granted) { + sendNotification({ + title: "Загрузка завершена", + body: name, + }); + } + } catch (error) { + // Notification backends are optional (e.g. Linux without libnotify). + console.warn("qBittorrent completion notification failed", error); + } +}; + +function DownloadsPage() { + const navigate = useNavigate(); + const api = useApiInContext((state) => state.api); + const queryClient = useQueryClient(); + + const settingsQuery = useQuery(qbSettingsQueryOptions); + const settings = settingsQuery.data; + const configured = Boolean(settings?.baseUrl && settings.hasSecret); + + const snapshotQuery = useQuery(qbSnapshotQueryOptions(settings)); + const data = snapshotQuery.data; + + const [filter, setFilter] = useState("all"); + const [addOpen, setAddOpen] = useState(false); + const [deleteTarget, setDeleteTarget] = useState(null); + const [deleteFiles, setDeleteFiles] = useState(false); + + const previousProgress = useRef>(new Map()); + const lastJellyfinRefresh = useRef(0); + + const invalidateSnapshot = () => + queryClient.invalidateQueries({ queryKey: ["qbittorrent", "snapshot"] }); + + const torrents = useMemo( + () => [...(data?.torrents ?? [])].sort(compareTorrents), + [data], + ); + + const counts = useMemo(() => { + const result: Record = { + all: torrents.length, + downloading: 0, + completed: 0, + error: 0, + }; + for (const torrent of torrents) { + for (const value of ["downloading", "completed", "error"] as const) { + if (matchesFilter(torrent, value)) result[value] += 1; + } + } + return result; + }, [torrents]); + + const visibleTorrents = useMemo( + () => torrents.filter((torrent) => matchesFilter(torrent, filter)), + [torrents, filter], + ); + + const refreshJellyfin = () => { + if (!api || !settings?.refreshJellyfin) return; + const now = Date.now(); + if (now - lastJellyfinRefresh.current < 30_000) return; + lastJellyfinRefresh.current = now; + getLibraryApi(api) + .refreshLibrary() + .catch((error) => console.warn("Jellyfin library refresh failed", error)); + }; + + // Detect the download -> complete transition between two polls. The first + // snapshot only seeds the map, so torrents that were already complete when + // the page opened do not produce notifications. + useEffect(() => { + if (!data || !settings) return; + + for (const torrent of data.torrents) { + const before = previousProgress.current.get(torrent.hash); + if ( + before !== undefined && + before < 1 && + torrent.progress >= 1 && + !getTorrentState(torrent.state).error + ) { + if (settings.notifyOnComplete) { + void notifyCompletion(torrent.name || "Раздача"); + } + refreshJellyfin(); + } + previousProgress.current.set(torrent.hash, torrent.progress); + } + + const present = new Set(data.torrents.map((torrent) => torrent.hash)); + for (const hash of previousProgress.current.keys()) { + if (!present.has(hash)) previousProgress.current.delete(hash); + } + }, [data, settings]); + + const action = useMutation({ + mutationFn: (variables: { + torrent: QbTorrent; + action: "pause" | "resume"; + }) => + variables.action === "pause" + ? qbPause([variables.torrent.hash]) + : qbResume([variables.torrent.hash]), + onError: (error) => { + enqueueSnackbar(toQbError(error).message, { variant: "error" }); + }, + onSettled: invalidateSnapshot, + }); + + const remove = useMutation({ + mutationFn: (variables: { torrent: QbTorrent; deleteFiles: boolean }) => + qbDelete([variables.torrent.hash], variables.deleteFiles), + onSuccess: () => { + enqueueSnackbar("Раздача удалена", { variant: "success" }); + setDeleteTarget(null); + setDeleteFiles(false); + void invalidateSnapshot(); + }, + onError: (error) => { + enqueueSnackbar(toQbError(error).message, { variant: "error" }); + }, + }); + + const pollError = snapshotQuery.isError + ? toQbError(snapshotQuery.error) + : null; + + if (settingsQuery.isLoading) { + return ( +
+ +
+ ); + } + + return ( +
+
+
+ + Загрузки + + + qBittorrent + {settings?.baseUrl ? ` · ${prettyHost(settings.baseUrl)}` : ""} + +
+
+ + void snapshotQuery.refetch()} + disabled={!configured || snapshotQuery.isFetching} + > + refresh + + + +
+
+ + {!settings?.hasSecret || !settings.baseUrl ? ( +
+ + cloud_download + + + Подключите qBittorrent + + + Добавляйте magnet-ссылки и .torrent файлы, выбирайте категорию и + следите за прогрессом каждой раздачи прямо из Blink. + + +
+ ) : pollError && !data ? ( +
+ + cloud_off + + + qBittorrent не отвечает + + + {pollError.message} + + + + + +
+ ) : ( + <> + {data && ( +
+
+ south +
+
+ {formatSpeed(data.serverState.dlInfoSpeed)} +
+
Скачивание
+
+
+
+ north +
+
+ {formatSpeed(data.serverState.upInfoSpeed)} +
+
Раздача
+
+
+
+ hard_drive +
+
+ {formatBytes(data.serverState.freeSpaceOnDisk)} +
+
Свободно на диске
+
+
+
+ )} + + {pollError && data && ( +
+ cloud_off + {pollError.message} + +
+ )} + + + + {visibleTorrents.length === 0 ? ( +
+ + {filter === "all" ? "download_done" : "filter_alt_off"} + + + {filter === "all" + ? "Пока ничего не скачивается" + : "В этом фильтре пусто"} + + {filter === "all" && ( + + Вставьте magnet-ссылку или выберите .torrent файл — статус + появится здесь. + + )} + {filter === "all" && ( + + )} +
+ ) : ( +
+ {visibleTorrents.map((torrent) => ( + + action.mutate({ torrent: item, action: "pause" }) + } + onResume={(item) => + action.mutate({ torrent: item, action: "resume" }) + } + onDelete={(item) => { + setDeleteFiles(false); + setDeleteTarget(item); + }} + /> + ))} +
+ )} + + )} + + {settings && ( + setAddOpen(false)} + settings={settings} + onAdded={invalidateSnapshot} + /> + )} + + setDeleteTarget(null)} + maxWidth="xs" + fullWidth + disableScrollLock + > + Удалить раздачу? + + + {deleteTarget?.name} + + setDeleteFiles(checked)} + /> + } + label="Удалить скачанные файлы" + /> + {deleteFiles && ( + + Файлы будут удалены с диска сервера qBittorrent без возможности + восстановления. + + )} + + + + + + +
+ ); +} diff --git a/src/routes/_api/settings.tsx b/src/routes/_api/settings.tsx index 0e15f01..ab88018 100644 --- a/src/routes/_api/settings.tsx +++ b/src/routes/_api/settings.tsx @@ -104,6 +104,12 @@ function SettingsRoute() { primary="Настройки" className="settings-sidebar-list-item" /> + (null); + const [secret, setSecret] = useState(""); + const [testResult, setTestResult] = useState(null); + + useEffect(() => { + if (settingsQuery.data && !form) { + setForm(settingsQuery.data); + } + }, [settingsQuery.data, form]); + + const update = ( + key: Key, + value: QbSettings[Key], + ) => { + setForm((current) => (current ? { ...current, [key]: value } : current)); + }; + + const save = useMutation({ + mutationFn: async () => { + if (!form) throw new Error("Настройки ещё не загружены"); + if (!form.hasSecret && !secret.trim()) { + throw new Error("Введите пароль qBittorrent или API-ключ"); + } + if ( + settingsQuery.data && + form.useApiKey !== settingsQuery.data.useApiKey && + !secret.trim() + ) { + throw new Error( + "Способ входа изменился — введите новый пароль или API-ключ", + ); + } + return qbSaveSettings(form, secret || undefined); + }, + onSuccess: (updated) => { + setForm(updated); + setSecret(""); + setTestResult(null); + queryClient.setQueryData(["qbittorrent", "settings"], updated); + void queryClient.invalidateQueries({ + queryKey: ["qbittorrent", "categories"], + }); + void queryClient.invalidateQueries({ + queryKey: ["qbittorrent", "snapshot"], + }); + if (form?.rememberSecret && !updated.secretSaved) { + enqueueSnackbar( + "Настройки сохранены, но системное хранилище секретов недоступно. Пароль будет действовать до закрытия Blink.", + { variant: "warning" }, + ); + } else { + enqueueSnackbar("Настройки загрузок сохранены", { + variant: "success", + }); + } + }, + onError: (error) => { + enqueueSnackbar(toQbError(error).message, { variant: "error" }); + }, + }); + + const test = useMutation({ + mutationFn: async () => { + if (!form) throw new Error("Настройки ещё не загружены"); + if ( + settingsQuery.data && + form.useApiKey !== settingsQuery.data.useApiKey && + !secret.trim() + ) { + throw new Error( + "Способ входа изменился — введите новый пароль или API-ключ", + ); + } + return qbTestConnection(form, secret || undefined); + }, + onSuccess: (result) => { + setTestResult(result); + enqueueSnackbar("Соединение с qBittorrent установлено", { + variant: "success", + }); + }, + onError: (error) => { + setTestResult(null); + enqueueSnackbar(toQbError(error).message, { variant: "error" }); + }, + }); + + const forget = useMutation({ + mutationFn: qbForgetSecret, + onSuccess: (updated) => { + setForm(updated); + setSecret(""); + setTestResult(null); + queryClient.setQueryData(["qbittorrent", "settings"], updated); + enqueueSnackbar("Сохранённый пароль удалён", { variant: "success" }); + }, + onError: (error) => { + enqueueSnackbar(toQbError(error).message, { variant: "error" }); + }, + }); + + if (settingsQuery.isError) { + return ( +
+ Загрузки +
+ error +
+ {toQbError(settingsQuery.error).message} + +
+
+
+ ); + } + + if (settingsQuery.isLoading || !form) { + return ( +
+ +
+ ); + } + + return ( +
+ Загрузки + + Подключение к qBittorrent и поведение страницы загрузок. + + +
{ + event.preventDefault(); + test.reset(); + save.mutate(); + }} + > + update("baseUrl", event.target.value)} + helperText="Без /api/v2. Поддерживаются http:// и https://." + /> + + + update("useApiKey", event.target.value === "apiKey") + } + > + Логин и пароль + API-ключ (qBittorrent 5.3+) + + + {!form.useApiKey && ( + update("username", event.target.value)} + autoComplete="username" + /> + )} + + setSecret(event.target.value)} + placeholder={form.hasSecret ? "•••••••• (задан)" : ""} + autoComplete="new-password" + helperText={ + form.hasSecret + ? "Оставьте поле пустым, чтобы не менять текущий секрет." + : form.useApiKey + ? "Ключ создаётся в qBittorrent: WebUI → API." + : "Пароль хранится только в системном хранилище секретов." + } + /> + + + update("rememberSecret", checked)} + /> + } + label="Запомнить секрет" + /> + update("allowInvalidCerts", checked)} + /> + } + label="Принимать самоподписанный сертификат" + /> + + + + Без системного хранилища (например, на Linux без Secret Service) + пароль действует до закрытия Blink и не пишется в файл. + + + update("defaultCategory", event.target.value)} + helperText="Подставляется в диалог добавления. Пустое поле — без категории." + /> + + + update("autoTmm", checked)} + /> + } + label="Автоуправление категорией" + /> + update("addPaused", checked)} + /> + } + label="Добавлять на паузе" + /> + + + + update("notifyOnComplete", checked)} + /> + } + label="Уведомлять о завершении" + /> + update("refreshJellyfin", checked)} + /> + } + label="Обновлять библиотеку Jellyfin" + /> + + + + update("pollIntervalMs", Number(event.target.value) || 0) + } + onBlur={() => + update( + "pollIntervalMs", + Math.min(60_000, Math.max(1000, form.pollIntervalMs)), + ) + } + helperText="От 1000 до 60000 мс. По умолчанию 2000." + /> + + {testResult && ( +
+ check_circle +
+ + qBittorrent {testResult.appVersion} · WebAPI{" "} + {testResult.apiVersion} + +
+ Папка по умолчанию: {testResult.defaultSavePath || "не задана"} +
+
+
+ )} + + {test.isError && ( +
+ error +
{toQbError(test.error).message}
+
+ )} + + + {form.hasSecret && ( + + )} + + + + +
+ ); +} diff --git a/src/utils/qbittorrent/api.ts b/src/utils/qbittorrent/api.ts new file mode 100644 index 0000000..e3fce42 --- /dev/null +++ b/src/utils/qbittorrent/api.ts @@ -0,0 +1,70 @@ +import { invoke } from "@tauri-apps/api/core"; +import type { + QbAddRequest, + QbAddResult, + QbCategory, + QbConnectionInfo, + QbError, + QbSettings, + QbSnapshot, +} from "./types"; + +export const qbGetSettings = () => invoke("qb_get_settings"); + +export const qbSaveSettings = (settings: QbSettings, secret?: string) => + invoke("qb_save_settings", { + settings, + secret: secret?.trim() ? secret : null, + }); + +export const qbForgetSecret = () => invoke("qb_forget_secret"); + +export const qbTestConnection = (settings: QbSettings, secret?: string) => + invoke("qb_test_connection", { + settings, + secret: secret?.trim() ? secret : null, + }); + +export const qbCategories = () => invoke("qb_categories"); + +export const qbAddTorrent = (request: QbAddRequest) => + invoke("qb_add_torrent", { request }); + +export const qbPoll = () => invoke("qb_poll"); + +export const qbPause = (hashes: string[]) => + invoke("qb_pause", { hashes }); + +export const qbResume = (hashes: string[]) => + invoke("qb_resume", { hashes }); + +export const qbDelete = (hashes: string[], deleteFiles: boolean) => + invoke("qb_delete", { hashes, deleteFiles }); + +export const qbSetCategory = (hashes: string[], category: string) => + invoke("qb_set_category", { hashes, category }); + +/** Normalise an unknown `invoke` rejection into the shape the UI renders. */ +export const toQbError = (error: unknown): QbError => { + if ( + typeof error === "object" && + error !== null && + "message" in error && + typeof (error as { message?: unknown }).message === "string" + ) { + const value = error as Partial; + return { + kind: value.kind ?? "http", + message: value.message ?? "Неизвестная ошибка qBittorrent", + status: value.status ?? null, + }; + } + return { + kind: "http", + message: + typeof error === "string" + ? error + : "Не удалось выполнить запрос к qBittorrent", + status: null, + }; +}; diff --git a/src/utils/qbittorrent/format.ts b/src/utils/qbittorrent/format.ts new file mode 100644 index 0000000..49f248c --- /dev/null +++ b/src/utils/qbittorrent/format.ts @@ -0,0 +1,129 @@ +const BYTE_UNITS = ["Б", "КБ", "МБ", "ГБ", "ТБ", "ПБ"]; + +export const formatBytes = (bytes: number) => { + if (!Number.isFinite(bytes) || bytes <= 0) return "0 Б"; + let value = bytes; + let unit = 0; + while (value >= 1024 && unit < BYTE_UNITS.length - 1) { + value /= 1024; + unit += 1; + } + const digits = value >= 100 || unit === 0 ? 0 : 1; + return `${value.toFixed(digits).replace(".", ",")} ${BYTE_UNITS[unit]}`; +}; + +export const formatSpeed = (bytesPerSecond: number) => + `${formatBytes(bytesPerSecond)}/с`; + +export const formatEta = (seconds: number) => { + if (!Number.isFinite(seconds) || seconds < 0 || seconds >= 8_640_000) { + return "∞"; + } + if (seconds < 60) return `${Math.max(1, Math.round(seconds))} с`; + const minutes = Math.floor(seconds / 60); + if (minutes < 60) return `${minutes} мин`; + const hours = Math.floor(minutes / 60); + const rest = minutes % 60; + return rest > 0 ? `${hours} ч ${rest} мин` : `${hours} ч`; +}; + +export const formatPercent = (progress: number) => + `${Math.min(100, Math.max(0, Math.round(progress * 100)))}%`; + +export type TorrentTone = + | "downloading" + | "seeding" + | "paused" + | "error" + | "neutral"; + +export type TorrentStateInfo = { + label: string; + tone: TorrentTone; + /** The download has finished, regardless of seeding/paused state. */ + done: boolean; + /** The torrent is stopped by the user. */ + paused: boolean; + error: boolean; +}; + +const state = ( + label: string, + tone: TorrentTone, + done = false, + paused = false, + error = false, +): TorrentStateInfo => ({ label, tone, done, paused, error }); + +export const getTorrentState = (value: string): TorrentStateInfo => { + switch (value) { + case "metaDL": + case "forcedMetaDL": + return state("Метаданные", "downloading"); + case "downloading": + case "forcedDL": + return state("Скачивается", "downloading"); + case "stalledDL": + return state("Нет пиров", "downloading"); + case "queuedDL": + return state("В очереди", "downloading"); + case "checkingDL": + return state("Проверка", "downloading"); + case "allocating": + return state("Выделение места", "downloading"); + case "moving": + return state("Перемещение", "downloading"); + case "checkingResumeData": + return state("Проверка данных", "downloading"); + case "pausedDL": + case "stoppedDL": + return state("Пауза", "paused", false, true); + case "uploading": + case "forcedUP": + return state("Раздаётся", "seeding", true); + case "stalledUP": + return state("Раздаётся", "seeding", true); + case "queuedUP": + return state("Завершено", "seeding", true); + case "checkingUP": + return state("Проверка", "seeding", true); + case "pausedUP": + case "stoppedUP": + return state("Завершено", "seeding", true, true); + case "error": + return state("Ошибка", "error", false, false, true); + case "missingFiles": + return state("Файлы не найдены", "error", false, false, true); + default: + return state("Неизвестно", "neutral"); + } +}; + +export type TorrentFilter = "all" | "downloading" | "completed" | "error"; + +export const matchesFilter = ( + torrent: { progress: number; state: string }, + filter: TorrentFilter, +) => { + const info = getTorrentState(torrent.state); + if (filter === "all") return true; + if (filter === "downloading") return !info.done && !info.error; + if (filter === "completed") return info.done; + return info.error; +}; + +export const compareTorrents = ( + left: { progress: number; state: string; addedOn: number }, + right: { progress: number; state: string; addedOn: number }, +) => { + const leftInfo = getTorrentState(left.state); + const rightInfo = getTorrentState(right.state); + const rank = (info: TorrentStateInfo) => { + if (info.error) return 0; + if (!info.done) return 1; + if (info.paused) return 3; + return 2; + }; + const diff = rank(leftInfo) - rank(rightInfo); + return diff !== 0 ? diff : right.addedOn - left.addedOn; +}; diff --git a/src/utils/qbittorrent/hooks.ts b/src/utils/qbittorrent/hooks.ts new file mode 100644 index 0000000..27eea00 --- /dev/null +++ b/src/utils/qbittorrent/hooks.ts @@ -0,0 +1,38 @@ +import { queryOptions, useQuery } from "@tanstack/react-query"; +import { qbCategories, qbGetSettings, qbPoll } from "./api"; +import type { QbSettings } from "./types"; + +export const qbSettingsQueryOptions = queryOptions({ + queryKey: ["qbittorrent", "settings"], + queryFn: qbGetSettings, + staleTime: Number.POSITIVE_INFINITY, + retry: false, + networkMode: "always", +}); + +export const useQbSettings = () => useQuery(qbSettingsQueryOptions); + +export const qbCategoriesQueryOptions = (enabled: boolean) => + queryOptions({ + queryKey: ["qbittorrent", "categories"], + queryFn: qbCategories, + enabled, + staleTime: 60_000, + retry: false, + networkMode: "always", + }); + +const pollInterval = (settings?: QbSettings) => + Math.max(1000, settings?.pollIntervalMs || 2000); + +export const qbSnapshotQueryOptions = (settings?: QbSettings) => + queryOptions({ + queryKey: ["qbittorrent", "snapshot"], + queryFn: qbPoll, + enabled: Boolean(settings?.baseUrl && settings.hasSecret), + refetchInterval: () => + document.visibilityState === "visible" ? pollInterval(settings) : false, + refetchIntervalInBackground: false, + retry: 1, + networkMode: "always", + }); diff --git a/src/utils/qbittorrent/index.ts b/src/utils/qbittorrent/index.ts new file mode 100644 index 0000000..f190b31 --- /dev/null +++ b/src/utils/qbittorrent/index.ts @@ -0,0 +1,4 @@ +export * from "./api"; +export * from "./format"; +export * from "./hooks"; +export type * from "./types"; diff --git a/src/utils/qbittorrent/types.ts b/src/utils/qbittorrent/types.ts new file mode 100644 index 0000000..377b2f0 --- /dev/null +++ b/src/utils/qbittorrent/types.ts @@ -0,0 +1,101 @@ +export type QbSettings = { + baseUrl: string; + username: string; + useApiKey: boolean; + rememberSecret: boolean; + defaultCategory: string; + autoTmm: boolean; + addPaused: boolean; + allowInvalidCerts: boolean; + refreshJellyfin: boolean; + notifyOnComplete: boolean; + pollIntervalMs: number; + secretSaved: boolean; + hasSecret: boolean; +}; + +export type QbCategory = { + name: string; + savePath: string; + downloadPath?: string | null; +}; + +export type QbTorrent = { + hash: string; + name: string; + category: string; + size: number; + completed: number; + downloaded: number; + progress: number; + dlspeed: number; + upspeed: number; + eta: number; + state: string; + savePath: string; + contentPath: string; + addedOn: number; + completionOn: number; + ratio: number; + numSeeds: number; + numLeeches: number; + error?: string | null; + tags: string; + seedingTime: number; + timeActive: number; + amountLeft: number; + tracker: string; +}; + +export type QbServerState = { + dlInfoSpeed: number; + upInfoSpeed: number; + dlInfoData: number; + upInfoData: number; + freeSpaceOnDisk: number; + connectionStatus: string; + queueing: boolean; + dhtNodes: number; +}; + +export type QbSnapshot = { + torrents: QbTorrent[]; + serverState: QbServerState; + synced: boolean; +}; + +export type QbAddResult = { + status: "added" | "pending" | "duplicate" | "invalid"; + addedHashes: string[]; + message?: string | null; +}; + +export type QbConnectionInfo = { + appVersion: string; + apiVersion: string; + defaultSavePath: string; +}; + +export type QbAddRequest = { + magnet?: string | null; + filePath?: string | null; + category?: string | null; + paused?: boolean | null; + autoTmm?: boolean | null; +}; + +export type QbError = { + kind: + | "unreachable" + | "auth" + | "banned" + | "tls" + | "duplicate" + | "torrent" + | "http" + | "config" + | "internal" + | string; + message: string; + status?: number | null; +};