Skip to content

Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.

feat: implement recovery feature with persistence and recovery item management

Tonho456a9c06df35
diff --git a/src-tauri/omniget-core/src/models/settings.rs b/src-tauri/omniget-core/src/models/settings.rs
index 8abb34c2..3070eecc 100644
--- a/src-tauri/omniget-core/src/models/settings.rs
+++ b/src-tauri/omniget-core/src/models/settings.rs
@@ -19,6 +19,16 @@ pub struct AppSettings {
pub portable_mode: bool,
#[serde(default)]
pub legal_acknowledged: bool,
+ #[serde(default)]
+ pub last_download_options: LastDownloadOptions,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+pub struct LastDownloadOptions {
+ #[serde(default)]
+ pub mode: Option<String>,
+ #[serde(default)]
+ pub quality: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -184,6 +194,7 @@ impl Default for AppSettings {
start_with_windows: false,
portable_mode: false,
legal_acknowledged: false,
+ last_download_options: LastDownloadOptions::default(),
}
}
}
diff --git a/src-tauri/src/commands/downloads.rs b/src-tauri/src/commands/downloads.rs
index 1c969942..dd099e2e 100644
--- a/src-tauri/src/commands/downloads.rs
+++ b/src-tauri/src/commands/downloads.rs
@@ -431,6 +431,66 @@ pub fn clear_download_log(download_id: u64) {
crate::core::download_log::clear(download_id);
}
+#[tauri::command]
+pub fn get_recovery_items() -> Vec<crate::core::recovery::RecoveryItem> {
+ crate::core::recovery::list()
+}
+
+#[tauri::command]
+pub fn discard_recovery() {
+ crate::core::recovery::clear_all();
+}
+
+#[tauri::command]
+pub async fn restore_recovery(
+ app: tauri::AppHandle,
+ state: tauri::State<'_, AppState>,
+) -> Result<u32, String> {
+ let items = crate::core::recovery::list();
+ crate::core::recovery::clear_all();
+ let mut restored: u32 = 0;
+ for item in items {
+ match download_from_url(
+ app.clone(),
+ state.clone(),
+ item.url,
+ item.output_dir,
+ item.download_mode,
+ item.quality,
+ item.format_id,
+ item.referer,
+ )
+ .await
+ {
+ Ok(_) => restored += 1,
+ Err(e) => tracing::warn!("[recovery] restore failed: {}", e),
+ }
+ }
+ Ok(restored)
+}
+
+#[tauri::command]
+pub fn parse_batch_file(path: String) -> Result<Vec<String>, String> {
+ let content = std::fs::read_to_string(&path)
+ .map_err(|e| format!("Read error: {}", e))?;
+ let mut urls = Vec::new();
+ for raw in content.lines() {
+ let line = raw.trim();
+ if line.is_empty() || line.starts_with('#') {
+ continue;
+ }
+ let candidate = line.split('|').next().unwrap_or(line).trim();
+ if candidate.starts_with("http://")
+ || candidate.starts_with("https://")
+ || candidate.starts_with("magnet:")
+ || candidate.starts_with("p2p:")
+ {
+ urls.push(candidate.to_string());
+ }
+ }
+ Ok(urls)
+}
+
#[tauri::command]
pub async fn get_queue_state(
state: tauri::State<'_, AppState>,
diff --git a/src-tauri/src/core/mod.rs b/src-tauri/src/core/mod.rs
index 95ee5c63..a0c076f1 100644
--- a/src-tauri/src/core/mod.rs
+++ b/src-tauri/src/core/mod.rs
@@ -19,4 +19,5 @@ pub mod download_log;
pub mod events;
pub mod path_limits;
pub mod queue;
+pub mod recovery;
pub mod url_parser;
diff --git a/src-tauri/src/core/queue.rs b/src-tauri/src/core/queue.rs
index b5e5c9b2..b4ca9f18 100644
--- a/src-tauri/src/core/queue.rs
+++ b/src-tauri/src/core/queue.rs
@@ -193,6 +193,17 @@ impl DownloadQueue {
from_hotkey,
torrent_id: None,
};
+ crate::core::recovery::persist(crate::core::recovery::RecoveryItem {
+ id: item.id,
+ url: item.url.clone(),
+ title: item.title.clone(),
+ platform: item.platform.clone(),
+ output_dir: item.output_dir.clone(),
+ download_mode: item.download_mode.clone(),
+ quality: item.quality.clone(),
+ format_id: item.format_id.clone(),
+ referer: item.referer.clone(),
+ });
self.items.push(item);
}
@@ -240,6 +251,7 @@ impl DownloadQueue {
item.file_path = file_path;
item.file_size_bytes = file_size_bytes;
item.speed_bytes_per_sec = 0.0;
+ crate::core::recovery::remove(id);
}
}
@@ -257,6 +269,7 @@ impl DownloadQueue {
item.file_size_bytes = file_size_bytes;
item.speed_bytes_per_sec = 0.0;
item.torrent_id = torrent_id;
+ crate::core::recovery::remove(id);
}
}
@@ -313,6 +326,14 @@ impl DownloadQueue {
/// Cancel an item. Returns the torrent_id if the item needs torrent cleanup (caller should delete from session).
pub fn cancel(&mut self, id: u64) -> (bool, Option<usize>) {
+ let result = self.cancel_inner(id);
+ if result.0 {
+ crate::core::recovery::remove(id);
+ }
+ result
+ }
+
+ fn cancel_inner(&mut self, id: u64) -> (bool, Option<usize>) {
if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
match &item.status {
QueueStatus::Active => {
@@ -377,6 +398,14 @@ impl DownloadQueue {
/// Remove an item. Returns the torrent_id if the item needs torrent cleanup (caller should delete from session).
pub fn remove(&mut self, id: u64) -> Option<Option<usize>> {
+ let result = self.remove_inner(id);
+ if result.is_some() {
+ crate::core::recovery::remove(id);
+ }
+ result
+ }
+
+ fn remove_inner(&mut self, id: u64) -> Option<Option<usize>> {
if let Some(pos) = self.items.iter().position(|i| i.id == id) {
let item = &self.items[pos];
if item.status == QueueStatus::Active {
@@ -400,6 +429,15 @@ impl DownloadQueue {
}
pub fn clear_finished(&mut self) {
+ let to_remove: Vec<u64> = self
+ .items
+ .iter()
+ .filter(|i| matches!(i.status, QueueStatus::Complete { .. } | QueueStatus::Error { .. }))
+ .map(|i| i.id)
+ .collect();
+ for id in &to_remove {
+ crate::core::recovery::remove(*id);
+ }
self.items.retain(|i| {
!matches!(
i.status,
diff --git a/src-tauri/src/core/recovery.rs b/src-tauri/src/core/recovery.rs
new file mode 100644
index 00000000..c0c90897
--- /dev/null
+++ b/src-tauri/src/core/recovery.rs
@@ -0,0 +1,119 @@
+use serde::{Deserialize, Serialize};
+use std::collections::HashMap;
+use std::io::Write;
+use std::path::PathBuf;
+use std::sync::{Mutex, OnceLock};
+
+const RECOVERY_FILE: &str = "recovery.json";
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct RecoveryItem {
+ pub id: u64,
+ pub url: String,
+ pub title: String,
+ pub platform: String,
+ pub output_dir: String,
+ #[serde(default)]
+ pub download_mode: Option<String>,
+ #[serde(default)]
+ pub quality: Option<String>,
+ #[serde(default)]
+ pub format_id: Option<String>,
+ #[serde(default)]
+ pub referer: Option<String>,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+struct RecoveryFile {
+ #[serde(default)]
+ items: Vec<RecoveryItem>,
+}
+
+static STORE: OnceLock<Mutex<HashMap<u64, RecoveryItem>>> = OnceLock::new();
+
+fn store() -> &'static Mutex<HashMap<u64, RecoveryItem>> {
+ STORE.get_or_init(|| Mutex::new(HashMap::new()))
+}
+
+fn file_path() -> Option<PathBuf> {
+ crate::core::paths::app_data_dir().map(|d| d.join(RECOVERY_FILE))
+}
+
+fn write_to_disk(items: &HashMap<u64, RecoveryItem>) {
+ let Some(path) = file_path() else { return };
+ let Some(parent) = path.parent() else { return };
+ if let Err(e) = std::fs::create_dir_all(parent) {
+ tracing::warn!("[recovery] create_dir_all failed: {}", e);
+ return;
+ }
+ let file_data = RecoveryFile {
+ items: items.values().cloned().collect(),
+ };
+ let serialized = match serde_json::to_string_pretty(&file_data) {
+ Ok(s) => s,
+ Err(e) => {
+ tracing::warn!("[recovery] serialize failed: {}", e);
+ return;
+ }
+ };
+ let tmp = path.with_extension("json.tmp");
+ let write_result = (|| -> std::io::Result<()> {
+ let mut f = std::fs::File::create(&tmp)?;
+ f.write_all(serialized.as_bytes())?;
+ f.sync_all()?;
+ Ok(())
+ })();
+ if let Err(e) = write_result {
+ tracing::warn!("[recovery] write tmp failed: {}", e);
+ let _ = std::fs::remove_file(&tmp);
+ return;
+ }
+ if let Err(e) = std::fs::rename(&tmp, &path) {
+ tracing::warn!("[recovery] rename failed: {}", e);
+ let _ = std::fs::remove_file(&tmp);
+ }
+}
+
+pub fn init_from_disk() {
+ let Some(path) = file_path() else { return };
+ let content = match std::fs::read_to_string(&path) {
+ Ok(c) => c,
+ Err(_) => return,
+ };
+ let parsed: RecoveryFile = match serde_json::from_str(&content) {
+ Ok(v) => v,
+ Err(e) => {
+ tracing::warn!("[recovery] parse failed: {}", e);
+ return;
+ }
+ };
+ let mut guard = store().lock().unwrap();
+ guard.clear();
+ for item in parsed.items {
+ guard.insert(item.id, item);
+ }
+}
+
+pub fn persist(item: RecoveryItem) {
+ let mut guard = store().lock().unwrap();
+ guard.insert(item.id, item);
+ write_to_disk(&guard);
+}
+
+pub fn remove(id: u64) {
+ let mut guard = store().lock().unwrap();
+ if guard.remove(&id).is_some() {
+ write_to_disk(&guard);
+ }
+}
+
+pub fn list() -> Vec<RecoveryItem> {
+ let guard = store().lock().unwrap();
+ guard.values().cloned().collect()
+}
+
+pub fn clear_all() {
+ let mut guard = store().lock().unwrap();
+ guard.clear();
+ write_to_disk(&guard);
+}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index c05132f9..8c38d66c 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -152,6 +152,21 @@ pub fn run() {
},
));
}
+ core::recovery::init_from_disk();
+ {
+ let pending = core::recovery::list();
+ if !pending.is_empty() {
+ let app_handle = app.handle().clone();
+ tauri::async_runtime::spawn(async move {
+ tokio::time::sleep(std::time::Duration::from_millis(800)).await;
+ let _ = tauri::Emitter::emit(
+ &app_handle,
+ "recovery-available",
+ serde_json::json!({ "count": pending.len() }),
+ );
+ });
+ }
+ }
tray::setup(app.handle())?;
hotkey::register_from_settings(app.handle());
if let Err(error) = native_host::ensure_registered() {
@@ -231,6 +246,10 @@ pub fn run() {
commands::downloads::clear_finished_downloads,
commands::downloads::get_download_log,
commands::downloads::clear_download_log,
+ commands::downloads::parse_batch_file,
+ commands::downloads::get_recovery_items,
+ commands::downloads::discard_recovery,
+ commands::downloads::restore_recovery,
commands::downloads::reveal_file,
commands::integration::register_external_frontend,
commands::settings::get_settings,