feat(downloads): add qBittorrent integration
Continuous Integration / build_web (push) Failing after 0s
Continuous Integration / build (macos-latest) (push) Skipped
Continuous Integration / build (ubuntu-22.04) (push) Skipped
Continuous Integration / build (windows-11-arm) (push) Skipped
Continuous Integration / build (windows-latest) (push) Skipped
Continuous Integration / nightly_release (push) Skipped
Continuous Integration / build_web (push) Failing after 0s
Continuous Integration / build (macos-latest) (push) Skipped
Continuous Integration / build (ubuntu-22.04) (push) Skipped
Continuous Integration / build (windows-11-arm) (push) Skipped
Continuous Integration / build (windows-latest) (push) Skipped
Continuous Integration / nightly_release (push) Skipped
- 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
This commit is contained in:
1 parent
fe30c4f1f9
commit
87315d9679
22 files changed
+4031
-21
No files matched your search
+20
-3
@@ -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())
|
||||
|
||||
@@ -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<String>,
|
||||
pub file_name: Option<String>,
|
||||
pub file_bytes: Option<Vec<u8>>,
|
||||
pub category: Option<String>,
|
||||
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<String, QbError> {
|
||||
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<Self, QbError> {
|
||||
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<Self, QbError> {
|
||||
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<F>(&self, build: F) -> Result<Response, QbError>
|
||||
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<String, QbError> {
|
||||
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<T>(&self, path: &str) -> Result<T, QbError>
|
||||
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<QbConnectionInfo, QbError> {
|
||||
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<Vec<QbCategory>, QbError> {
|
||||
let categories: HashMap<String, QbCategory> =
|
||||
self.get_json("/api/v2/torrents/categories").await?;
|
||||
|
||||
let mut list: Vec<QbCategory> = 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<QbAddResult, QbError> {
|
||||
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<Value, QbError> {
|
||||
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<u8>), 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<QbAddResult, QbError> {
|
||||
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::<QbAddResponse>(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))
|
||||
}
|
||||
@@ -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<String>,
|
||||
secret_saved: bool,
|
||||
client: Option<QbClient>,
|
||||
torrents: HashMap<String, Value>,
|
||||
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<Inner>,
|
||||
}
|
||||
|
||||
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<MutexGuard<'_, Inner>, QbError> {
|
||||
self.inner
|
||||
.lock()
|
||||
.map_err(|_| QbError::new("internal", "Внутреннее состояние qBittorrent повреждено"))
|
||||
}
|
||||
}
|
||||
|
||||
fn keyring_entry() -> Result<keyring::Entry, QbError> {
|
||||
keyring::Entry::new(KEYRING_SERVICE, KEYRING_USER).map_err(|err| {
|
||||
QbError::new(
|
||||
"config",
|
||||
format!("Системное хранилище секретов недоступно: {err}"),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn keyring_read() -> Option<String> {
|
||||
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<PathBuf, QbError> {
|
||||
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<QbTorrent> = 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<QbSettings, QbError> {
|
||||
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<String>,
|
||||
) -> Result<QbSettings, QbError> {
|
||||
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<QbSettings, QbError> {
|
||||
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<String>,
|
||||
) -> Result<QbConnectionInfo, QbError> {
|
||||
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<Vec<QbCategory>, 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<QbAddResult, QbError> {
|
||||
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<QbSnapshot, QbError> {
|
||||
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<String>) -> 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<String>) -> 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<String>,
|
||||
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<String>,
|
||||
category: String,
|
||||
) -> Result<(), QbError> {
|
||||
let (client, _settings) = client_and_settings(&state).await?;
|
||||
client.set_category(&hashes, category.trim()).await
|
||||
}
|
||||
@@ -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<String>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
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<String>,
|
||||
pub tags: String,
|
||||
pub seeding_time: i64,
|
||||
pub time_active: i64,
|
||||
pub amount_left: i64,
|
||||
pub tracker: String,
|
||||
}
|
||||
|
||||
impl From<QbTorrentRaw> 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<QbServerStateRaw> 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<QbTorrent>,
|
||||
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<String>,
|
||||
pub message: Option<String>,
|
||||
}
|
||||
|
||||
impl QbAddResult {
|
||||
pub fn new(status: &str, added_hashes: Vec<String>, message: Option<String>) -> 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<u16>,
|
||||
}
|
||||
|
||||
impl QbError {
|
||||
pub fn new(kind: &str, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
kind: kind.to_string(),
|
||||
message: message.into(),
|
||||
status: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_status(kind: &str, message: impl Into<String>, status: u16) -> Self {
|
||||
Self {
|
||||
kind: kind.to_string(),
|
||||
message: message.into(),
|
||||
status: Some(status),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn config(message: impl Into<String>) -> Self {
|
||||
Self::new("config", message)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct QbAddRequest {
|
||||
pub magnet: Option<String>,
|
||||
pub file_path: Option<String>,
|
||||
pub category: Option<String>,
|
||||
pub paused: Option<bool>,
|
||||
pub auto_tmm: Option<bool>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
}
|
||||
Reference in new issue
Block a user