qBittorrent's add call answers `Ok.` and nothing else — no hash, no name, no duplicate signal — so arr derives the v1 infohash from the magnet or the `.torrent` bytes before the call and looks the torrent up by it. That also drops Transmission's numeric torrent id: the hash is the only identity now. The reaper needs "stopped because a share limit was reached", and qBittorrent's state field cannot tell that apart from a hand-paused torrent. So the ratio and idle counters are checked against the limits arr set, and a torrent stopped by a global limit reads as still seeding rather than being deleted. The WebUI needs a login, so `ARR_QBITTORRENT_USERNAME` and `ARR_QBITTORRENT_PASSWORD` join the env-only secrets; leaving both unset is valid for an instance that whitelists arr's subnet. Verified against qBittorrent 5 (WebAPI 2.15.1) in a container: it rejects `setShareLimits` without `shareLimitAction`, which 4.x ignores, so it is always sent. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
232 lines
7.3 KiB
Rust
232 lines
7.3 KiB
Rust
//! The live download snapshot, joined to arr-owned grabs only.
|
|
|
|
use std::time::{Duration, Instant};
|
|
|
|
use arr_dl::{Torrent, TorrentState};
|
|
use axum::extract::State;
|
|
use axum::Json;
|
|
use serde::Serialize;
|
|
use utoipa::ToSchema;
|
|
|
|
use crate::movies::ApiError;
|
|
use crate::state::AppState;
|
|
|
|
const SNAPSHOT_TTL: Duration = Duration::from_secs(15);
|
|
|
|
#[derive(Debug, Clone, Copy, Serialize, ToSchema, PartialEq, Eq)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum DownloadPhase {
|
|
Downloading,
|
|
Stalled,
|
|
Errored,
|
|
Seeding,
|
|
Queued,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
|
pub struct Download {
|
|
pub target_kind: String,
|
|
pub target_id: i64,
|
|
pub infohash: String,
|
|
pub name: String,
|
|
pub phase: DownloadPhase,
|
|
pub progress: f64,
|
|
pub download_rate: u64,
|
|
pub eta: Option<i64>,
|
|
pub error: Option<String>,
|
|
}
|
|
|
|
#[utoipa::path(
|
|
get,
|
|
path = "/api/downloads",
|
|
tag = "system",
|
|
responses(
|
|
(status = 200, description = "Live downloads started by arr", body = [Download]),
|
|
(status = 503, description = "qBittorrent or database unavailable", body = crate::movies::ErrorBody)
|
|
)
|
|
)]
|
|
pub(crate) async fn list(State(state): State<AppState>) -> Result<Json<Vec<Download>>, ApiError> {
|
|
let database = state.database().ok_or(ApiError::Unavailable)?;
|
|
let qbit = state.qbit().ok_or(ApiError::Upstream("qbit"))?;
|
|
|
|
let torrents = {
|
|
let mut cache = state.download_snapshot().write().await;
|
|
if let Some((at, torrents)) = cache.as_ref() {
|
|
if at.elapsed() < SNAPSHOT_TTL {
|
|
torrents.clone()
|
|
} else {
|
|
let torrents = qbit
|
|
.list_torrents()
|
|
.await
|
|
.map_err(|_| ApiError::Upstream("qbit"))?;
|
|
*cache = Some((Instant::now(), torrents.clone()));
|
|
torrents
|
|
}
|
|
} else {
|
|
let torrents = qbit
|
|
.list_torrents()
|
|
.await
|
|
.map_err(|_| ApiError::Upstream("qbit"))?;
|
|
*cache = Some((Instant::now(), torrents.clone()));
|
|
torrents
|
|
}
|
|
};
|
|
|
|
let grabs: Vec<Grab> =
|
|
sqlx::query_as("SELECT target_kind, target_id, infohash FROM grabs ORDER BY id")
|
|
.fetch_all(database.pool())
|
|
.await?;
|
|
|
|
let mut downloads = Vec::new();
|
|
for grab in grabs {
|
|
let Some(torrent) = torrents
|
|
.iter()
|
|
.find(|torrent| torrent.hash.eq_ignore_ascii_case(&grab.infohash))
|
|
else {
|
|
continue;
|
|
};
|
|
downloads.push(Download {
|
|
target_kind: grab.target_kind,
|
|
target_id: grab.target_id,
|
|
infohash: torrent.hash.clone(),
|
|
name: torrent.name.clone(),
|
|
phase: phase(torrent),
|
|
progress: torrent.progress,
|
|
download_rate: torrent.download_rate,
|
|
eta: torrent.eta,
|
|
error: torrent.error.clone(),
|
|
});
|
|
}
|
|
|
|
Ok(Json(downloads))
|
|
}
|
|
|
|
#[derive(Debug, sqlx::FromRow)]
|
|
struct Grab {
|
|
target_kind: String,
|
|
target_id: i64,
|
|
infohash: String,
|
|
}
|
|
|
|
fn phase(torrent: &Torrent) -> DownloadPhase {
|
|
if torrent.error.is_some() {
|
|
DownloadPhase::Errored
|
|
} else {
|
|
match torrent.state {
|
|
TorrentState::Seeding => DownloadPhase::Seeding,
|
|
// qBittorrent's own verdict, not a zero rate: a torrent between
|
|
// peers reads zero for a poll or two and finishes fine, and
|
|
// §9.8's stalled chip is for the case that never does.
|
|
TorrentState::Downloading if torrent.is_stalled => DownloadPhase::Stalled,
|
|
TorrentState::Downloading => DownloadPhase::Downloading,
|
|
_ => DownloadPhase::Queued,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use std::path::PathBuf;
|
|
|
|
use arr_db::Db;
|
|
use axum::extract::State;
|
|
use serde_json::json;
|
|
use wiremock::matchers::{method, path};
|
|
use wiremock::{Mock, MockServer, ResponseTemplate};
|
|
|
|
use super::{list, phase, DownloadPhase};
|
|
use crate::state::{AppState, Upstreams};
|
|
|
|
#[test]
|
|
fn torrent_states_become_the_download_phases() {
|
|
let torrent =
|
|
|state: arr_dl::TorrentState, rate: u64, error: Option<&str>| arr_dl::Torrent {
|
|
name: "name".into(),
|
|
hash: "hash".into(),
|
|
state,
|
|
progress: 0.5,
|
|
download_rate: rate,
|
|
eta: None,
|
|
error: error.map(str::to_owned),
|
|
is_stalled: rate == 0,
|
|
download_dir: PathBuf::from("/downloads"),
|
|
labels: Vec::new(),
|
|
is_finished: false,
|
|
};
|
|
|
|
assert_eq!(
|
|
phase(&torrent(arr_dl::TorrentState::Downloading, 10, None)),
|
|
DownloadPhase::Downloading
|
|
);
|
|
assert_eq!(
|
|
phase(&torrent(arr_dl::TorrentState::Downloading, 0, None)),
|
|
DownloadPhase::Stalled
|
|
);
|
|
assert_eq!(
|
|
phase(&torrent(arr_dl::TorrentState::Seeding, 0, None)),
|
|
DownloadPhase::Seeding
|
|
);
|
|
assert_eq!(
|
|
phase(&torrent(
|
|
arr_dl::TorrentState::Downloading,
|
|
10,
|
|
Some("disk full")
|
|
)),
|
|
DownloadPhase::Errored
|
|
);
|
|
assert_eq!(
|
|
phase(&torrent(arr_dl::TorrentState::QueuedToDownload, 0, None)),
|
|
DownloadPhase::Queued
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn endpoint_joins_only_arr_grabs_and_reuses_the_snapshot() {
|
|
let server = MockServer::start().await;
|
|
Mock::given(method("GET"))
|
|
.and(path("/api/v2/torrents/info"))
|
|
.respond_with(ResponseTemplate::new(200).set_body_json(json!([{
|
|
"hash": "ABC", "name": "grabbed", "state": "downloading",
|
|
"progress": 0.4, "dlspeed": 123, "eta": 60,
|
|
"save_path": "/downloads", "tags": ""
|
|
}])))
|
|
.expect(1)
|
|
.mount(&server)
|
|
.await;
|
|
|
|
let directory = tempfile::tempdir().expect("tempdir");
|
|
let database = Db::connect(directory.path().join("arr.db"))
|
|
.await
|
|
.expect("database");
|
|
database.migrate().await.expect("migrate");
|
|
sqlx::query(
|
|
"INSERT INTO releases (id, indexer_id, guid, name, size, download_url, parsed)
|
|
VALUES (1, 1, 'guid', 'release', 1, 'magnet:?x', '{}')",
|
|
)
|
|
.execute(database.pool())
|
|
.await
|
|
.expect("release");
|
|
sqlx::query(
|
|
"INSERT INTO grabs (release_id, target_kind, target_id, infohash)
|
|
VALUES (1, 'movie', 42, 'abc')",
|
|
)
|
|
.execute(database.pool())
|
|
.await
|
|
.expect("grab");
|
|
|
|
let state = AppState::new(Upstreams::new("unused".into(), server.uri()))
|
|
.expect("state")
|
|
.with_database(database)
|
|
.with_qbit(arr_dl::QbitClient::new(&server.uri()).expect("client"));
|
|
let first = list(State(state.clone())).await.expect("first").0;
|
|
let second = list(State(state)).await.expect("second").0;
|
|
assert_eq!(first.len(), 1);
|
|
assert_eq!(first[0].target_kind, "movie");
|
|
assert_eq!(first[0].target_id, 42);
|
|
assert_eq!(first[0].infohash, "ABC");
|
|
assert_eq!(first[0].phase, DownloadPhase::Downloading);
|
|
assert_eq!(first[0].download_rate, 123);
|
|
assert_eq!(second.len(), 1);
|
|
}
|
|
}
|