feat(downloads): WiFi-only network-type-aware download gating
Add a metered/cellular network detector so downloads honour a "WiFi only" preference. Android reports network type via NetworkTypeMonitor; Rust exposes it through download/network.rs and holds the queue pump when on a metered connection, emitting a queue-wide waitingForNetwork event. The frontend surfaces this via the networkType service and a waitingForNetwork store flag. TRACES: UR-053 | DR-074
This commit is contained in:
@@ -8,6 +8,7 @@ use std::sync::{Arc, Mutex};
|
||||
use tauri::{Manager, State};
|
||||
|
||||
use super::{DatabaseWrapper, SmartCacheWrapper};
|
||||
use crate::download::network::{NetworkState, NetworkStateHandle, NetworkType};
|
||||
use crate::download::{DownloadInfo, DownloadManager};
|
||||
use crate::storage::db_service::{DatabaseService, Query, QueryParam};
|
||||
|
||||
@@ -21,6 +22,80 @@ pub use smart_cache::*;
|
||||
/// Wrapper for DownloadManager to be used as Tauri state
|
||||
pub struct DownloadManagerWrapper(pub Mutex<DownloadManager>);
|
||||
|
||||
/// Wrapper for the current network transport, used by the WiFi-only gate.
|
||||
///
|
||||
/// TRACES: UR-053 | DR-074
|
||||
pub struct NetworkStateWrapper(pub NetworkStateHandle);
|
||||
|
||||
/// Report the device's current network transport (Android → Rust).
|
||||
///
|
||||
/// The frontend calls this on startup and whenever the native network callback
|
||||
/// fires. Updating to an acceptable network re-pumps the download queue, so a
|
||||
/// queue parked on "waiting for WiFi" drains itself without user action.
|
||||
///
|
||||
/// TRACES: UR-053 | DR-074
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn set_network_state(
|
||||
app: tauri::AppHandle,
|
||||
network: NetworkStateWrapperArg,
|
||||
db: State<'_, DatabaseWrapper>,
|
||||
download_manager: State<'_, DownloadManagerWrapper>,
|
||||
) -> Result<(), String> {
|
||||
let new_state = NetworkState {
|
||||
network_type: network.network_type,
|
||||
unmetered: network.unmetered,
|
||||
};
|
||||
|
||||
let handle = app.state::<NetworkStateWrapper>().0.clone();
|
||||
let previous = handle.get().await;
|
||||
handle.set(new_state).await;
|
||||
|
||||
if previous != new_state {
|
||||
info!(
|
||||
"[network] Transport changed: {:?} (unmetered={}) -> {:?} (unmetered={})",
|
||||
previous.network_type, previous.unmetered, new_state.network_type, new_state.unmetered
|
||||
);
|
||||
}
|
||||
|
||||
// If the new network unblocks the gate, drain whatever was waiting.
|
||||
if downloads_allowed_on_current_network(&app).await {
|
||||
let db_service = {
|
||||
let database = db.0.lock().map_err(|e| e.to_string())?;
|
||||
Arc::new(database.service())
|
||||
};
|
||||
let active = {
|
||||
let manager = download_manager.0.lock().map_err(|e| e.to_string())?;
|
||||
manager.get_active_downloads()
|
||||
};
|
||||
pump_download_queue(app.clone(), db_service, active).await;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Argument struct for [`set_network_state`].
|
||||
///
|
||||
/// TRACES: UR-053 | DR-074
|
||||
#[derive(specta::Type, Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NetworkStateWrapperArg {
|
||||
pub network_type: NetworkType,
|
||||
pub unmetered: bool,
|
||||
}
|
||||
|
||||
/// Whether downloads are currently permitted by the WiFi-only gate.
|
||||
///
|
||||
/// The downloads UI uses this to render "Waiting for WiFi" on pending rows
|
||||
/// rather than leaving them looking silently stuck.
|
||||
///
|
||||
/// TRACES: UR-053 | DR-074
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn get_downloads_allowed(app: tauri::AppHandle) -> Result<bool, String> {
|
||||
Ok(downloads_allowed_on_current_network(&app).await)
|
||||
}
|
||||
|
||||
/// Download statistics computed server-side
|
||||
#[allow(dead_code)]
|
||||
#[derive(specta::Type, Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
@@ -1213,6 +1288,37 @@ pub async fn enqueue_video_downloads(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the current network permits downloads, given the user's WiFi-only
|
||||
/// preference.
|
||||
///
|
||||
/// Reads `wifi_only` from the SmartCache config (the single home of the
|
||||
/// setting) and checks it against the transport reported by the platform. On
|
||||
/// desktop the transport defaults to unmetered ethernet, so this is always
|
||||
/// true there.
|
||||
///
|
||||
/// TRACES: UR-053 | DR-074
|
||||
pub(crate) async fn downloads_allowed_on_current_network(app: &tauri::AppHandle) -> bool {
|
||||
let wifi_only = {
|
||||
let smart_cache = app.state::<SmartCacheWrapper>();
|
||||
let cache = match smart_cache.0.lock() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
error!("[pump] Failed to lock smart cache: {}", e);
|
||||
// Fail open: a lock problem must not silently wedge downloads.
|
||||
return true;
|
||||
}
|
||||
};
|
||||
cache.get_config().map(|c| c.wifi_only).unwrap_or(false)
|
||||
};
|
||||
|
||||
if !wifi_only {
|
||||
return true;
|
||||
}
|
||||
|
||||
let network = app.state::<NetworkStateWrapper>();
|
||||
network.0.allows_download(true).await
|
||||
}
|
||||
|
||||
/// Start as many pending downloads as there are free concurrency slots.
|
||||
///
|
||||
/// Picks the highest-priority `pending` rows that have a persisted `stream_url`
|
||||
@@ -1227,6 +1333,16 @@ pub(crate) async fn pump_download_queue(
|
||||
use crate::download::events::DownloadEvent;
|
||||
use tauri::Emitter;
|
||||
|
||||
// WiFi-only gate (UR-053): when the user has restricted downloads to
|
||||
// unmetered networks and we're on cellular (or can't tell), leave every
|
||||
// pending row exactly as it is. They stay 'pending' and the Android
|
||||
// network callback re-pumps us as soon as an acceptable network appears.
|
||||
if !downloads_allowed_on_current_network(&app).await {
|
||||
info!("[pump] Downloads paused: waiting for an unmetered network (WiFi-only enabled)");
|
||||
let _ = app.emit("download-event", DownloadEvent::WaitingForNetwork);
|
||||
return;
|
||||
}
|
||||
|
||||
let max_concurrent = {
|
||||
let manager = app.state::<DownloadManagerWrapper>();
|
||||
let manager = match manager.0.lock() {
|
||||
@@ -1799,6 +1915,76 @@ pub async fn delete_album_downloads(
|
||||
Ok(deleted_count as i64)
|
||||
}
|
||||
|
||||
/// Remove every completed download at or under a container item.
|
||||
///
|
||||
/// Works at any level of the Downloaded browse: a leaf (removes just that
|
||||
/// download), an album/season/series (removes all downloaded descendants linked
|
||||
/// via album_id/season_id/series_id/parent_id). Deletes the DB rows and the
|
||||
/// on-disk files. Returns the number of downloads removed. Idempotent.
|
||||
///
|
||||
/// TRACES: UR-055 | DR-083
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn delete_downloads_under(
|
||||
db: State<'_, DatabaseWrapper>,
|
||||
item_id: String,
|
||||
user_id: String,
|
||||
) -> Result<i64, String> {
|
||||
let db_service = {
|
||||
let database = db.0.lock().map_err(|e| e.to_string())?;
|
||||
Arc::new(database.service())
|
||||
};
|
||||
|
||||
// The item itself, or any child linked to it by container id.
|
||||
const SCOPE: &str = "d.user_id = ? AND d.status = 'completed'
|
||||
AND (
|
||||
d.item_id = ?
|
||||
OR d.item_id IN (
|
||||
SELECT c.id FROM items c
|
||||
WHERE c.album_id = ? OR c.season_id = ? OR c.series_id = ? OR c.parent_id = ?
|
||||
)
|
||||
)";
|
||||
|
||||
let file_query = Query::with_params(
|
||||
&format!("SELECT d.file_path FROM downloads d WHERE {SCOPE}"),
|
||||
vec![
|
||||
QueryParam::String(user_id.clone()),
|
||||
QueryParam::String(item_id.clone()),
|
||||
QueryParam::String(item_id.clone()),
|
||||
QueryParam::String(item_id.clone()),
|
||||
QueryParam::String(item_id.clone()),
|
||||
QueryParam::String(item_id.clone()),
|
||||
],
|
||||
);
|
||||
let file_paths: Vec<String> = db_service
|
||||
.query_many(file_query, |row| row.get(0))
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let delete_query = Query::with_params(
|
||||
&format!("DELETE FROM downloads WHERE id IN (SELECT d.id FROM downloads d WHERE {SCOPE})"),
|
||||
vec![
|
||||
QueryParam::String(user_id),
|
||||
QueryParam::String(item_id.clone()),
|
||||
QueryParam::String(item_id.clone()),
|
||||
QueryParam::String(item_id.clone()),
|
||||
QueryParam::String(item_id.clone()),
|
||||
QueryParam::String(item_id),
|
||||
],
|
||||
);
|
||||
let deleted_count = db_service
|
||||
.execute(delete_query)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
for path in file_paths {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let _ = std::fs::remove_file(format!("{}.part", path));
|
||||
}
|
||||
|
||||
Ok(deleted_count as i64)
|
||||
}
|
||||
|
||||
/// Download manager statistics
|
||||
#[derive(specta::Type, Debug, Clone, serde::Serialize)]
|
||||
pub struct DownloadManagerStats {
|
||||
|
||||
Reference in New Issue
Block a user