Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.
Rust downloadmanagerguihacktoberfesthomebrewlightweightlinuxlinux-distributionlocal-firstmacosmacos-packagemedia-toolboxopen-sourcerustsveltetauritrendingtrending-repositorieswindowswindows-desktopytdlp
Refactor code for improved readability and organization
Tonho623441b89749
diff --git a/src-tauri/omniget-core/src/core/clipboard.rs b/src-tauri/omniget-core/src/core/clipboard.rsindex 4f6f9034..a7cd0583 100644--- a/src-tauri/omniget-core/src/core/clipboard.rs+++ b/src-tauri/omniget-core/src/core/clipboard.rs@@ -140,10 +140,7 @@ async fn copy_file_linux(path: &str) -> anyhow::Result<()> {.map_err(|e| anyhow::anyhow!("{}", e))?;if let Ok(true) = wl_result {- tracing::info!(- "[clipboard] copied file to clipboard (wl-copy): {}",- path- );+ tracing::info!("[clipboard] copied file to clipboard (wl-copy): {}", path);return Ok(());}@@ -154,10 +151,7 @@ async fn copy_file_linux(path: &str) -> anyhow::Result<()> {#[cfg(target_os = "windows")]async fn copy_file_windows(path: &str) -> anyhow::Result<()> {- let ps_script = format!(- "Set-Clipboard -LiteralPath '{}'",- path.replace('\'', "''")- );+ let ps_script = format!("Set-Clipboard -LiteralPath '{}'", path.replace('\'', "''"));let output = tokio::task::spawn_blocking(move || {crate::core::process::std_command("powershell")@@ -169,7 +163,10 @@ async fn copy_file_windows(path: &str) -> anyhow::Result<()> {if !output.status.success() {let stderr = String::from_utf8_lossy(&output.stderr);- return Err(anyhow::anyhow!("PowerShell Set-Clipboard failed: {}", stderr));+ return Err(anyhow::anyhow!(+ "PowerShell Set-Clipboard failed: {}",+ stderr+ ));}tracing::info!("[clipboard] copied file to clipboard (Windows): {}", path);diff --git a/src-tauri/omniget-core/src/core/cookie_parser.rs b/src-tauri/omniget-core/src/core/cookie_parser.rsindex 98da566a..394e0560 100644--- a/src-tauri/omniget-core/src/core/cookie_parser.rs+++ b/src-tauri/omniget-core/src/core/cookie_parser.rs@@ -41,7 +41,11 @@ pub fn load_extension_cookies_for_domain(domain: &str) -> Option<Arc<reqwest::coreturn None;}- tracing::debug!("[cookies] loaded {} extension cookies for {}", count, domain);+ tracing::debug!(+ "[cookies] loaded {} extension cookies for {}",+ count,+ domain+ );Some(Arc::new(jar))}@@ -69,7 +73,11 @@ fn normalize_cookie_domains(url: &str) -> Vec<String> {let parts: Vec<&str> = host.split('.').collect();if parts.len() >= 2 {- domains.push(format!("{}.{}", parts[parts.len() - 2], parts[parts.len() - 1]));+ domains.push(format!(+ "{}.{}",+ parts[parts.len() - 2],+ parts[parts.len() - 1]+ ));}if host.contains("cdninstagram.com") || host.contains("fbcdn.net") {@@ -88,7 +96,8 @@ fn normalize_cookie_domains(url: &str) -> Vec<String> {if host.contains("tiktokcdn.com") || host.contains("tiktokv.com") {domains.push("tiktok.com".to_string());}- if host.contains("biliapi.net") || host.contains("bilivideo.com") || host.contains("hdslb.com") {+ if host.contains("biliapi.net") || host.contains("bilivideo.com") || host.contains("hdslb.com")+ {domains.push("bilibili.com".to_string());}if host.contains("googlevideo.com") || host.contains("ytimg.com") {@@ -217,7 +226,13 @@ pub fn parse_bearer_input(input: &str) -> String {if trimmed.starts_with('{') || trimmed.starts_with('[') {if let Ok(val) = serde_json::from_str::<serde_json::Value>(trimmed) {- for key in &["access_token", "token", "idToken", "bearerToken", "bearer_token"] {+ for key in &[+ "access_token",+ "token",+ "idToken",+ "bearerToken",+ "bearer_token",+ ] {if let Some(t) = val.get(*key).and_then(|v| v.as_str()) {return t.to_string();}@@ -245,7 +260,11 @@ pub fn parse_bearer_input(input: &str) -> String {cookie_obj.get("value").and_then(|v| v.as_str()),) {let lower = name.to_lowercase();- if lower.contains("token") || lower.contains("auth") || lower.contains("session") || lower.contains("sid") {+ if lower.contains("token")+ || lower.contains("auth")+ || lower.contains("session")+ || lower.contains("sid")+ {if value.len() > 20 {return value.to_string();}diff --git a/src-tauri/omniget-core/src/core/course_utils.rs b/src-tauri/omniget-core/src/core/course_utils.rsindex 9d5e007c..0049d780 100644--- a/src-tauri/omniget-core/src/core/course_utils.rs+++ b/src-tauri/omniget-core/src/core/course_utils.rs@@ -20,7 +20,10 @@ pub async fn save_description(dir: &str, content: &str, format: &str) -> anyhow:return Ok(());}- let wrapped = if ext == "html" && !content.trim_start().starts_with("<!") && !content.trim_start().starts_with("<html") {+ let wrapped = if ext == "html"+ && !content.trim_start().starts_with("<!")+ && !content.trim_start().starts_with("<html")+ {format!("<!DOCTYPE html>\n<html>\n<head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><style>body{{max-width:800px;margin:40px auto;padding:0 20px;font-family:system-ui,sans-serif;line-height:1.6;color:#333}}img{{max-width:100%;height:auto}}a{{color:#0066cc}}</style></head>\n<body>\n{}\n</body>\n</html>",contentdiff --git a/src-tauri/omniget-core/src/core/dependencies.rs b/src-tauri/omniget-core/src/core/dependencies.rsindex 9880b365..54202835 100644--- a/src-tauri/omniget-core/src/core/dependencies.rs+++ b/src-tauri/omniget-core/src/core/dependencies.rs@@ -4,8 +4,7 @@ use std::process::Stdio;use anyhow::anyhow;pub fn is_flatpak() -> bool {- std::path::Path::new("/.flatpak-info").exists()- || std::env::var("FLATPAK_ID").is_ok()+ std::path::Path::new("/.flatpak-info").exists() || std::env::var("FLATPAK_ID").is_ok()}fn managed_bin_dir() -> Option<PathBuf> {@@ -29,7 +28,11 @@ pub async fn find_tool(tool: &str) -> Option<PathBuf> {{let flatpak_path = PathBuf::from("/app/bin").join(&name);if flatpak_path.exists() {- tracing::debug!("[perf] find_tool({}) took {:?}", tool, _timer_start.elapsed());+ tracing::debug!(+ "[perf] find_tool({}) took {:?}",+ tool,+ _timer_start.elapsed()+ );return Some(flatpak_path);}}@@ -56,10 +59,18 @@ pub async fn find_tool(tool: &str) -> Option<PathBuf> {};if check.is_some() {- tracing::debug!("[perf] find_tool({}) took {:?}", tool, _timer_start.elapsed());+ tracing::debug!(+ "[perf] find_tool({}) took {:?}",+ tool,+ _timer_start.elapsed()+ );return Some(managed_path.clone());}- tracing::warn!("find_tool({}): binary exists at {} but failed to execute", tool, managed_path.display());+ tracing::warn!(+ "find_tool({}): binary exists at {} but failed to execute",+ tool,+ managed_path.display()+ );}}@@ -84,18 +95,30 @@ pub async fn find_tool(tool: &str) -> Option<PathBuf> {if result.is_some() {let abs = resolve_absolute_path(&name);- tracing::debug!("[perf] find_tool({}) took {:?}", tool, _timer_start.elapsed());+ tracing::debug!(+ "[perf] find_tool({}) took {:?}",+ tool,+ _timer_start.elapsed()+ );return Some(abs);}- tracing::debug!("[perf] find_tool({}) took {:?}", tool, _timer_start.elapsed());+ tracing::debug!(+ "[perf] find_tool({}) took {:?}",+ tool,+ _timer_start.elapsed()+ );None}/// Resolve a bare binary name to its absolute path via `where` (Windows)/// or `which` (Unix). Returns the original name as fallback.fn resolve_absolute_path(bin_name: &str) -> PathBuf {- let finder = if cfg!(target_os = "windows") { "where" } else { "which" };+ let finder = if cfg!(target_os = "windows") {+ "where"+ } else {+ "which"+ };if let Ok(output) = std::process::Command::new(finder).arg(bin_name).stdout(std::process::Stdio::piped())@@ -141,7 +164,11 @@ pub async fn check_version(tool: &str) -> Option<String> {};if !output.status.success() {- tracing::debug!("[perf] check_version({}) took {:?}", tool, _timer_start.elapsed());+ tracing::debug!(+ "[perf] check_version({}) took {:?}",+ tool,+ _timer_start.elapsed()+ );return None;}@@ -149,22 +176,20 @@ pub async fn check_version(tool: &str) -> Option<String> {let first_line = stdout.lines().next().unwrap_or("");let result = if tool == "ffmpeg" || tool == "ffprobe" {- first_line- .split_whitespace()- .nth(2)- .map(|s| s.to_string())+ first_line.split_whitespace().nth(2).map(|s| s.to_string())} else if tool == "yt-dlp" {Some(first_line.trim().to_string())} else if tool == "aria2c" {- first_line- .split_whitespace()- .nth(2)- .map(|s| s.to_string())+ first_line.split_whitespace().nth(2).map(|s| s.to_string())} else {Some(first_line.trim().to_string())};- tracing::debug!("[perf] check_version({}) took {:?}", tool, _timer_start.elapsed());+ tracing::debug!(+ "[perf] check_version({}) took {:?}",+ tool,+ _timer_start.elapsed()+ );result}@@ -193,8 +218,7 @@ pub async fn ensure_ffmpeg() -> anyhow::Result<PathBuf> {}async fn download_ffmpeg() -> anyhow::Result<PathBuf> {- let bin_dir = managed_bin_dir()- .ok_or_else(|| anyhow!("Could not determine data directory"))?;+ let bin_dir = managed_bin_dir().ok_or_else(|| anyhow!("Could not determine data directory"))?;std::fs::create_dir_all(&bin_dir)?;let ffmpeg_name = bin_name("ffmpeg");@@ -211,7 +235,11 @@ async fn download_ffmpeg() -> anyhow::Result<PathBuf> {tracing::info!("Downloading FFmpeg component from {}", url);let response = client.get(url).send().await?;if !response.status().is_success() {- return Err(anyhow!("Failed to download FFmpeg from {}: HTTP {}", url, response.status()));+ return Err(anyhow!(+ "Failed to download FFmpeg from {}: HTTP {}",+ url,+ response.status()+ ));}let temp_path = bin_dir.join(".ffmpeg_download.tmp");@@ -233,8 +261,12 @@ async fn download_ffmpeg() -> anyhow::Result<PathBuf> {}match archive_type {- ArchiveType::Zip => extract_zip_ffmpeg(&temp_path, &bin_dir, &ffmpeg_name, &ffprobe_name).await?,- ArchiveType::TarXz => extract_tar_xz_ffmpeg(&temp_path, &bin_dir, &ffmpeg_name, &ffprobe_name).await?,+ ArchiveType::Zip => {+ extract_zip_ffmpeg(&temp_path, &bin_dir, &ffmpeg_name, &ffprobe_name).await?+ }+ ArchiveType::TarXz => {+ extract_tar_xz_ffmpeg(&temp_path, &bin_dir, &ffmpeg_name, &ffprobe_name).await?+ }}let _ = std::fs::remove_file(&temp_path);@@ -302,7 +334,12 @@ async fn download_ffmpeg() -> anyhow::Result<PathBuf> {};match verify {Ok(s) if s.success() => {}- Ok(s) => return Err(anyhow!("FFmpeg installed but failed to execute (exit code {})", s)),+ Ok(s) => {+ return Err(anyhow!(+ "FFmpeg installed but failed to execute (exit code {})",+ s+ ))+ }Err(e) => return Err(anyhow!("FFmpeg installed but failed to execute: {}", e)),}@@ -323,8 +360,14 @@ fn ffmpeg_download_urls() -> Vec<(&'static str, ArchiveType)> {)]} else if cfg!(target_os = "macos") {vec![- ("https://evermeet.cx/ffmpeg/getrelease/zip", ArchiveType::Zip),- ("https://evermeet.cx/ffmpeg/getrelease/ffprobe/zip", ArchiveType::Zip),+ (+ "https://evermeet.cx/ffmpeg/getrelease/zip",+ ArchiveType::Zip,+ ),+ (+ "https://evermeet.cx/ffmpeg/getrelease/ffprobe/zip",+ ArchiveType::Zip,+ ),]} else if cfg!(target_arch = "aarch64") {vec![(@@ -353,8 +396,8 @@ async fn extract_zip_ffmpeg(tokio::task::spawn_blocking(move || {let file = std::fs::File::open(&archive_path).map_err(|e| anyhow!("Failed to open archive: {}", e))?;- let mut archive = zip::ZipArchive::new(file)- .map_err(|e| anyhow!("Failed to open zip: {}", e))?;+ let mut archive =+ zip::ZipArchive::new(file).map_err(|e| anyhow!("Failed to open zip: {}", e))?;let targets = [ffmpeg_name.as_str(), ffprobe_name.as_str()];@@ -400,16 +443,15 @@ async fn extract_tar_xz_ffmpeg(let mut archive = tar::Archive::new(decompressor);let targets = [ffmpeg_name.as_str(), ffprobe_name.as_str()];- for entry_result in archive.entries()+ for entry_result in archive+ .entries().map_err(|e| anyhow!("Failed to read tar entries: {}", e))?{- let mut entry = entry_result- .map_err(|e| anyhow!("Failed to read tar entry: {}", e))?;- let path = entry.path()+ let mut entry = entry_result.map_err(|e| anyhow!("Failed to read tar entry: {}", e))?;+ let path = entry+ .path().map_err(|e| anyhow!("Failed to read entry path: {}", e))?;- let file_name = path.file_name()- .and_then(|n| n.to_str())- .unwrap_or("");+ let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");for target in &targets {if file_name == *target {let dest = bin_dir.join(target);@@ -470,8 +512,7 @@ pub async fn ensure_js_runtime() -> Option<PathBuf> {}async fn download_deno() -> anyhow::Result<PathBuf> {- let bin_dir = managed_bin_dir()- .ok_or_else(|| anyhow!("Could not determine data directory"))?;+ let bin_dir = managed_bin_dir().ok_or_else(|| anyhow!("Could not determine data directory"))?;std::fs::create_dir_all(&bin_dir)?;let deno_name = bin_name("deno");@@ -503,7 +544,10 @@ async fn download_deno() -> anyhow::Result<PathBuf> {let response = client.get(url).send().await?;if !response.status().is_success() {- return Err(anyhow!("Failed to download Deno: HTTP {}", response.status()));+ return Err(anyhow!(+ "Failed to download Deno: HTTP {}",+ response.status()+ ));}let bytes = response.bytes().await?;@@ -513,8 +557,8 @@ async fn download_deno() -> anyhow::Result<PathBuf> {tokio::task::spawn_blocking(move || {let cursor = std::io::Cursor::new(&data);- let mut archive = zip::ZipArchive::new(cursor)- .map_err(|e| anyhow!("Failed to open Deno zip: {}", e))?;+ let mut archive =+ zip::ZipArchive::new(cursor).map_err(|e| anyhow!("Failed to open Deno zip: {}", e))?;for i in 0..archive.len() {let mut file = archive@@ -583,8 +627,7 @@ pub async fn ensure_aria2c() -> Option<PathBuf> {#[cfg(target_os = "windows")]async fn download_aria2c() -> anyhow::Result<PathBuf> {- let bin_dir = managed_bin_dir()- .ok_or_else(|| anyhow!("Could not determine data directory"))?;+ let bin_dir = managed_bin_dir().ok_or_else(|| anyhow!("Could not determine data directory"))?;std::fs::create_dir_all(&bin_dir)?;let aria2c_name = bin_name("aria2c");@@ -598,7 +641,10 @@ async fn download_aria2c() -> anyhow::Result<PathBuf> {let response = client.get(url).send().await?;if !response.status().is_success() {- return Err(anyhow!("Failed to download aria2c: HTTP {}", response.status()));+ return Err(anyhow!(+ "Failed to download aria2c: HTTP {}",+ response.status()+ ));}let bytes = response.bytes().await?;diff --git a/src-tauri/omniget-core/src/core/direct_downloader.rs b/src-tauri/omniget-core/src/core/direct_downloader.rsindex 2f1c71d4..fc5fccb5 100644--- a/src-tauri/omniget-core/src/core/direct_downloader.rs+++ b/src-tauri/omniget-core/src/core/direct_downloader.rs@@ -102,8 +102,7 @@ fn part_path_for(output: &Path) -> PathBuf {fn is_fatal_error(err: &anyhow::Error) -> bool {let msg = err.to_string();for code in &[- "HTTP 400", "HTTP 401", "HTTP 403", "HTTP 404", "HTTP 405",- "HTTP 410", "HTTP 451",+ "HTTP 400", "HTTP 401", "HTTP 403", "HTTP 404", "HTTP 405", "HTTP 410", "HTTP 451",] {if msg.contains(code) {return true;@@ -163,14 +162,20 @@ async fn download_attempt(let probe = probe_url(client, url, headers.as_ref()).await;- let use_chunked = probe.accept_ranges- && probe.content_length.is_some_and(|s| s > CHUNK_THRESHOLD);+ let use_chunked =+ probe.accept_ranges && probe.content_length.is_some_and(|s| s > CHUNK_THRESHOLD);if use_chunked {let total = probe.content_length.unwrap();let _ = std::fs::remove_file(&part_path);if let Err(chunked_err) = download_chunked(- client, url, &part_path, total, progress_tx, headers.clone(), cancel,+ client,+ url,+ &part_path,+ total,+ progress_tx,+ headers.clone(),+ cancel,).await{@@ -180,7 +185,14 @@ async fn download_attempt(let _ = std::fs::remove_file(&part_path);tracing::warn!("[direct] chunked failed, falling back: {}", chunked_err);download_single_stream(- client, url, &part_path, 0, probe.content_length, progress_tx, headers, cancel,+ client,+ url,+ &part_path,+ 0,+ probe.content_length,+ progress_tx,+ headers,+ cancel,).await?;}@@ -190,7 +202,14 @@ async fn download_attempt(_ => 0,};download_single_stream(- client, url, &part_path, existing, probe.content_length, progress_tx, headers, cancel,+ client,+ url,+ &part_path,+ existing,+ probe.content_length,+ progress_tx,+ headers,+ cancel,).await?;}@@ -253,8 +272,10 @@ async fn download_chunked(if ct.is_cancelled() {return Err(anyhow!("Download cancelled"));}- download_chunk(&client, &url, &path, start, end, &dl, total_size, &ptx, hdrs, &ct)- .await+ download_chunk(+ &client, &url, &path, start, end, &dl, total_size, &ptx, hdrs, &ct,+ )+ .await});}@@ -304,8 +325,16 @@ async fn download_chunk(}match download_chunk_attempt(- client, url, part_path, start, end, downloaded, total_size, progress_tx,- headers.clone(), cancel,+ client,+ url,+ part_path,+ start,+ end,+ downloaded,+ total_size,+ progress_tx,+ headers.clone(),+ cancel,).await{@@ -319,7 +348,10 @@ async fn download_chunk(downloaded.fetch_sub(chunk_bytes.min(current), Ordering::Relaxed);tracing::warn!("[direct] chunk {}-{} attempt {}/3 failed: {}",- start, end, attempt + 1, e+ start,+ end,+ attempt + 1,+ e);last_err = Some(e);}@@ -361,9 +393,7 @@ async fn download_chunk_attempt(}use std::io::{Seek, Write};- let mut file = std::fs::OpenOptions::new()- .write(true)- .open(part_path)?;+ let mut file = std::fs::OpenOptions::new().write(true).open(part_path)?;file.seek(std::io::SeekFrom::Start(start))?;let expected_size = end - start + 1;@@ -378,9 +408,8 @@ async fn download_chunk_attempt(let chunk_result = tokio::time::timeout(CHUNK_TIMEOUT, stream.next()).await;match chunk_result {Ok(Some(Ok(data))) => {- file.write_all(&data).map_err(|e| {- anyhow!("Write error (disk full?): {}", e)- })?;+ file.write_all(&data)+ .map_err(|e| anyhow!("Write error (disk full?): {}", e))?;chunk_written += data.len() as u64;let total_dl =downloaded.fetch_add(data.len() as u64, Ordering::Relaxed) + data.len() as u64;@@ -389,11 +418,7 @@ async fn download_chunk_attempt(}Ok(Some(Err(e))) => return Err(anyhow!("Chunk stream error: {}", e)),Ok(None) => break,- Err(_) => {- return Err(anyhow!(- "Chunk timeout — no data received for 30 seconds"- ))- }+ Err(_) => return Err(anyhow!("Chunk timeout — no data received for 30 seconds")),}}@@ -462,9 +487,7 @@ async fn download_single_stream(use std::io::Write;let raw_file = if offset > 0 {- std::fs::OpenOptions::new()- .append(true)- .open(part_path)?+ std::fs::OpenOptions::new().append(true).open(part_path)?} else {std::fs::File::create(part_path)?};@@ -484,9 +507,8 @@ async fn download_single_stream(let chunk_result = tokio::time::timeout(CHUNK_TIMEOUT, stream.next()).await;match chunk_result {Ok(Some(Ok(chunk))) => {- file.write_all(&chunk).map_err(|e| {- anyhow!("Write error (disk full?): {}", e)- })?;+ file.write_all(&chunk)+ .map_err(|e| anyhow!("Write error (disk full?): {}", e))?;downloaded += chunk.len() as u64;if let Some(total) = total_size {@@ -495,8 +517,7 @@ async fn download_single_stream(let _ = progress_tx.send(percent).await;}} else {- let percent =- (downloaded as f64 / (downloaded as f64 + 500_000.0)) * 100.0;+ let percent = (downloaded as f64 / (downloaded as f64 + 500_000.0)) * 100.0;let _ = progress_tx.send(percent.min(95.0)).await;}}diff --git a/src-tauri/omniget-core/src/core/errors.rs b/src-tauri/omniget-core/src/core/errors.rsindex a41d3ae0..f4f7cf71 100644--- a/src-tauri/omniget-core/src/core/errors.rs+++ b/src-tauri/omniget-core/src/core/errors.rs@@ -1,16 +1,25 @@pub fn classify_download_error(error: &str) -> (&str, &str) {let lower = error.to_lowercase();- if lower.contains("cookie") || lower.contains("login") || lower.contains("sign in")- || lower.contains("authentication") || lower.contains("403")+ if lower.contains("cookie")+ || lower.contains("login")+ || lower.contains("sign in")+ || lower.contains("authentication")+ || lower.contains("403"){return ("auth_required", "This content requires login. Install the browser extension and visit the site while logged in.");}- if lower.contains("captcha") || lower.contains("blocking") || lower.contains("rate limit")- || lower.contains("429") || lower.contains("too many")+ if lower.contains("captcha")+ || lower.contains("blocking")+ || lower.contains("rate limit")+ || lower.contains("429")+ || lower.contains("too many"){- return ("rate_limited", "Too many requests. Try again in a few minutes.");+ return (+ "rate_limited",+ "Too many requests. Try again in a few minutes.",+ );}if lower.contains("private") || lower.contains("restricted") || lower.contains("age") {@@ -18,25 +27,39 @@ pub fn classify_download_error(error: &str) -> (&str, &str) {}if lower.contains("downloaded file") && lower.contains("not found") {- return ("file_missing", "Downloaded file could not be located in the output folder.");+ return (+ "file_missing",+ "Downloaded file could not be located in the output folder.",+ );}- if lower.contains("not found") || lower.contains("404") || lower.contains("unavailable")+ if lower.contains("not found")+ || lower.contains("404")+ || lower.contains("unavailable")|| lower.contains("deleted"){return ("not_found", "Content not found or has been deleted.");}if lower.contains("ffmpeg") || lower.contains("mux") || lower.contains("merge") {- return ("ffmpeg_needed", "FFmpeg is required for this download. Install it from Settings.");+ return (+ "ffmpeg_needed",+ "FFmpeg is required for this download. Install it from Settings.",+ );}if lower.contains("yt-dlp") || lower.contains("ytdlp") || lower.contains("no downloader") {- return ("ytdlp_needed", "yt-dlp is required. Install it from Settings.");+ return (+ "ytdlp_needed",+ "yt-dlp is required. Install it from Settings.",+ );}if lower.contains("nsig") || lower.contains("signature") || lower.contains("cipher") {- return ("ytdlp_outdated", "yt-dlp needs updating. Restart the app to auto-update.");+ return (+ "ytdlp_outdated",+ "yt-dlp needs updating. Restart the app to auto-update.",+ );}("unknown", error)diff --git a/src-tauri/omniget-core/src/core/ffmpeg.rs b/src-tauri/omniget-core/src/core/ffmpeg.rsindex c272f6e6..6ad0967d 100644--- a/src-tauri/omniget-core/src/core/ffmpeg.rs+++ b/src-tauri/omniget-core/src/core/ffmpeg.rs@@ -135,7 +135,9 @@ pub async fn probe(path: &Path) -> anyhow::Result<MediaProbeInfo> {let json: serde_json::Value = serde_json::from_slice(&output.stdout).map_err(|e| anyhow!("Failed to parse ffprobe JSON: {}", e))?;- let format = json.get("format").ok_or_else(|| anyhow!("Missing 'format' field"))?;+ let format = json+ .get("format")+ .ok_or_else(|| anyhow!("Missing 'format' field"))?;let duration_seconds = format.get("duration")@@ -441,15 +443,8 @@ pub async fn embed_metadata(}let temp_dir = file.parent().unwrap_or(Path::new("."));- let ext = file- .extension()- .and_then(|e| e.to_str())- .unwrap_or("mp4");- let temp_output = temp_dir.join(format!(- ".omniget_meta_{}.{}",- uuid::Uuid::new_v4(),- ext- ));+ let ext = file.extension().and_then(|e| e.to_str()).unwrap_or("mp4");+ let temp_output = temp_dir.join(format!(".omniget_meta_{}.{}", uuid::Uuid::new_v4(), ext));let is_audio_only = matches!(ext.to_lowercase().as_str(),@@ -472,7 +467,11 @@ pub async fn embed_metadata(None};- let mut args: Vec<String> = vec!["-y".to_string(), "-i".to_string(), file.to_string_lossy().to_string()];+ let mut args: Vec<String> = vec![+ "-y".to_string(),+ "-i".to_string(),+ file.to_string_lossy().to_string(),+ ];if let Some(ref thumb) = thumbnail_path {args.extend(["-i".to_string(), thumb.to_string_lossy().to_string()]);@@ -481,10 +480,14 @@ pub async fn embed_metadata(if let Some(ref thumb) = thumbnail_path {let _ = thumb;args.extend([- "-map".to_string(), "0:a".to_string(),- "-map".to_string(), "1:v".to_string(),- "-c".to_string(), "copy".to_string(),- "-disposition:v:0".to_string(), "attached_pic".to_string(),+ "-map".to_string(),+ "0:a".to_string(),+ "-map".to_string(),+ "1:v".to_string(),+ "-c".to_string(),+ "copy".to_string(),+ "-disposition:v:0".to_string(),+ "attached_pic".to_string(),]);} else {args.extend(["-c".to_string(), "copy".to_string()]);diff --git a/src-tauri/omniget-core/src/core/hls_downloader.rs b/src-tauri/omniget-core/src/core/hls_downloader.rsindex 324e5f9f..66198606 100644--- a/src-tauri/omniget-core/src/core/hls_downloader.rs+++ b/src-tauri/omniget-core/src/core/hls_downloader.rs@@ -57,7 +57,17 @@ impl HlsDownloader {max_concurrent: u32,max_retries: u32,) -> anyhow::Result<HlsDownloadResult> {- self.download_with_quality(m3u8_url, output_path, referer, bytes_tx, cancel_token, max_concurrent, max_retries, None).await+ self.download_with_quality(+ m3u8_url,+ output_path,+ referer,+ bytes_tx,+ cancel_token,+ max_concurrent,+ max_retries,+ None,+ )+ .await}#[allow(clippy::too_many_arguments)]@@ -84,14 +94,30 @@ impl HlsDownloader {if let Some(variant) = select_best_variant(&master, max_height.unwrap_or(720)) {let variant_url = resolve_url(m3u8_url, &variant.uri);return self- .download_media_playlist(&variant_url, output_path, referer, bytes_tx, cancel_token, max_concurrent, max_retries)+ .download_media_playlist(+ &variant_url,+ output_path,+ referer,+ bytes_tx,+ cancel_token,+ max_concurrent,+ max_retries,+ ).await;}}if parse_media_playlist(m3u8_bytes).is_ok() {return self- .download_media_playlist(m3u8_url, output_path, referer, bytes_tx, cancel_token, max_concurrent, max_retries)+ .download_media_playlist(+ m3u8_url,+ output_path,+ referer,+ bytes_tx,+ cancel_token,+ max_concurrent,+ max_retries,+ ).await;}@@ -176,13 +202,21 @@ impl HlsDownloader {let writer_output = part_path.clone();let media_sequence = playlist.media_sequence;let writer = tokio::spawn(async move {- write_segments_ordered(seg_rx, &writer_output, &encryption, media_sequence, total_segments).await+ write_segments_ordered(+ seg_rx,+ &writer_output,+ &encryption,+ media_sequence,+ total_segments,+ )+ .await});let semaphore = Arc::new(Semaphore::new(max_concurrent as usize));let completed = Arc::new(AtomicUsize::new(0));let fail_token = cancel_token.child_token();- let errors: Arc<tokio::sync::Mutex<HashMap<String, u32>>> = Arc::new(tokio::sync::Mutex::new(HashMap::new()));+ let errors: Arc<tokio::sync::Mutex<HashMap<String, u32>>> =+ Arc::new(tokio::sync::Mutex::new(HashMap::new()));let segment_urls: Vec<(usize, String)> = playlist.segments@@ -207,7 +241,9 @@ impl HlsDownloader {if fail_ref.is_cancelled() {return;}- match download_segment_with_retry(client, &url, &referer, max_retries, fail_ref).await {+ match download_segment_with_retry(client, &url, &referer, max_retries, fail_ref)+ .await+ {Ok(data) => {if let Some(ref btx) = bytes_tx {let _ = btx.send(data.len() as u64);@@ -231,7 +267,8 @@ impl HlsDownloader {drop(seg_tx);- let writer_result = writer.await+ let writer_result = writer+ .await.map_err(|e| anyhow::anyhow!("Writer task panicked: {:?}", e))?;if cancel_token.is_cancelled() {@@ -342,11 +379,7 @@ struct EncryptionInfo {}fn select_best_variant(master: &MasterPlaylist, max_height: u32) -> Option<&VariantStream> {- let real: Vec<&VariantStream> = master- .variants- .iter()- .filter(|v| !v.is_i_frame)- .collect();+ let real: Vec<&VariantStream> = master.variants.iter().filter(|v| !v.is_i_frame).collect();if real.is_empty() {return None;@@ -400,10 +433,8 @@ async fn write_segments_ordered(total_segments: usize,) -> anyhow::Result<()> {use std::io::Write;- let mut file = std::io::BufWriter::with_capacity(- 256 * 1024,- std::fs::File::create(output_path)?,- );+ let mut file =+ std::io::BufWriter::with_capacity(256 * 1024, std::fs::File::create(output_path)?);let mut next_expected: usize = 0;let mut pending: BTreeMap<usize, Vec<u8>> = BTreeMap::new();@@ -475,7 +506,10 @@ async fn download_segment_with_retry(return Err(anyhow::anyhow!("HTTP {} downloading segment", code));}- resp.bytes().await.map(|b| b.to_vec()).map_err(|e| anyhow::anyhow!(e))+ resp.bytes()+ .await+ .map(|b| b.to_vec())+ .map_err(|e| anyhow::anyhow!(e))}).await;@@ -492,12 +526,12 @@ async fn download_segment_with_retry(if attempt < max_retries - 1 {let base = 500 * (attempt as u64 + 1);let jitter = rand::random::<u64>() % (base / 2 + 1);- tokio::time::sleep(std::time::Duration::from_millis(base + jitter))- .await;+ tokio::time::sleep(std::time::Duration::from_millis(base + jitter)).await;}}- Err(last_err- .unwrap_or_else(|| anyhow::anyhow!("Segment download failed after {} attempts", max_retries)))+ Err(last_err.unwrap_or_else(|| {+ anyhow::anyhow!("Segment download failed after {} attempts", max_retries)+ }))}fn compute_iv(encryption: &EncryptionInfo, segment_index: usize, media_sequence: u64) -> [u8; 16] {@@ -511,9 +545,7 @@ fn compute_iv(encryption: &EncryptionInfo, segment_index: usize, media_sequence:}fn parse_hex_iv(iv_str: &str) -> [u8; 16] {- let hex = iv_str- .trim_start_matches("0x")- .trim_start_matches("0X");+ let hex = iv_str.trim_start_matches("0x").trim_start_matches("0X");let mut result = [0u8; 16];let padded = format!("{:0>32}", hex);for i in 0..16 {diff --git a/src-tauri/omniget-core/src/core/http_client.rs b/src-tauri/omniget-core/src/core/http_client.rsindex dd9ce636..751c03f1 100644--- a/src-tauri/omniget-core/src/core/http_client.rs+++ b/src-tauri/omniget-core/src/core/http_client.rs@@ -13,10 +13,7 @@ pub fn init_proxy(proxy: ProxySettings) {}pub fn get_proxy_snapshot() -> ProxySettings {- GLOBAL_PROXY- .read()- .map(|g| g.clone())- .unwrap_or_default()+ GLOBAL_PROXY.read().map(|g| g.clone()).unwrap_or_default()}pub fn proxy_url() -> Option<String> {diff --git a/src-tauri/omniget-core/src/core/hwaccel.rs b/src-tauri/omniget-core/src/core/hwaccel.rsindex ea1b53c3..57e7b2ce 100644--- a/src-tauri/omniget-core/src/core/hwaccel.rs+++ b/src-tauri/omniget-core/src/core/hwaccel.rs@@ -19,12 +19,8 @@ const GPU_ENCODER_PRIORITY: &[&str] = &["h264_vaapi",];-const GPU_DECODER_PRIORITY: &[&str] = &[- "h264_cuvid",- "h264_qsv",- "h264_videotoolbox",- "h264_vaapi",-];+const GPU_DECODER_PRIORITY: &[&str] =+ &["h264_cuvid", "h264_qsv", "h264_videotoolbox", "h264_vaapi"];pub async fn detect_hwaccel() -> HwAccelInfo {HW_ACCEL_CACHE@@ -70,7 +66,13 @@ async fn query_codecs(flag: &str) -> Vec<String> {let text = String::from_utf8_lossy(&output.stdout);let gpu_keywords = [- "nvenc", "qsv", "amf", "videotoolbox", "vaapi", "cuvid", "cuda",+ "nvenc",+ "qsv",+ "amf",+ "videotoolbox",+ "vaapi",+ "cuvid",+ "cuda",];text.lines()diff --git a/src-tauri/omniget-core/src/core/media_processor.rs b/src-tauri/omniget-core/src/core/media_processor.rsindex 9e41f902..81369865 100644--- a/src-tauri/omniget-core/src/core/media_processor.rs+++ b/src-tauri/omniget-core/src/core/media_processor.rs@@ -19,7 +19,17 @@ impl MediaProcessor {Some(c) => crate::core::hls_downloader::HlsDownloader::with_client(c),None => crate::core::hls_downloader::HlsDownloader::new(),};- downloader.download(m3u8_url, output, referer, bytes_tx, cancel_token, max_concurrent, max_retries).await+ downloader+ .download(+ m3u8_url,+ output,+ referer,+ bytes_tx,+ cancel_token,+ max_concurrent,+ max_retries,+ )+ .await}#[allow(clippy::too_many_arguments)]@@ -38,7 +48,18 @@ impl MediaProcessor {Some(c) => crate::core::hls_downloader::HlsDownloader::with_client(c),None => crate::core::hls_downloader::HlsDownloader::new(),};- downloader.download_with_quality(m3u8_url, output, referer, bytes_tx, cancel_token, max_concurrent, max_retries, max_height).await+ downloader+ .download_with_quality(+ m3u8_url,+ output,+ referer,+ bytes_tx,+ cancel_token,+ max_concurrent,+ max_retries,+ max_height,+ )+ .await}pub async fn remux(input: &str, output: &str) -> anyhow::Result<()> {@@ -56,15 +77,10 @@ impl MediaProcessor {Ok(())}- pub async fn merge_audio_video(- video: &str,- audio: &str,- output: &str,- ) -> anyhow::Result<()> {+ pub async fn merge_audio_video(video: &str, audio: &str, output: &str) -> anyhow::Result<()> {let status = crate::core::process::command("ffmpeg").args([- "-y", "-i", video, "-i", audio, "-map", "0:v", "-map", "1:a", "-c", "copy",- output,+ "-y", "-i", video, "-i", audio, "-map", "0:v", "-map", "1:a", "-c", "copy", output,]).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::piped())diff --git a/src-tauri/omniget-core/src/core/mod.rs b/src-tauri/omniget-core/src/core/mod.rsindex 6621a8bc..1b2358f0 100644--- a/src-tauri/omniget-core/src/core/mod.rs+++ b/src-tauri/omniget-core/src/core/mod.rs@@ -1,19 +1,19 @@-pub mod registry;-pub mod events;pub mod clipboard;pub mod cookie_parser;pub mod course_utils;+pub mod dependencies;pub mod direct_downloader;+pub mod errors;+pub mod events;+pub mod ffmpeg;pub mod filename;pub mod hls_downloader;pub mod http_client;pub mod hwaccel;pub mod media_processor;pub mod paths;+pub mod pokemon_names;pub mod process;pub mod redirect;-pub mod dependencies;-pub mod errors;-pub mod ffmpeg;-pub mod pokemon_names;+pub mod registry;pub mod ytdlp;diff --git a/src-tauri/omniget-core/src/core/pokemon_names.rs b/src-tauri/omniget-core/src/core/pokemon_names.rsindex 8b5e3525..9d57e580 100644--- a/src-tauri/omniget-core/src/core/pokemon_names.rs+++ b/src-tauri/omniget-core/src/core/pokemon_names.rs@@ -1,64 +1,304 @@pub const POKEMON_NAMES: &[&str] = &[- "bulbasaur", "ivysaur", "venusaur", "charmander", "charmeleon",- "charizard", "squirtle", "wartortle", "blastoise", "caterpie",- "butterfree", "weedle", "beedrill", "pidgey", "pidgeotto",- "pidgeot", "rattata", "raticate", "spearow", "fearow",- "ekans", "arbok", "pikachu", "raichu", "sandshrew",- "sandslash", "nidoran", "nidorina", "nidoqueen", "nidorino",- "nidoking", "clefairy", "clefable", "vulpix", "ninetales",- "jigglypuff", "wigglytuff", "zubat", "golbat", "oddish",- "gloom", "vileplume", "paras", "parasect", "venonat",- "venomoth", "diglett", "dugtrio", "meowth", "persian",- "psyduck", "golduck", "mankey", "primeape", "growlithe",- "arcanine", "poliwag", "poliwhirl", "poliwrath", "abra",- "kadabra", "alakazam", "machop", "machoke", "machamp",- "bellsprout", "weepinbell", "victreebel", "tentacool", "tentacruel",- "geodude", "graveler", "golem", "ponyta", "rapidash",- "slowpoke", "slowbro", "magnemite", "magneton", "farfetchd",- "doduo", "dodrio", "seel", "dewgong", "grimer",- "muk", "shellder", "cloyster", "gastly", "haunter",- "gengar", "onix", "drowzee", "hypno", "krabby",- "kingler", "voltorb", "electrode", "exeggcute", "exeggutor",- "cubone", "marowak", "hitmonlee", "hitmonchan", "lickitung",- "koffing", "weezing", "rhyhorn", "rhydon", "chansey",- "tangela", "kangaskhan", "horsea", "seadra", "goldeen",- "seaking", "staryu", "starmie", "scyther", "jynx",- "electabuzz", "magmar", "pinsir", "tauros", "magikarp",- "gyarados", "lapras", "ditto", "eevee", "vaporeon",- "jolteon", "flareon", "porygon", "omanyte", "omastar",- "kabuto", "kabutops", "aerodactyl", "snorlax", "articuno",- "zapdos", "moltres", "dratini", "dragonair", "dragonite",- "mewtwo", "mew", "chikorita", "cyndaquil", "totodile",- "espeon", "umbreon", "murkrow", "misdreavus", "unown",- "wobbuffet", "girafarig", "pineco", "forretress", "dunsparce",- "steelix", "snubbull", "granbull", "scizor", "shuckle",- "heracross", "sneasel", "teddiursa", "ursaring", "slugma",- "magcargo", "swinub", "piloswine", "corsola", "remoraid",- "octillery", "delibird", "skarmory", "houndour", "houndoom",- "kingdra", "phanpy", "donphan", "porygon2", "stantler",- "smeargle", "tyrogue", "hitmontop", "smoochum", "elekid",- "magby", "miltank", "blissey", "raikou", "entei",- "suicune", "larvitar", "pupitar", "tyranitar", "lugia",- "celebi", "treecko", "torchic", "mudkip", "gardevoir",- "slakoth", "ninjask", "shedinja", "whismur", "loudred",- "exploud", "makuhita", "hariyama", "nosepass", "skitty",- "delcatty", "sableye", "mawile", "aron", "lairon",- "aggron", "meditite", "medicham", "electrike", "manectric",- "plusle", "minun", "volbeat", "illumise", "roselia",- "gulpin", "swalot", "carvanha", "sharpedo", "wailmer",- "wailord", "numel", "camerupt", "torkoal", "spoink",- "grumpig", "spinda", "trapinch", "vibrava", "flygon",- "cacnea", "cacturne", "swablu", "altaria", "zangoose",- "seviper", "lunatone", "solrock", "barboach", "whiscash",- "corphish", "crawdaunt", "baltoy", "claydol", "lileep",- "cradily", "anorith", "armaldo", "feebas", "milotic",- "castform", "kecleon", "shuppet", "banette", "duskull",- "dusclops", "tropius", "chimecho", "absol", "wynaut",- "snorunt", "glalie", "spheal", "sealeo", "walrein",- "clamperl", "huntail", "gorebyss", "relicanth", "luvdisc",- "bagon", "shelgon", "salamence", "beldum", "metang",- "metagross", "regirock", "regice", "registeel", "latias",- "latios", "kyogre", "groudon", "rayquaza", "jirachi",+ "bulbasaur",+ "ivysaur",+ "venusaur",+ "charmander",+ "charmeleon",+ "charizard",+ "squirtle",+ "wartortle",+ "blastoise",+ "caterpie",+ "butterfree",+ "weedle",+ "beedrill",+ "pidgey",+ "pidgeotto",+ "pidgeot",+ "rattata",+ "raticate",+ "spearow",+ "fearow",+ "ekans",+ "arbok",+ "pikachu",+ "raichu",+ "sandshrew",+ "sandslash",+ "nidoran",+ "nidorina",+ "nidoqueen",+ "nidorino",+ "nidoking",+ "clefairy",+ "clefable",+ "vulpix",+ "ninetales",+ "jigglypuff",+ "wigglytuff",+ "zubat",+ "golbat",+ "oddish",+ "gloom",+ "vileplume",+ "paras",+ "parasect",+ "venonat",+ "venomoth",+ "diglett",+ "dugtrio",+ "meowth",+ "persian",+ "psyduck",+ "golduck",+ "mankey",+ "primeape",+ "growlithe",+ "arcanine",+ "poliwag",+ "poliwhirl",+ "poliwrath",+ "abra",+ "kadabra",+ "alakazam",+ "machop",+ "machoke",+ "machamp",+ "bellsprout",+ "weepinbell",+ "victreebel",+ "tentacool",+ "tentacruel",+ "geodude",+ "graveler",+ "golem",+ "ponyta",+ "rapidash",+ "slowpoke",+ "slowbro",+ "magnemite",+ "magneton",+ "farfetchd",+ "doduo",+ "dodrio",+ "seel",+ "dewgong",+ "grimer",+ "muk",+ "shellder",+ "cloyster",+ "gastly",+ "haunter",+ "gengar",+ "onix",+ "drowzee",+ "hypno",+ "krabby",+ "kingler",+ "voltorb",+ "electrode",+ "exeggcute",+ "exeggutor",+ "cubone",+ "marowak",+ "hitmonlee",+ "hitmonchan",+ "lickitung",+ "koffing",+ "weezing",+ "rhyhorn",+ "rhydon",+ "chansey",+ "tangela",+ "kangaskhan",+ "horsea",+ "seadra",+ "goldeen",+ "seaking",+ "staryu",+ "starmie",+ "scyther",+ "jynx",+ "electabuzz",+ "magmar",+ "pinsir",+ "tauros",+ "magikarp",+ "gyarados",+ "lapras",+ "ditto",+ "eevee",+ "vaporeon",+ "jolteon",+ "flareon",+ "porygon",+ "omanyte",+ "omastar",+ "kabuto",+ "kabutops",+ "aerodactyl",+ "snorlax",+ "articuno",+ "zapdos",+ "moltres",+ "dratini",+ "dragonair",+ "dragonite",+ "mewtwo",+ "mew",+ "chikorita",+ "cyndaquil",+ "totodile",+ "espeon",+ "umbreon",+ "murkrow",+ "misdreavus",+ "unown",+ "wobbuffet",+ "girafarig",+ "pineco",+ "forretress",+ "dunsparce",+ "steelix",+ "snubbull",+ "granbull",+ "scizor",+ "shuckle",+ "heracross",+ "sneasel",+ "teddiursa",+ "ursaring",+ "slugma",+ "magcargo",+ "swinub",+ "piloswine",+ "corsola",+ "remoraid",+ "octillery",+ "delibird",+ "skarmory",+ "houndour",+ "houndoom",+ "kingdra",+ "phanpy",+ "donphan",+ "porygon2",+ "stantler",+ "smeargle",+ "tyrogue",+ "hitmontop",+ "smoochum",+ "elekid",+ "magby",+ "miltank",+ "blissey",+ "raikou",+ "entei",+ "suicune",+ "larvitar",+ "pupitar",+ "tyranitar",+ "lugia",+ "celebi",+ "treecko",+ "torchic",+ "mudkip",+ "gardevoir",+ "slakoth",+ "ninjask",+ "shedinja",+ "whismur",+ "loudred",+ "exploud",+ "makuhita",+ "hariyama",+ "nosepass",+ "skitty",+ "delcatty",+ "sableye",+ "mawile",+ "aron",+ "lairon",+ "aggron",+ "meditite",+ "medicham",+ "electrike",+ "manectric",+ "plusle",+ "minun",+ "volbeat",+ "illumise",+ "roselia",+ "gulpin",+ "swalot",+ "carvanha",+ "sharpedo",+ "wailmer",+ "wailord",+ "numel",+ "camerupt",+ "torkoal",+ "spoink",+ "grumpig",+ "spinda",+ "trapinch",+ "vibrava",+ "flygon",+ "cacnea",+ "cacturne",+ "swablu",+ "altaria",+ "zangoose",+ "seviper",+ "lunatone",+ "solrock",+ "barboach",+ "whiscash",+ "corphish",+ "crawdaunt",+ "baltoy",+ "claydol",+ "lileep",+ "cradily",+ "anorith",+ "armaldo",+ "feebas",+ "milotic",+ "castform",+ "kecleon",+ "shuppet",+ "banette",+ "duskull",+ "dusclops",+ "tropius",+ "chimecho",+ "absol",+ "wynaut",+ "snorunt",+ "glalie",+ "spheal",+ "sealeo",+ "walrein",+ "clamperl",+ "huntail",+ "gorebyss",+ "relicanth",+ "luvdisc",+ "bagon",+ "shelgon",+ "salamence",+ "beldum",+ "metang",+ "metagross",+ "regirock",+ "regice",+ "registeel",+ "latias",+ "latios",+ "kyogre",+ "groudon",+ "rayquaza",+ "jirachi","deoxys",];diff --git a/src-tauri/omniget-core/src/core/redirect.rs b/src-tauri/omniget-core/src/core/redirect.rsindex 9d1bd07b..81a9c176 100644--- a/src-tauri/omniget-core/src/core/redirect.rs+++ b/src-tauri/omniget-core/src/core/redirect.rs@@ -1,10 +1,7 @@use anyhow::anyhow;pub async fn resolve_redirect(client: &reqwest::Client, url: &str) -> anyhow::Result<String> {- let response = client- .get(url)- .send()- .await?;+ let response = client.get(url).send().await?;let final_url = response.url().to_string();diff --git a/src-tauri/omniget-core/src/core/registry.rs b/src-tauri/omniget-core/src/core/registry.rsindex c1a26216..8651208f 100644--- a/src-tauri/omniget-core/src/core/registry.rs+++ b/src-tauri/omniget-core/src/core/registry.rs@@ -18,10 +18,7 @@ impl PlatformRegistry {}pub fn find_platform(&self, url: &str) -> Option<Arc<dyn PlatformDownloader>> {- self.platforms- .iter()- .find(|p| p.can_handle(url))- .cloned()+ self.platforms.iter().find(|p| p.can_handle(url)).cloned()}}diff --git a/src-tauri/omniget-core/src/core/ytdlp.rs b/src-tauri/omniget-core/src/core/ytdlp.rsindex c8c16957..797777ab 100644--- a/src-tauri/omniget-core/src/core/ytdlp.rs+++ b/src-tauri/omniget-core/src/core/ytdlp.rs@@ -41,7 +41,10 @@ fn ext_referer_for_url(url: &str) -> Option<String> {}fn cookies_from_browser_setting() -> String {- COOKIES_FROM_BROWSER_FN.get().map(|f| f()).unwrap_or_default()+ COOKIES_FROM_BROWSER_FN+ .get()+ .map(|f| f())+ .unwrap_or_default()}pub fn ext_cookie_path() -> PathBuf {@@ -70,12 +73,10 @@ fn global_cookie_file() -> Option<String> {static YTDLP_UPDATING: AtomicBool = AtomicBool::new(false);static YTDLP_UPDATE_CHECKED: AtomicBool = AtomicBool::new(false);-static YTDLP_PATH_CACHE: std::sync::RwLock<Option<Option<PathBuf>>> =- std::sync::RwLock::new(None);+static YTDLP_PATH_CACHE: std::sync::RwLock<Option<Option<PathBuf>>> = std::sync::RwLock::new(None);static FFMPEG_LOCATION_CACHE: std::sync::RwLock<Option<Option<String>>> =std::sync::RwLock::new(None);-static JS_RUNTIME_CACHE: std::sync::RwLock<Option<Option<String>>> =- std::sync::RwLock::new(None);+static JS_RUNTIME_CACHE: std::sync::RwLock<Option<Option<String>>> = std::sync::RwLock::new(None);static RATE_LIMIT_429_COUNT: AtomicU64 = AtomicU64::new(0);static RATE_LIMIT_429_LAST_TS: AtomicU64 = AtomicU64::new(0);static COOKIE_ERROR_FLAG: AtomicBool = AtomicBool::new(false);@@ -132,7 +133,6 @@ pub fn reset_js_runtime_cache() {}}-pub async fn check_ytdlp_update(ytdlp: &Path) -> anyhow::Result<bool> {if YTDLP_UPDATE_CHECKED.swap(true, Ordering::Relaxed) {return Ok(false);@@ -262,7 +262,11 @@ pub async fn find_ytdlp() -> Option<PathBuf> {/// Resolve a bare binary name to its absolute path via `where` (Windows)/// or `which` (Unix). Returns the original name as fallback.fn resolve_absolute_path(bin_name: &str) -> PathBuf {- let finder = if cfg!(target_os = "windows") { "where" } else { "which" };+ let finder = if cfg!(target_os = "windows") {+ "where"+ } else {+ "which"+ };if let Ok(output) = std::process::Command::new(finder).arg(bin_name).stdout(std::process::Stdio::piped())@@ -287,7 +291,10 @@ pub async fn find_ytdlp_cached() -> Option<PathBuf> {if let Some(ref cached) = *cache {if let Some(ref path) = cached {if path.exists() {- tracing::debug!("[perf] find_ytdlp_cached (hit): {:?}", _timer_start.elapsed());+ tracing::debug!(+ "[perf] find_ytdlp_cached (hit): {:?}",+ _timer_start.elapsed()+ );return cached.clone();}tracing::warn!("[ytdlp] cached path no longer exists: {}", path.display());@@ -300,7 +307,10 @@ pub async fn find_ytdlp_cached() -> Option<PathBuf> {if let Ok(mut cache) = YTDLP_PATH_CACHE.write() {*cache = Some(result.clone());}- tracing::debug!("[perf] find_ytdlp_cached (miss): {:?}", _timer_start.elapsed());+ tracing::debug!(+ "[perf] find_ytdlp_cached (miss): {:?}",+ _timer_start.elapsed()+ );result}@@ -342,7 +352,10 @@ pub async fn ensure_ytdlp() -> anyhow::Result<PathBuf> {return Ok(path);}Err(e) => {- tracing::warn!("[ytdlp] failed to download managed binary, falling back to system: {}", e);+ tracing::warn!(+ "[ytdlp] failed to download managed binary, falling back to system: {}",+ e+ );}}}@@ -523,7 +536,8 @@ async fn find_ffmpeg_location_cached() -> Option<String> {if let Ok(cache) = FFMPEG_LOCATION_CACHE.read() {if let Some(ref cached) = *cache {if let Some(ref dir) = cached {- let check_path = std::path::Path::new(dir).join(crate::core::dependencies::bin_name("ffmpeg"));+ let check_path =+ std::path::Path::new(dir).join(crate::core::dependencies::bin_name("ffmpeg"));if check_path.exists() {return cached.clone();}@@ -565,14 +579,22 @@ fn extension_cookie_file() -> Option<std::path::PathBuf> {/// own, so we locate the binary and pass it via `--js-runtimes runtime:path`.fn detect_js_runtime() -> Option<String> {let runtimes: &[(&str, &str)] = if cfg!(target_os = "windows") {- &[("node", "node.exe"), ("deno", "deno.exe"), ("bun", "bun.exe")]+ &[+ ("node", "node.exe"),+ ("deno", "deno.exe"),+ ("bun", "bun.exe"),+ ]} else {&[("node", "node"), ("deno", "deno"), ("bun", "bun")]};// Try system PATH via `where` (Windows) or `which` (Unix).for &(runtime, bin) in runtimes {- let finder = if cfg!(target_os = "windows") { "where" } else { "which" };+ let finder = if cfg!(target_os = "windows") {+ "where"+ } else {+ "which"+ };if let Ok(output) = crate::core::process::std_command(finder).arg(bin).stdout(std::process::Stdio::piped())@@ -781,7 +803,11 @@ pub async fn get_video_info(}let stderr = String::from_utf8_lossy(&result.stderr).to_string();- tracing::debug!("[yt-dlp info] stderr ({} bytes): {}", stderr.len(), stderr.trim());+ tracing::debug!(+ "[yt-dlp info] stderr ({} bytes): {}",+ stderr.len(),+ stderr.trim()+ );let stderr_lower = stderr.to_lowercase();if stderr_lower.contains("http error 429") {rate_limit_429_increment();@@ -887,7 +913,10 @@ pub async fn get_playlist_info(player_client);}- return Err(anyhow!("yt-dlp playlist failed: {}", extract_error_message(&stderr)));+ return Err(anyhow!(+ "yt-dlp playlist failed: {}",+ extract_error_message(&stderr)+ ));}let stdout = String::from_utf8_lossy(&output.stdout);@@ -1036,10 +1065,7 @@ pub async fn download_video(} else {tracing::warn!("[yt-dlp] ffmpeg not available, using fallback format selector");match quality_height {- Some(h) if h > 0 => format!(- "b[height<={}]/bv*[height<={}]/b",- h, h- ),+ Some(h) if h > 0 => format!("b[height<={}]/bv*[height<={}]/b", h, h),_ => "b/bv*".to_string(),}}@@ -1177,8 +1203,7 @@ pub async fn download_video(base_args.push("--windows-filenames".to_string());}- let should_download_subs =- download_subtitles && rate_limit_429_count() < 2;+ let should_download_subs = download_subtitles && rate_limit_429_count() < 2;let subtitle_args = if should_download_subs {vec!["--write-sub".to_string(),@@ -1308,10 +1333,8 @@ pub async fn download_video(.and_then(|e| e.to_str()).unwrap_or("").to_lowercase();- let is_subtitle = matches!(- ext.as_str(),- "vtt" | "srt" | "ass" | "ssa" | "sub" | "lrc"- );+ let is_subtitle =+ matches!(ext.as_str(), "vtt" | "srt" | "ass" | "ssa" | "sub" | "lrc");if !is_subtitle {phase += 1;let mut guard = captured_path_writer.lock().unwrap();@@ -1584,7 +1607,9 @@ pub async fn download_video(|| stderr_lower.contains("postprocessing"){if format_already_simplified {- tracing::warn!("[yt-dlp] format/postprocessing error after simplification, giving up");+ tracing::warn!(+ "[yt-dlp] format/postprocessing error after simplification, giving up"+ );break;}diff --git a/src-tauri/omniget-core/src/lib.rs b/src-tauri/omniget-core/src/lib.rsindex eb471e5d..db8f57bb 100644--- a/src-tauri/omniget-core/src/lib.rs+++ b/src-tauri/omniget-core/src/lib.rs@@ -1,5 +1,4 @@-pub mod platforms;-pub mod models;pub mod core;pub mod fs_paths;-+pub mod models;+pub mod platforms;diff --git a/src-tauri/omniget-core/src/models/media.rs b/src-tauri/omniget-core/src/models/media.rsindex 67e36d02..4d637795 100644--- a/src-tauri/omniget-core/src/models/media.rs+++ b/src-tauri/omniget-core/src/models/media.rs@@ -1,5 +1,5 @@-use std::collections::HashMap;use serde::{Deserialize, Serialize};+use std::collections::HashMap;use std::path::PathBuf;use crate::platforms::Platform;diff --git a/src-tauri/omniget-core/src/models/mod.rs b/src-tauri/omniget-core/src/models/mod.rsindex 1fb7ea80..fb97db1d 100644--- a/src-tauri/omniget-core/src/models/mod.rs+++ b/src-tauri/omniget-core/src/models/mod.rs@@ -1,3 +1,3 @@-pub mod media;pub mod download;+pub mod media;pub mod settings;diff --git a/src-tauri/omniget-core/src/platforms/mod.rs b/src-tauri/omniget-core/src/platforms/mod.rsindex db0c0010..4bf47da4 100644--- a/src-tauri/omniget-core/src/platforms/mod.rs+++ b/src-tauri/omniget-core/src/platforms/mod.rs@@ -1,8 +1,8 @@pub mod traits;+use serde::{Deserialize, Serialize};use std::fmt;use std::str::FromStr;-use serde::{Deserialize, Serialize};#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "lowercase")]@@ -84,9 +84,8 @@ impl Platform {let parsed = url::Url::parse(url_str).ok()?;let host = parsed.host_str()?.to_lowercase();- let matches = |domain: &str| -> bool {- host == domain || host.ends_with(&format!(".{}", domain))- };+ let matches =+ |domain: &str| -> bool { host == domain || host.ends_with(&format!(".{}", domain)) };if matches("hotmart.com") {Some(Platform::Hotmart)@@ -96,7 +95,11 @@ impl Platform {Some(Platform::Instagram)} else if matches("tiktok.com") {Some(Platform::TikTok)- } else if matches("twitter.com") || matches("x.com") || matches("vxtwitter.com") || matches("fixvx.com") {+ } else if matches("twitter.com")+ || matches("x.com")+ || matches("vxtwitter.com")+ || matches("fixvx.com")+ {Some(Platform::Twitter)} else if matches("reddit.com") || host == "v.redd.it" || host == "redd.it" {Some(Platform::Reddit)diff --git a/src-tauri/omniget-plugin-sdk/src/lib.rs b/src-tauri/omniget-plugin-sdk/src/lib.rsindex 499c0b1c..38aade5d 100644--- a/src-tauri/omniget-plugin-sdk/src/lib.rs+++ b/src-tauri/omniget-plugin-sdk/src/lib.rs@@ -1,9 +1,9 @@+mod host;mod manifest;mod plugin;-mod host;+pub use host::*;pub use manifest::*;pub use plugin::*;-pub use host::*;pub const ABI_VERSION: u32 = 1;diff --git a/src-tauri/omniget-plugin-sdk/src/plugin.rs b/src-tauri/omniget-plugin-sdk/src/plugin.rsindex 95885cc9..48ca4b74 100644--- a/src-tauri/omniget-plugin-sdk/src/plugin.rs+++ b/src-tauri/omniget-plugin-sdk/src/plugin.rs@@ -13,7 +13,9 @@ pub trait OmnigetPlugin: Send + Sync {&self,command: String,args: serde_json::Value,- ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<serde_json::Value, String>> + Send + 'static>>;+ ) -> std::pin::Pin<+ Box<dyn std::future::Future<Output = Result<serde_json::Value, String>> + Send + 'static>,+ >;fn commands(&self) -> Vec<String>;}diff --git a/src-tauri/src/commands/auth_webview.rs b/src-tauri/src/commands/auth_webview.rsindex 81959159..00186e7f 100644--- a/src-tauri/src/commands/auth_webview.rs+++ b/src-tauri/src/commands/auth_webview.rs@@ -69,14 +69,11 @@ pub async fn open_auth_webview(let success_pattern = request.success_url_contains.clone();let tx_nav = tx.clone();- let mut builder = tauri::WebviewWindowBuilder::new(- &app,- &label,- tauri::WebviewUrl::External(parsed_url),- )- .title(&request.title)- .inner_size(width, height)- .center();+ let mut builder =+ tauri::WebviewWindowBuilder::new(&app, &label, tauri::WebviewUrl::External(parsed_url))+ .title(&request.title)+ .inner_size(width, height)+ .center();if let Some(ref script) = request.initialization_script {builder = builder.initialization_script(script);@@ -147,16 +144,27 @@ pub async fn open_auth_webview(tracing::info!("[auth_webview] signal: {}",- if final_url == "__CLOSE_REQUESTED__" { "user closed window" } else { &final_url }+ if final_url == "__CLOSE_REQUESTED__" {+ "user closed window"+ } else {+ &final_url+ });let default_domain = request.cookie_domains.first().cloned().unwrap_or_default();let cookies = if let Some(ref target_cookie) = request.wait_for_cookie {- poll_for_cookie(&webview_window, &default_domain, &request.cookie_domains, target_cookie).await+ poll_for_cookie(+ &webview_window,+ &default_domain,+ &request.cookie_domains,+ target_cookie,+ )+ .await} else {tokio::time::sleep(std::time::Duration::from_secs(2)).await;- let cookies = extract_cookies(&webview_window, &default_domain, &request.cookie_domains).await;+ let cookies =+ extract_cookies(&webview_window, &default_domain, &request.cookie_domains).await;if cookies.is_empty() {tracing::warn!("[auth_webview] no cookies on first attempt, retrying in 3s...");tokio::time::sleep(std::time::Duration::from_secs(3)).await;@@ -196,13 +204,18 @@ async fn poll_for_cookie(attempt += 1;let elapsed = start.elapsed();if elapsed > timeout {- tracing::warn!("[auth_webview] cookie polling timed out after {:.1}s", elapsed.as_secs_f64());+ tracing::warn!(+ "[auth_webview] cookie polling timed out after {:.1}s",+ elapsed.as_secs_f64()+ );return extract_cookies(window, default_domain, domains).await;}let cookies = extract_cookies(window, default_domain, domains).await;- let found = cookies.iter().any(|c| c.name.to_lowercase() == target_lower);+ let found = cookies+ .iter()+ .any(|c| c.name.to_lowercase() == target_lower);if found {tracing::info!("[auth_webview] target cookie '{}' found after {:.1}s ({} attempts, {} total cookies)",@@ -383,7 +396,11 @@ async fn extract_cookies_native(for uri in &uris {match extract_cookies_for_uri(window, uri).await {Ok(batch) => {- tracing::debug!("[auth_webview] native cookies from {}: {}", uri, batch.len());+ tracing::debug!(+ "[auth_webview] native cookies from {}: {}",+ uri,+ batch.len()+ );for c in batch {if !all_cookies.iter()@@ -411,85 +428,83 @@ async fn extract_cookies_for_uri(let uri_owned = uri.to_string();window- .with_webview(move |platform_webview| {- unsafe {- use webview2_com::Microsoft::Web::WebView2::Win32::*;- use windows::core::{Interface, HSTRING, PCWSTR, PWSTR, BOOL};-- let core = match platform_webview.controller().CoreWebView2() {- Ok(c) => c,- Err(_) => {- let _ = tx.send(Vec::new());- return;- }- };- let core2: ICoreWebView2_2 = match core.cast() {- Ok(c) => c,- Err(_) => {- let _ = tx.send(Vec::new());- return;- }- };- let manager = match core2.CookieManager() {- Ok(m) => m,- Err(_) => {- let _ = tx.send(Vec::new());- return;- }- };-- let uri_hstring = HSTRING::from(uri_owned);-- let _ = manager.GetCookies(- PCWSTR::from_raw(uri_hstring.as_ptr()),- &webview2_com::GetCookiesCompletedHandler::create(Box::new(- move |hr, cookie_list| {- let mut cookies = Vec::new();- if hr.is_ok() {- if let Some(list) = cookie_list {- let mut count: u32 = 0;- let _ = list.Count(&mut count);- for i in 0..count {- if let Ok(cookie) = list.GetValueAtIndex(i) {- let mut name_pw = PWSTR::null();- let mut value_pw = PWSTR::null();- let mut domain_pw = PWSTR::null();- let mut path_pw = PWSTR::null();- let mut http_only_b = BOOL::default();- let mut secure_b = BOOL::default();-- let _ = cookie.Name(&mut name_pw);- let _ = cookie.Value(&mut value_pw);- let _ = cookie.Domain(&mut domain_pw);- let _ = cookie.Path(&mut path_pw);- let _ = cookie.IsHttpOnly(&mut http_only_b);- let _ = cookie.IsSecure(&mut secure_b);-- let name = name_pw.to_string().unwrap_or_default();- let value = value_pw.to_string().unwrap_or_default();- let domain = domain_pw.to_string().unwrap_or_default();- let path = path_pw.to_string().unwrap_or_default();-- if !name.is_empty() && !value.is_empty() {- cookies.push(AuthCookie {- name,- value,- domain,- path,- http_only: http_only_b.as_bool(),- secure: secure_b.as_bool(),- });- }+ .with_webview(move |platform_webview| unsafe {+ use webview2_com::Microsoft::Web::WebView2::Win32::*;+ use windows::core::{Interface, BOOL, HSTRING, PCWSTR, PWSTR};++ let core = match platform_webview.controller().CoreWebView2() {+ Ok(c) => c,+ Err(_) => {+ let _ = tx.send(Vec::new());+ return;+ }+ };+ let core2: ICoreWebView2_2 = match core.cast() {+ Ok(c) => c,+ Err(_) => {+ let _ = tx.send(Vec::new());+ return;+ }+ };+ let manager = match core2.CookieManager() {+ Ok(m) => m,+ Err(_) => {+ let _ = tx.send(Vec::new());+ return;+ }+ };++ let uri_hstring = HSTRING::from(uri_owned);++ let _ = manager.GetCookies(+ PCWSTR::from_raw(uri_hstring.as_ptr()),+ &webview2_com::GetCookiesCompletedHandler::create(Box::new(+ move |hr, cookie_list| {+ let mut cookies = Vec::new();+ if hr.is_ok() {+ if let Some(list) = cookie_list {+ let mut count: u32 = 0;+ let _ = list.Count(&mut count);+ for i in 0..count {+ if let Ok(cookie) = list.GetValueAtIndex(i) {+ let mut name_pw = PWSTR::null();+ let mut value_pw = PWSTR::null();+ let mut domain_pw = PWSTR::null();+ let mut path_pw = PWSTR::null();+ let mut http_only_b = BOOL::default();+ let mut secure_b = BOOL::default();++ let _ = cookie.Name(&mut name_pw);+ let _ = cookie.Value(&mut value_pw);+ let _ = cookie.Domain(&mut domain_pw);+ let _ = cookie.Path(&mut path_pw);+ let _ = cookie.IsHttpOnly(&mut http_only_b);+ let _ = cookie.IsSecure(&mut secure_b);++ let name = name_pw.to_string().unwrap_or_default();+ let value = value_pw.to_string().unwrap_or_default();+ let domain = domain_pw.to_string().unwrap_or_default();+ let path = path_pw.to_string().unwrap_or_default();++ if !name.is_empty() && !value.is_empty() {+ cookies.push(AuthCookie {+ name,+ value,+ domain,+ path,+ http_only: http_only_b.as_bool(),+ secure: secure_b.as_bool(),+ });}}}}- let _ = tx.send(cookies);- Ok(())- },- )),- );- }+ }+ let _ = tx.send(cookies);+ Ok(())+ },+ )),+ );}).map_err(|e| format!("{}", e))?;diff --git a/src-tauri/src/commands/autostart.rs b/src-tauri/src/commands/autostart.rsindex 467e09d9..73d98225 100644--- a/src-tauri/src/commands/autostart.rs+++ b/src-tauri/src/commands/autostart.rs@@ -11,14 +11,24 @@ const REG_KEY: &str = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run";const APP_NAME: &str = "OmniGet";pub fn apply_autostart(enabled: bool) -> Result<(), String> {- if std::env::var("OMNIGET_PORTABLE").is_ok() { return Ok(()); }+ if std::env::var("OMNIGET_PORTABLE").is_ok() {+ return Ok(());+ }#[cfg(windows)]{if enabled {- let exe = std::env::current_exe()- .map_err(|e| format!("Failed to get exe path: {e}"))?;+ let exe =+ std::env::current_exe().map_err(|e| format!("Failed to get exe path: {e}"))?;let output = std::process::Command::new("reg")- .args(["add", REG_KEY, "/v", APP_NAME, "/d", &exe.to_string_lossy(), "/f"])+ .args([+ "add",+ REG_KEY,+ "/v",+ APP_NAME,+ "/d",+ &exe.to_string_lossy(),+ "/f",+ ]).creation_flags(CREATE_NO_WINDOW).output().map_err(|e| format!("reg add failed: {e}"))?;@@ -59,8 +69,7 @@ pub fn set_autostart(app: tauri::AppHandle, enabled: bool) -> Result<(), String>apply_autostart(enabled)?;let mut current = crate::storage::config::load_settings(&app);current.start_with_windows = enabled;- crate::storage::config::save_settings(&app, ¤t)- .map_err(|e| format!("Save: {e}"))?;+ crate::storage::config::save_settings(&app, ¤t).map_err(|e| format!("Save: {e}"))?;Ok(())}diff --git a/src-tauri/src/commands/downloads.rs b/src-tauri/src/commands/downloads.rsindex ef143a93..9ae18dcc 100644--- a/src-tauri/src/commands/downloads.rs+++ b/src-tauri/src/commands/downloads.rs@@ -48,7 +48,11 @@ pub async fn detect_platform(url: String) -> Result<PlatformInfo, String> {.map(|u| u.scheme() == "http" || u.scheme() == "https").unwrap_or(false);let result = Ok(PlatformInfo {- platform: if is_valid_url { "generic".to_string() } else { "unknown".to_string() },+ platform: if is_valid_url {+ "generic".to_string()+ } else {+ "unknown".to_string()+ },supported: is_valid_url,content_id: None,content_type: None,@@ -247,7 +251,9 @@ pub async fn cancel_generic_download(};if let Some(tid) = seeding_torrent_id {if let Some(session) = state.torrent_session.lock().await.as_ref() {- let _ = session.delete(librqbit::api::TorrentIdOrHash::Id(tid), false).await;+ let _ = session+ .delete(librqbit::api::TorrentIdOrHash::Id(tid), false)+ .await;}}if let Some(s) = state_to_emit {@@ -268,7 +274,11 @@ pub async fn pause_download(let (state_to_emit, torrent_id) = {let mut q = state.download_queue.lock().await;if q.pause(download_id) {- let tid = q.items.iter().find(|i| i.id == download_id).and_then(|i| i.torrent_id);+ let tid = q+ .items+ .iter()+ .find(|i| i.id == download_id)+ .and_then(|i| i.torrent_id);(Some(q.get_state()), tid)} else {(None, None)@@ -299,7 +309,11 @@ pub async fn resume_download(let (state_to_emit, torrent_id) = {let mut q = state.download_queue.lock().await;if q.resume(download_id) {- let tid = q.items.iter().find(|i| i.id == download_id).and_then(|i| i.torrent_id);+ let tid = q+ .items+ .iter()+ .find(|i| i.id == download_id)+ .and_then(|i| i.torrent_id);(Some(q.get_state()), tid)} else {(None, None)@@ -359,7 +373,9 @@ pub async fn remove_download(};if let Some(tid) = seeding_torrent_id {if let Some(session) = state.torrent_session.lock().await.as_ref() {- let _ = session.delete(librqbit::api::TorrentIdOrHash::Id(tid), false).await;+ let _ = session+ .delete(librqbit::api::TorrentIdOrHash::Id(tid), false)+ .await;}}if let Some(s) = state_to_emit {@@ -455,8 +471,10 @@ pub async fn reveal_file(path: String) -> Result<(), String> {.map(|u| u.to_string()).unwrap_or_else(|_| format!("file://{}", dir_path.display()));- let gdbus_show_items_arg =- format!("[\"{}\"]", item_uri.replace('\\', "\\\\").replace('"', "\\\""));+ let gdbus_show_items_arg = format!(+ "[\"{}\"]",+ item_uri.replace('\\', "\\\\").replace('"', "\\\"")+ );let show_items_with_gdbus = tokio::process::Command::new("gdbus").args(["call",@@ -534,4 +552,3 @@ pub async fn reveal_file(path: String) -> Result<(), String> {Ok(())}-diff --git a/src-tauri/src/commands/p2p.rs b/src-tauri/src/commands/p2p.rsindex 9537d965..59d627fd 100644--- a/src-tauri/src/commands/p2p.rs+++ b/src-tauri/src/commands/p2p.rs@@ -2,8 +2,8 @@ use serde::Serialize;use tauri::Emitter;use tokio_util::sync::CancellationToken;-use crate::{AppState, P2pSendHandle};use crate::platforms::p2p;+use crate::{AppState, P2pSendHandle};#[derive(Clone, Serialize)]pub struct P2pSendStarted {@@ -46,10 +46,13 @@ pub async fn p2p_send_file(let paused_ref = session.paused.clone();{let mut sends = state.active_p2p_sends.lock().await;- sends.insert(code.clone(), P2pSendHandle {- cancel_token,- paused: paused_ref,- });+ sends.insert(+ code.clone(),+ P2pSendHandle {+ cancel_token,+ paused: paused_ref,+ },+ );}let app_clone = app.clone();@@ -128,19 +131,25 @@ pub async fn p2p_send_file(match result {Ok(()) => {- let _ = app_clone.emit("p2p-send-complete", serde_json::json!({- "code": code_for_task,- "success": true,- }));+ let _ = app_clone.emit(+ "p2p-send-complete",+ serde_json::json!({+ "code": code_for_task,+ "success": true,+ }),+ );}Err(e) => {let err = e.to_string();tracing::error!("[p2p] send failed: {}", err);- let _ = app_clone.emit("p2p-send-complete", serde_json::json!({- "code": code_for_task,- "success": false,- "error": err,- }));+ let _ = app_clone.emit(+ "p2p-send-complete",+ serde_json::json!({+ "code": code_for_task,+ "success": false,+ "error": err,+ }),+ );}}});@@ -173,7 +182,9 @@ pub async fn p2p_pause_send(let sends = state.active_p2p_sends.lock().await;match sends.get(&code) {Some(handle) => {- handle.paused.store(true, std::sync::atomic::Ordering::Relaxed);+ handle+ .paused+ .store(true, std::sync::atomic::Ordering::Relaxed);Ok("Send paused".to_string())}None => Err("No active send with this code".to_string()),@@ -189,7 +200,9 @@ pub async fn p2p_resume_send(let sends = state.active_p2p_sends.lock().await;match sends.get(&code) {Some(handle) => {- handle.paused.store(false, std::sync::atomic::Ordering::Relaxed);+ handle+ .paused+ .store(false, std::sync::atomic::Ordering::Relaxed);Ok("Send resumed".to_string())}None => Err("No active send with this code".to_string()),diff --git a/src-tauri/src/commands/plugins.rs b/src-tauri/src/commands/plugins.rsindex 0ab2f4dc..a0a2c7ee 100644--- a/src-tauri/src/commands/plugins.rs+++ b/src-tauri/src/commands/plugins.rs@@ -66,9 +66,10 @@ pub fn list_plugins(},None => {let manifest_path = manager.plugins_dir().join(&entry.id).join("plugin.json");- let manifest: Option<omniget_plugin_sdk::PluginManifest> = std::fs::read_to_string(&manifest_path)- .ok()- .and_then(|s| serde_json::from_str(&s).ok());+ let manifest: Option<omniget_plugin_sdk::PluginManifest> =+ std::fs::read_to_string(&manifest_path)+ .ok()+ .and_then(|s| serde_json::from_str(&s).ok());match manifest {Some(m) => PluginInfo {id: entry.id.clone(),@@ -79,16 +80,22 @@ pub fn list_plugins(enabled: entry.enabled,loaded: false,icon: m.icon,- nav: m.nav.iter().map(|n| PluginNavInfo {- route: n.route.clone(),- label: n.label.clone(),- icon_svg: n.icon_svg.clone(),- group: match n.group {- omniget_plugin_sdk::NavGroup::Primary => "primary".into(),- omniget_plugin_sdk::NavGroup::Secondary => "secondary".into(),- },- order: n.order,- }).collect(),+ nav: m+ .nav+ .iter()+ .map(|n| PluginNavInfo {+ route: n.route.clone(),+ label: n.label.clone(),+ icon_svg: n.icon_svg.clone(),+ group: match n.group {+ omniget_plugin_sdk::NavGroup::Primary => "primary".into(),+ omniget_plugin_sdk::NavGroup::Secondary => {+ "secondary".into()+ }+ },+ order: n.order,+ })+ .collect(),},None => PluginInfo {id: entry.id.clone(),@@ -102,7 +109,7 @@ pub fn list_plugins(nav: Vec::new(),},}- },+ }}}).collect();@@ -212,7 +219,9 @@ pub async fn fetch_marketplace_registry(.build().map_err(|e| e.to_string())?;- let response = client.get(REGISTRY_URL).send()+ let response = client+ .get(REGISTRY_URL)+ .send().await.map_err(|e| format!("Failed to fetch registry: {}", e))?;diff --git a/src-tauri/src/commands/settings.rs b/src-tauri/src/commands/settings.rsindex 667c977d..890e8e7f 100644--- a/src-tauri/src/commands/settings.rs+++ b/src-tauri/src/commands/settings.rs@@ -19,8 +19,7 @@ pub fn update_settings(app: tauri::AppHandle, partial: String) -> Result<AppSettlet mut current_val =serde_json::to_value(¤t).map_err(|e| format!("Serialize: {}", e))?;merge_json(&mut current_val, &patch);- current =- serde_json::from_value(current_val).map_err(|e| format!("Deserialize: {}", e))?;+ current = serde_json::from_value(current_val).map_err(|e| format!("Deserialize: {}", e))?;config::save_settings(&app, ¤t).map_err(|e| format!("Save: {}", e))?;crate::core::http_client::init_proxy(current.proxy.clone());diff --git a/src-tauri/src/core/mod.rs b/src-tauri/src/core/mod.rsindex ba90c9fe..e4712c79 100644--- a/src-tauri/src/core/mod.rs+++ b/src-tauri/src/core/mod.rs@@ -1,8 +1,9 @@-pub use omniget_core::core::registry;pub use omniget_core::core::clipboard;pub use omniget_core::core::cookie_parser;pub use omniget_core::core::course_utils;+pub use omniget_core::core::dependencies;pub use omniget_core::core::direct_downloader;+pub use omniget_core::core::ffmpeg;pub use omniget_core::core::filename;pub use omniget_core::core::hls_downloader;pub use omniget_core::core::http_client;@@ -11,10 +12,9 @@ pub use omniget_core::core::media_processor;pub use omniget_core::core::paths;pub use omniget_core::core::process;pub use omniget_core::core::redirect;-pub use omniget_core::core::dependencies;-pub use omniget_core::core::ffmpeg;+pub use omniget_core::core::registry;pub use omniget_core::core::ytdlp;pub mod events;-pub mod url_parser;pub mod queue;+pub mod url_parser;diff --git a/src-tauri/src/core/queue.rs b/src-tauri/src/core/queue.rsindex bbe83ea4..c3b2d2dd 100644--- a/src-tauri/src/core/queue.rs+++ b/src-tauri/src/core/queue.rs@@ -37,8 +37,9 @@ fn info_cache() -> &'static tokio::sync::Mutex<HashMap<String, CachedInfo>> {const INFO_CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(600);-static IN_FLIGHT_FETCHES: OnceLock<tokio::sync::Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>> =- OnceLock::new();+static IN_FLIGHT_FETCHES: OnceLock<+ tokio::sync::Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,+> = OnceLock::new();fn in_flight_map() -> &'static tokio::sync::Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>> {IN_FLIGHT_FETCHES.get_or_init(|| tokio::sync::Mutex::new(HashMap::new()))@@ -123,7 +124,10 @@ impl QueueItem {file_path: self.file_path.clone(),file_size_bytes: self.file_size_bytes,file_count: self.file_count,- thumbnail_url: self.media_info.as_ref().and_then(|m| m.thumbnail_url.clone()),+ thumbnail_url: self+ .media_info+ .as_ref()+ .and_then(|m| m.thumbnail_url.clone()),}}}@@ -332,7 +336,11 @@ impl DownloadQueue {// so we must cancel it now to stop the background download loop.// Also return the torrent_id for session cleanup.item.cancel_token.cancel();- let tid = if item.platform == "magnet" { item.torrent_id } else { None };+ let tid = if item.platform == "magnet" {+ item.torrent_id+ } else {+ None+ };item.status = QueueStatus::Error {message: "Cancelled".to_string(),};@@ -409,7 +417,10 @@ impl DownloadQueue {i.url == url&& matches!(i.status,- QueueStatus::Queued | QueueStatus::Active | QueueStatus::Paused | QueueStatus::Seeding+ QueueStatus::Queued+ | QueueStatus::Active+ | QueueStatus::Paused+ | QueueStatus::Seeding)})}@@ -493,9 +504,13 @@ pub fn spawn_download(item_id: u64,) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> {Box::pin(async move {- let _timer_start = std::time::Instant::now();- spawn_download_inner(app, queue, item_id).await;- tracing::debug!("[perf] spawn_download {} took {:?}", item_id, _timer_start.elapsed());+ let _timer_start = std::time::Instant::now();+ spawn_download_inner(app, queue, item_id).await;+ tracing::debug!(+ "[perf] spawn_download {} took {:?}",+ item_id,+ _timer_start.elapsed()+ );})}@@ -506,18 +521,35 @@ async fn spawn_download_inner() {tracing::info!("[queue] download {} started", item_id);- let _ = app.emit("queue-item-progress", &QueueItemProgress {- id: item_id,- title: "".to_string(),- platform: "".to_string(),- percent: 0.0,- speed_bytes_per_sec: 0.0,- downloaded_bytes: 0,- total_bytes: None,- phase: "preparing".to_string(),- });+ let _ = app.emit(+ "queue-item-progress",+ &QueueItemProgress {+ id: item_id,+ title: "".to_string(),+ platform: "".to_string(),+ percent: 0.0,+ speed_bytes_per_sec: 0.0,+ downloaded_bytes: 0,+ total_bytes: None,+ phase: "preparing".to_string(),+ },+ );- let (url, output_dir, download_mode, quality, format_id, referer, extra_headers, cancel_token, media_info, platform_name, downloader, ytdlp_path, from_hotkey) = {+ let (+ url,+ output_dir,+ download_mode,+ quality,+ format_id,+ referer,+ extra_headers,+ cancel_token,+ media_info,+ platform_name,+ downloader,+ ytdlp_path,+ from_hotkey,+ ) = {let q = queue.lock().await;let item = match q.items.iter().find(|i| i.id == item_id) {Some(i) => i,@@ -543,26 +575,37 @@ async fn spawn_download_inner(let info_start = std::time::Instant::now();let info = match media_info {Some(i) => {- tracing::info!("[queue] info for {} from cache/pre-fetched in {:?}", item_id, info_start.elapsed());+ tracing::info!(+ "[queue] info for {} from cache/pre-fetched in {:?}",+ item_id,+ info_start.elapsed()+ );i}None => {- tracing::debug!("[perf] spawn_download_inner {}: media_info is None, fetching info", item_id);- let _ = app.emit("queue-item-progress", &QueueItemProgress {- id: item_id,- title: url.clone(),- platform: platform_name.clone(),- percent: 0.0,- speed_bytes_per_sec: 0.0,- downloaded_bytes: 0,- total_bytes: None,- phase: "fetching_info".to_string(),- });+ tracing::debug!(+ "[perf] spawn_download_inner {}: media_info is None, fetching info",+ item_id+ );+ let _ = app.emit(+ "queue-item-progress",+ &QueueItemProgress {+ id: item_id,+ title: url.clone(),+ platform: platform_name.clone(),+ percent: 0.0,+ speed_bytes_per_sec: 0.0,+ downloaded_bytes: 0,+ total_bytes: None,+ phase: "fetching_info".to_string(),+ },+ );let info_result = tokio::time::timeout(std::time::Duration::from_secs(60),- fetch_and_cache_info(&url, &*downloader, &platform_name, ytdlp_path.as_deref())- ).await;+ fetch_and_cache_info(&url, &*downloader, &platform_name, ytdlp_path.as_deref()),+ )+ .await;match info_result {Ok(Ok(i)) => i,@@ -580,7 +623,13 @@ async fn spawn_download_inner(tracing::warn!("[queue] info fetch timed out for {} after 60s", item_id);let state = {let mut q = queue.lock().await;- q.mark_complete(item_id, false, Some("Timed out fetching video info".to_string()), None, None);+ q.mark_complete(+ item_id,+ false,+ Some("Timed out fetching video info".to_string()),+ None,+ None,+ );q.get_state()};emit_queue_state_from_state(&app, state);@@ -590,7 +639,11 @@ async fn spawn_download_inner(}}};- tracing::info!("[queue] info fetch for {} took {:?}", item_id, info_start.elapsed());+ tracing::info!(+ "[queue] info fetch for {} took {:?}",+ item_id,+ info_start.elapsed()+ );let mut info = info;if is_generic_title(&info.title) {@@ -617,16 +670,19 @@ async fn spawn_download_inner(};emit_queue_state_from_state(&app, state);- let _ = app.emit("queue-item-progress", &QueueItemProgress {- id: item_id,- title: info.title.clone(),- platform: platform_name.clone(),- percent: 0.5,- speed_bytes_per_sec: 0.0,- downloaded_bytes: 0,- total_bytes: info.file_size_bytes,- phase: "starting".to_string(),- });+ let _ = app.emit(+ "queue-item-progress",+ &QueueItemProgress {+ id: item_id,+ title: info.title.clone(),+ platform: platform_name.clone(),+ percent: 0.5,+ speed_bytes_per_sec: 0.0,+ downloaded_bytes: 0,+ total_bytes: info.file_size_bytes,+ phase: "starting".to_string(),+ },+ );let settings = config::load_settings(&app);let tmpl = settings.download.filename_template.clone();@@ -701,19 +757,29 @@ async fn spawn_download_inner({let mut q = queue_progress.lock().await;let tid = { *torrent_id_slot_progress.lock().await };- q.update_progress(item_id, clamped, current_speed, downloaded_bytes, total_bytes, tid);+ q.update_progress(+ item_id,+ clamped,+ current_speed,+ downloaded_bytes,+ total_bytes,+ tid,+ );}- let _ = app_progress.emit("queue-item-progress", &QueueItemProgress {- id: item_id,- title: item_title.clone(),- platform: item_platform.clone(),- percent: clamped,- speed_bytes_per_sec: current_speed,- downloaded_bytes,- total_bytes,- phase: phase.to_string(),- });+ let _ = app_progress.emit(+ "queue-item-progress",+ &QueueItemProgress {+ id: item_id,+ title: item_title.clone(),+ platform: item_platform.clone(),+ percent: clamped,+ speed_bytes_per_sec: current_speed,+ downloaded_bytes,+ total_bytes,+ phase: phase.to_string(),+ },+ );}});@@ -724,7 +790,11 @@ async fn spawn_download_inner(Err(anyhow::anyhow!("Download cancelado"))}};- tracing::info!("[queue] download {} completed in {:?}", item_id, dl_start.elapsed());+ tracing::info!(+ "[queue] download {} completed in {:?}",+ item_id,+ dl_start.elapsed()+ );let _ = progress_forwarder.await;@@ -749,7 +819,10 @@ async fn spawn_download_inner(match result {Ok(dl) => {- if settings.download.embed_metadata && platform_name != "magnet" && ffmpeg::is_ffmpeg_available().await {+ if settings.download.embed_metadata+ && platform_name != "magnet"+ && ffmpeg::is_ffmpeg_available().await+ {let metadata = MetadataEmbed {title: Some(info.title.clone()),artist: Some(info.author.clone()),@@ -773,9 +846,12 @@ async fn spawn_download_inner({match crate::core::clipboard::copy_file_to_clipboard(&dl.file_path).await {Ok(()) => {- let _ = app.emit("file-copied-to-clipboard", serde_json::json!({- "path": dl.file_path.to_string_lossy(),- }));+ let _ = app.emit(+ "file-copied-to-clipboard",+ serde_json::json!({+ "path": dl.file_path.to_string_lossy(),+ }),+ );}Err(e) => {tracing::warn!("[clipboard] failed to copy file: {}", e);@@ -814,7 +890,12 @@ async fn spawn_download_inner(} else {raw_err.clone()};- tracing::error!("Download error '{}' [{}]: {}", platform_name, category, raw_err);+ tracing::error!(+ "Download error '{}' [{}]: {}",+ platform_name,+ category,+ raw_err+ );let state = {let mut q = queue.lock().await;q.mark_complete(item_id, false, Some(user_msg), None, None);@@ -855,7 +936,10 @@ async fn fetch_and_cache_info(let cache = info_cache().lock().await;if let Some(entry) = cache.get(url) {if entry.cached_at.elapsed() < INFO_CACHE_TTL {- tracing::debug!("[perf] fetch_and_cache_info: dedup cache hit for {}", platform);+ tracing::debug!(+ "[perf] fetch_and_cache_info: dedup cache hit for {}",+ platform+ );return Ok(entry.info.clone());}}@@ -878,10 +962,13 @@ async fn fetch_and_cache_info(};let mut cache = info_cache().lock().await;- cache.insert(url.to_string(), CachedInfo {- info: info.clone(),- cached_at: std::time::Instant::now(),- });+ cache.insert(+ url.to_string(),+ CachedInfo {+ info: info.clone(),+ cached_at: std::time::Instant::now(),+ },+ );if cache.len() > 50 {cache.retain(|_, v| v.cached_at.elapsed() < INFO_CACHE_TTL);}@@ -916,7 +1003,11 @@ pub async fn prefetch_info_with_emit(tracing::debug!("[perf] prefetch_info: started");match fetch_and_cache_info(url, downloader, platform, ytdlp_path).await {Ok(info) => {- tracing::debug!("[perf] prefetch_info: completed in {:?} — {}", _timer_start.elapsed(), info.title);+ tracing::debug!(+ "[perf] prefetch_info: completed in {:?} — {}",+ _timer_start.elapsed(),+ info.title+ );if let Some(app) = app {let preview = MediaPreviewEvent {url: url.to_string(),@@ -928,7 +1019,11 @@ pub async fn prefetch_info_with_emit(let _ = app.emit("media-info-preview", preview);}}- Err(e) => tracing::warn!("[perf] prefetch_info: failed in {:?} — {}", _timer_start.elapsed(), e),+ Err(e) => tracing::warn!(+ "[perf] prefetch_info: failed in {:?} — {}",+ _timer_start.elapsed(),+ e+ ),}}@@ -940,7 +1035,11 @@ pub async fn try_start_next(app: tauri::AppHandle, queue: Arc<tokio::sync::Mutexfor nid in &ids {q.mark_active(*nid);}- let state = if !ids.is_empty() { Some(q.get_state()) } else { None };+ let state = if !ids.is_empty() {+ Some(q.get_state())+ } else {+ None+ };(ids, q.stagger_delay_ms, state)};@@ -950,21 +1049,27 @@ pub async fn try_start_next(app: tauri::AppHandle, queue: Arc<tokio::sync::Mutexlet batch_size = next_ids.len();for (i, nid) in next_ids.into_iter().enumerate() {- let _ = app.emit("queue-item-progress", &QueueItemProgress {- id: nid,- title: String::new(),- platform: String::new(),- percent: 0.0,- speed_bytes_per_sec: 0.0,- downloaded_bytes: 0,- total_bytes: None,- phase: "queued_starting".to_string(),- });+ let _ = app.emit(+ "queue-item-progress",+ &QueueItemProgress {+ id: nid,+ title: String::new(),+ platform: String::new(),+ percent: 0.0,+ speed_bytes_per_sec: 0.0,+ downloaded_bytes: 0,+ total_bytes: None,+ phase: "queued_starting".to_string(),+ },+ );if i > 0 {let item_platform = {let q = queue.lock().await;- q.items.iter().find(|item| item.id == nid).map(|item| item.platform.clone())+ q.items+ .iter()+ .find(|item| item.id == nid)+ .map(|item| item.platform.clone())};let delay_ms = if item_platform.as_deref() == Some("youtube") {2000diff --git a/src-tauri/src/external_url.rs b/src-tauri/src/external_url.rsindex bc047fc3..ba8a64c2 100644--- a/src-tauri/src/external_url.rs+++ b/src-tauri/src/external_url.rs@@ -90,7 +90,8 @@ pub async fn queue_url_with_defaults(let ext_meta = crate::native_host::read_extension_metadata(&url);- let has_ext_media = ext_meta.as_ref()+ let has_ext_media = ext_meta+ .as_ref().and_then(|m| m.media_type.as_deref()).is_some();@@ -130,12 +131,19 @@ pub async fn queue_url_with_defaults(} else {return None;};- let title = url::Url::parse(&url).ok()+ let title = url::Url::parse(&url)+ .ok().and_then(|u| {let path = u.path();let last = path.rsplit('/').next()?;- if last.is_empty() { return None; }- Some(urlencoding::decode(last).unwrap_or_else(|_| last.into()).to_string())+ if last.is_empty() {+ return None;+ }+ Some(+ urlencoding::decode(last)+ .unwrap_or_else(|_| last.into())+ .to_string(),+ )}).map(|n| sanitize_filename::sanitize(&n)).unwrap_or_else(|| "download".to_string());diff --git a/src-tauri/src/hotkey.rs b/src-tauri/src/hotkey.rsindex 03028a95..4df885d3 100644--- a/src-tauri/src/hotkey.rs+++ b/src-tauri/src/hotkey.rs@@ -74,9 +74,6 @@ async fn enqueue_from_clipboard(app: &tauri::AppHandle, url: String) {crate::external_url::queue_url_with_defaults(app, url.clone(), true).await,Ok(crate::external_url::QueueUrlOutcome::Queued)) {- let _ = app.emit(- "hotkey-download-queued",- serde_json::json!({ "url": url }),- );+ let _ = app.emit("hotkey-download-queued", serde_json::json!({ "url": url }));}}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex d4eb9a7a..86474239 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -2,10 +2,6 @@ use std::collections::HashMap;use std::sync::Arc;use tauri::Manager;----use tokio_util::sync::CancellationToken;pub struct P2pSendHandle {@@ -26,149 +22,10 @@ pub mod plugin_loader;pub mod storage;pub mod tray;--------------------------------------------------------------------------------------------------------------------------------------------pub struct AppState {pub active_downloads: Arc<tokio::sync::Mutex<HashMap<u64, CancellationToken>>>,- pub active_generic_downloads: Arc<tokio::sync::Mutex<HashMap<u64, (String, CancellationToken)>>>,+ pub active_generic_downloads:+ Arc<tokio::sync::Mutex<HashMap<u64, (String, CancellationToken)>>>,pub registry: core::registry::PlatformRegistry,pub download_queue: Arc<tokio::sync::Mutex<core::queue::DownloadQueue>>,pub torrent_session: Arc<tokio::sync::Mutex<Option<Arc<librqbit::Session>>>>,@@ -182,44 +39,22 @@ pub fn run() {tracing_subscriber::fmt::init();let mut registry = core::registry::PlatformRegistry::new();- registry.register(Arc::new(- platforms::instagram::InstagramDownloader::new(),- ));- registry.register(Arc::new(- platforms::pinterest::PinterestDownloader::new(),- ));- registry.register(Arc::new(- platforms::tiktok::TikTokDownloader::new(),- ));- registry.register(Arc::new(- platforms::twitter::TwitterDownloader::new(),- ));- registry.register(Arc::new(- platforms::twitch::TwitchClipsDownloader::new(),- ));- registry.register(Arc::new(- platforms::bluesky::BlueskyDownloader::new(),- ));- registry.register(Arc::new(- platforms::reddit::RedditDownloader::new(),- ));- registry.register(Arc::new(- platforms::youtube::YouTubeDownloader::new(),- ));- registry.register(Arc::new(- platforms::vimeo::VimeoDownloader::new(),- ));- registry.register(Arc::new(- platforms::bilibili::BilibiliDownloader::new(),- ));+ registry.register(Arc::new(platforms::instagram::InstagramDownloader::new()));+ registry.register(Arc::new(platforms::pinterest::PinterestDownloader::new()));+ registry.register(Arc::new(platforms::tiktok::TikTokDownloader::new()));+ registry.register(Arc::new(platforms::twitter::TwitterDownloader::new()));+ registry.register(Arc::new(platforms::twitch::TwitchClipsDownloader::new()));+ registry.register(Arc::new(platforms::bluesky::BlueskyDownloader::new()));+ registry.register(Arc::new(platforms::reddit::RedditDownloader::new()));+ registry.register(Arc::new(platforms::youtube::YouTubeDownloader::new()));+ registry.register(Arc::new(platforms::vimeo::VimeoDownloader::new()));+ registry.register(Arc::new(platforms::bilibili::BilibiliDownloader::new()));let torrent_session: Arc<tokio::sync::Mutex<Option<Arc<librqbit::Session>>>> =Arc::new(tokio::sync::Mutex::new(None));- registry.register(Arc::new(- platforms::magnet::MagnetDownloader::new(torrent_session.clone()),- ));- registry.register(Arc::new(- platforms::p2p::P2pDownloader::new(),- ));+ registry.register(Arc::new(platforms::magnet::MagnetDownloader::new(+ torrent_session.clone(),+ )));+ registry.register(Arc::new(platforms::p2p::P2pDownloader::new()));registry.register(Arc::new(platforms::generic_ytdlp::GenericYtdlpDownloader::new(),));@@ -237,11 +72,18 @@ pub fn run() {tauri::Builder::default().plugin(tauri_plugin_single_instance::init(|app, argv, _cwd| {- if let Some(url) = external_url::find_external_url_arg(argv.iter().skip(1).map(|arg| arg.as_str())) {+ if let Some(url) =+ external_url::find_external_url_arg(argv.iter().skip(1).map(|arg| arg.as_str()))+ {let app_handle = app.clone();tauri::async_runtime::spawn(async move {- if let Err(error) = external_url::handle_external_url(&app_handle, url, "command-line").await {- tracing::warn!("Failed to handle external URL from second instance: {}", error);+ if let Err(error) =+ external_url::handle_external_url(&app_handle, url, "command-line").await+ {+ tracing::warn!(+ "Failed to handle external URL from second instance: {}",+ error+ );}});} else {@@ -280,14 +122,19 @@ pub fn run() {core::ytdlp::set_global_cookie_file_fn(|| {let s = storage::config::load_settings_standalone();let cf = s.download.cookie_file.clone();- if !cf.is_empty() && std::path::Path::new(&cf).exists() { Some(cf) } else { None }+ if !cf.is_empty() && std::path::Path::new(&cf).exists() {+ Some(cf)+ } else {+ None+ }});core::ytdlp::set_cookies_from_browser_fn(|| {- storage::config::load_settings_standalone().advanced.cookies_from_browser+ storage::config::load_settings_standalone()+ .advanced+ .cookies_from_browser});core::ytdlp::set_ext_referer_fn(|url| {- native_host::read_extension_metadata(url)- .and_then(|m| m.referer)+ native_host::read_extension_metadata(url).and_then(|m| m.referer)});tray::setup(app.handle())?;hotkey::register_from_settings(app.handle());@@ -302,7 +149,9 @@ pub fn run() {app.handle().clone(),plugins_dir,));- let plugin_mgr = app.handle().state::<std::sync::Arc<tokio::sync::RwLock<plugin_loader::PluginManager>>>();+ let plugin_mgr = app+ .handle()+ .state::<std::sync::Arc<tokio::sync::RwLock<plugin_loader::PluginManager>>>();let mut mgr = plugin_mgr.blocking_write();mgr.load_all(host);}@@ -330,7 +179,9 @@ pub fn run() {if let Some(url) = external_url::find_external_url_arg(std::env::args().skip(1)) {let app_handle = app.handle().clone();tauri::async_runtime::spawn(async move {- if let Err(error) = external_url::handle_external_url(&app_handle, url, "command-line").await {+ if let Err(error) =+ external_url::handle_external_url(&app_handle, url, "command-line").await+ {tracing::warn!("Failed to handle startup external URL: {}", error);}});diff --git a/src-tauri/src/native_host.rs b/src-tauri/src/native_host.rsindex b9432255..66f67995 100644--- a/src-tauri/src/native_host.rs+++ b/src-tauri/src/native_host.rs@@ -7,9 +7,7 @@ use anyhow::Context;use serde::{Deserialize, Serialize};pub const CHROME_HOST_NAME: &str = "wtf.tonho.omniget";-pub const CHROME_EXTENSION_IDS: &[&str] = &[- "dkjelkhaaakffpghdfalobccaaipajip",-];+pub const CHROME_EXTENSION_IDS: &[&str] = &["dkjelkhaaakffpghdfalobccaaipajip"];const FIREFOX_EXTENSION_ID: &str = "[email protected]";#[cfg(target_os = "windows")]@@ -66,7 +64,10 @@ struct NativeHostConfig {pub fn should_run_as_native_host() -> bool {std::env::current_exe().ok()- .and_then(|path| path.file_stem().map(|stem| stem.to_string_lossy().to_string()))+ .and_then(|path| {+ path.file_stem()+ .map(|stem| stem.to_string_lossy().to_string())+ }).map(|stem| stem.eq_ignore_ascii_case(HOST_BINARY_STEM)).unwrap_or(false)}@@ -166,7 +167,10 @@ fn write_host_config(config_path: &Path, app_path: &Path) -> anyhow::Result<()>}fn write_host_manifest(manifest_path: &Path, host_exe: &Path) -> anyhow::Result<()> {- fs::write(manifest_path, serde_json::to_vec_pretty(&build_host_manifest(host_exe))?)?;+ fs::write(+ manifest_path,+ serde_json::to_vec_pretty(&build_host_manifest(host_exe))?,+ )?;Ok(())}@@ -194,8 +198,9 @@ fn chrome_manifest_path(integration_dir: &Path) -> anyhow::Result<PathBuf> {#[cfg(target_os = "linux")]fn chrome_manifest_path(_integration_dir: &Path) -> anyhow::Result<PathBuf> {- let base_dir = dirs::config_dir()- .context("Could not resolve the Linux config directory for Chrome native host registration")?;+ let base_dir = dirs::config_dir().context(+ "Could not resolve the Linux config directory for Chrome native host registration",+ )?;Ok(chrome_manifest_path_from_base(&base_dir))}@@ -280,7 +285,10 @@ fn build_firefox_manifest(host_exe: &Path) -> serde_json::Value {}fn write_firefox_manifest(manifest_path: &Path, host_exe: &Path) -> anyhow::Result<()> {- fs::write(manifest_path, serde_json::to_vec_pretty(&build_firefox_manifest(host_exe))?)?;+ fs::write(+ manifest_path,+ serde_json::to_vec_pretty(&build_firefox_manifest(host_exe))?,+ )?;Ok(())}@@ -403,19 +411,20 @@ fn write_extension_cookies(cookies: &[NativeCookie]) -> anyhow::Result<()> {let name = sanitize_cookie_field(&c.name);let value = sanitize_cookie_field(&c.value);let http_only_prefix = if c.http_only { "#HttpOnly_" } else { "" };- let include_subdomains = if domain.starts_with('.') { "TRUE" } else { "FALSE" };+ let include_subdomains = if domain.starts_with('.') {+ "TRUE"+ } else {+ "FALSE"+ };let secure = if c.secure { "TRUE" } else { "FALSE" };- let expires = if c.expires == 0 { session_ttl } else { c.expires as u64 };+ let expires = if c.expires == 0 {+ session_ttl+ } else {+ c.expires as u64+ };content.push_str(&format!("{}{}\t{}\t{}\t{}\t{}\t{}\t{}\n",- http_only_prefix,- domain,- include_subdomains,- path_field,- secure,- expires,- name,- value,+ http_only_prefix, domain, include_subdomains, path_field, secure, expires, name, value,));}@@ -493,10 +502,19 @@ pub fn read_extension_metadata(url: &str) -> Option<ExtensionMetadata> {});let result = ExtensionMetadata {- referer: meta.get("referer").and_then(|v| v.as_str()).map(String::from),+ referer: meta+ .get("referer")+ .and_then(|v| v.as_str())+ .map(String::from),headers,- media_type: meta.get("mediaType").and_then(|v| v.as_str()).map(String::from),- content_type: meta.get("contentType").and_then(|v| v.as_str()).map(String::from),+ media_type: meta+ .get("mediaType")+ .and_then(|v| v.as_str())+ .map(String::from),+ content_type: meta+ .get("contentType")+ .and_then(|v| v.as_str())+ .map(String::from),};let _ = fs::remove_file(&path);@@ -579,9 +597,7 @@ fn read_message() -> anyhow::Result<NativeHostRequest> {let length = u32::from_le_bytes(length_bytes) as usize;if length > MAX_MESSAGE_LENGTH {- anyhow::bail!(- "Native message too large ({length} bytes, max {MAX_MESSAGE_LENGTH})"- );+ anyhow::bail!("Native message too large ({length} bytes, max {MAX_MESSAGE_LENGTH})");}let mut payload = vec![0u8; length];@@ -656,8 +672,14 @@ mod tests {let manifest = build_host_manifest(host_exe);assert_eq!(manifest["name"].as_str(), Some(CHROME_HOST_NAME));- assert_eq!(manifest["description"].as_str(), Some("OmniGet native host for Chrome"));- assert_eq!(manifest["path"].as_str(), Some(host_exe.to_string_lossy().as_ref()));+ assert_eq!(+ manifest["description"].as_str(),+ Some("OmniGet native host for Chrome")+ );+ assert_eq!(+ manifest["path"].as_str(),+ Some(host_exe.to_string_lossy().as_ref())+ );assert_eq!(manifest["type"].as_str(), Some("stdio"));let allowed_origins = manifest["allowed_origins"].as_array()diff --git a/src-tauri/src/platforms/twitter/mod.rs b/src-tauri/src/platforms/twitter/mod.rsindex 9e052437..0f7d8b33 100644--- a/src-tauri/src/platforms/twitter/mod.rs+++ b/src-tauri/src/platforms/twitter/mod.rs@@ -5,13 +5,10 @@ use async_trait::async_trait;use tokio::sync::{mpsc, Mutex};use crate::core::direct_downloader;-use crate::models::media::{- DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality,-};+use crate::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};use crate::platforms::traits::PlatformDownloader;-const GRAPHQL_URL: &str =- "https://api.x.com/graphql/4Siu98E55GquhG52zHdY5w/TweetDetail";+const GRAPHQL_URL: &str = "https://api.x.com/graphql/4Siu98E55GquhG52zHdY5w/TweetDetail";const TOKEN_URL: &str = "https://api.x.com/1.1/guest/activate.json";const BEARER: &str = "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA";const USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";@@ -99,7 +96,10 @@ impl TwitterDownloader {.await?;if !response.status().is_success() {- return Err(anyhow!("Falha ao obter guest token: HTTP {}", response.status()));+ return Err(anyhow!(+ "Falha ao obter guest token: HTTP {}",+ response.status()+ ));}let json: serde_json::Value = response.json().await?;@@ -138,7 +138,10 @@ impl TwitterDownloader {urlencoding::encode(TWEET_FIELD_TOGGLES),);- let cookie_val = format!("guest_id={}", urlencoding::encode(&format!("v1:{}", guest_token)));+ let cookie_val = format!(+ "guest_id={}",+ urlencoding::encode(&format!("v1:{}", guest_token))+ );let response = self.client@@ -243,7 +246,10 @@ impl TwitterDownloader {let response = self.client.get(&url).send().await?;if !response.status().is_success() {- return Err(anyhow!("Syndication API retornou HTTP {}", response.status()));+ return Err(anyhow!(+ "Syndication API retornou HTTP {}",+ response.status()+ ));}response.json().await.map_err(Into::into)@@ -310,15 +316,15 @@ impl TwitterDownloader {tweet_result.get("legacy")};- let base_tweet =- base_tweet.ok_or_else(|| anyhow!("Post not available"))?;+ let base_tweet = base_tweet.ok_or_else(|| anyhow!("Post not available"))?;let reposted_media = if typename == "TweetWithVisibilityResults" {tweet_result.pointer("/tweet/legacy/retweeted_status_result/result/tweet/legacy/extended_entities/media")} else {- tweet_result- .pointer("/legacy/retweeted_status_result/result/legacy/extended_entities/media")+ tweet_result.pointer(+ "/legacy/retweeted_status_result/result/legacy/extended_entities/media",+ )};let media = reposted_media@@ -350,14 +356,8 @@ impl TwitterDownloader {variants.iter()- .filter(|v| {- v.get("content_type").and_then(|c| c.as_str()) == Some("video/mp4")- })- .max_by_key(|v| {- v.get("bitrate")- .and_then(|b| b.as_u64())- .unwrap_or(0)- })+ .filter(|v| v.get("content_type").and_then(|c| c.as_str()) == Some("video/mp4"))+ .max_by_key(|v| v.get("bitrate").and_then(|b| b.as_u64()).unwrap_or(0)).and_then(|v| v.get("url").and_then(|u| u.as_str())).map(|s| s.to_string())}@@ -370,15 +370,9 @@ impl TwitterDownloader {match media_type_str {"photo" => {- let base_url = m- .get("media_url_https")- .and_then(|v| v.as_str())?;+ let base_url = m.get("media_url_https").and_then(|v| v.as_str())?;let url = format!("{}?name=4096x4096", base_url);- let ext = base_url- .rsplit('.')- .next()- .unwrap_or("jpg")- .to_string();+ let ext = base_url.rsplit('.').next().unwrap_or("jpg").to_string();Some(TwitterMediaItem {media_type: TwitterMediaType::Photo,url,@@ -453,7 +447,10 @@ impl PlatformDownloader for TwitterDownloader {match self.native_get_media_info(url).await {Ok(info) => Ok(info),Err(native_err) => {- tracing::warn!("[twitter] native failed: {}, trying yt-dlp fallback", native_err);+ tracing::warn!(+ "[twitter] native failed: {}, trying yt-dlp fallback",+ native_err+ );self.fallback_ytdlp(url).await.map_err(|_| native_err)}}@@ -529,14 +526,9 @@ impl PlatformDownloader for TwitterDownloader {let output = opts.output_dir.join(&filename);let (tx, _rx) = mpsc::channel(8);- let bytes = direct_downloader::download_direct(- &self.client,- &quality.url,- &output,- tx,- None,- )- .await?;+ let bytes =+ direct_downloader::download_direct(&self.client, &quality.url, &output, tx, None)+ .await?;total_bytes += bytes;last_path = output;@@ -562,8 +554,8 @@ impl TwitterDownloader {}async fn native_get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {- let tweet_id = Self::extract_tweet_id(url)- .ok_or_else(|| anyhow!("Could not extract tweet ID"))?;+ let tweet_id =+ Self::extract_tweet_id(url).ok_or_else(|| anyhow!("Could not extract tweet ID"))?;let filename_base = format!("twitter_{}", tweet_id);@@ -598,9 +590,12 @@ impl TwitterDownloader {})}TwitterMedia::Multiple(items) => {- let has_video = items- .iter()- .any(|i| matches!(i.media_type, TwitterMediaType::Video | TwitterMediaType::AnimatedGif));+ let has_video = items.iter().any(|i| {+ matches!(+ i.media_type,+ TwitterMediaType::Video | TwitterMediaType::AnimatedGif+ )+ });let media_type = if has_video {MediaType::Video@@ -634,10 +629,7 @@ impl TwitterDownloader {}}- async fn try_graphql(- &self,- tweet_id: &str,- ) -> anyhow::Result<Vec<serde_json::Value>> {+ async fn try_graphql(&self, tweet_id: &str) -> anyhow::Result<Vec<serde_json::Value>> {let token = self.get_guest_token(false).await?;match self.request_tweet(tweet_id, &token).await {diff --git a/src-tauri/src/plugin_loader.rs b/src-tauri/src/plugin_loader.rsindex 7636c55e..b1a1773a 100644--- a/src-tauri/src/plugin_loader.rs+++ b/src-tauri/src/plugin_loader.rs@@ -3,7 +3,7 @@ use std::fs;use std::path::{Path, PathBuf};use std::sync::Arc;-use omniget_plugin_sdk::{OmnigetPlugin, PluginHost, PluginManifest, InstalledPlugin, ABI_VERSION};+use omniget_plugin_sdk::{InstalledPlugin, OmnigetPlugin, PluginHost, PluginManifest, ABI_VERSION};use tracing;pub struct LoadedPlugin {@@ -32,7 +32,11 @@ impl PluginManager {}pub fn load_all(&mut self, host: Arc<dyn PluginHost>) {- tracing::info!("[plugins] load_all: {} installed, {} enabled", self.installed.len(), self.installed.iter().filter(|p| p.enabled).count());+ tracing::info!(+ "[plugins] load_all: {} installed, {} enabled",+ self.installed.len(),+ self.installed.iter().filter(|p| p.enabled).count()+ );let enabled: Vec<_> = self.installed.iter()@@ -44,7 +48,11 @@ impl PluginManager {let plugin_dir = self.plugins_dir.join(&entry.id);match load_single_plugin(&plugin_dir, host.clone()) {Ok(loaded) => {- tracing::info!("Loaded plugin: {} v{}", loaded.manifest.id, loaded.manifest.version);+ tracing::info!(+ "Loaded plugin: {} v{}",+ loaded.manifest.id,+ loaded.manifest.version+ );self.loaded.insert(entry.id.clone(), loaded);}Err(e) => {@@ -63,7 +71,11 @@ impl PluginManager {}pub fn installed_plugins(&self) -> &[InstalledPlugin] {- tracing::debug!("[plugins] installed_plugins() called, count={}, ids={:?}", self.installed.len(), self.installed.iter().map(|p| &p.id).collect::<Vec<_>>());+ tracing::debug!(+ "[plugins] installed_plugins() called, count={}, ids={:?}",+ self.installed.len(),+ self.installed.iter().map(|p| &p.id).collect::<Vec<_>>()+ );&self.installed}@@ -82,7 +94,10 @@ impl PluginManager {.get(plugin_id).ok_or_else(|| format!("Plugin '{}' not loaded", plugin_id))?;- loaded.plugin.handle_command(command.to_string(), args).await+ loaded+ .plugin+ .handle_command(command.to_string(), args)+ .await}pub fn save_installed(&self) -> anyhow::Result<()> {@@ -197,7 +212,11 @@ fn load_installed_list(plugins_dir: &Path) -> Vec<InstalledPlugin> {}};let content = content.strip_prefix('\u{FEFF}').unwrap_or(&content);- tracing::debug!("[plugins] installed.json raw ({} bytes): {}", content.len(), &content[..content.len().min(200)]);+ tracing::debug!(+ "[plugins] installed.json raw ({} bytes): {}",+ content.len(),+ &content[..content.len().min(200)]+ );#[derive(serde::Deserialize)]struct InstalledFile {@@ -206,12 +225,19 @@ fn load_installed_list(plugins_dir: &Path) -> Vec<InstalledPlugin> {match serde_json::from_str::<InstalledFile>(content) {Ok(f) => {- tracing::info!("[plugins] parsed {} installed plugins: {:?}", f.plugins.len(), f.plugins.iter().map(|p| &p.id).collect::<Vec<_>>());+ tracing::info!(+ "[plugins] parsed {} installed plugins: {:?}",+ f.plugins.len(),+ f.plugins.iter().map(|p| &p.id).collect::<Vec<_>>()+ );f.plugins}Err(e) => {tracing::error!("[plugins] FAILED to parse installed.json: {e}");- tracing::error!("[plugins] content was: {}", &content[..content.len().min(500)]);+ tracing::error!(+ "[plugins] content was: {}",+ &content[..content.len().min(500)]+ );Vec::new()}}diff --git a/src-tauri/src/tray.rs b/src-tauri/src/tray.rsindex 81f15aea..2d1735dc 100644--- a/src-tauri/src/tray.rs+++ b/src-tauri/src/tray.rs@@ -1,9 +1,9 @@-use std::sync::atomic::{AtomicU32, Ordering};-use std::sync::OnceLock;-use std::collections::HashMap;-use std::sync::Mutex;use std::collections::hash_map::DefaultHasher;+use std::collections::HashMap;use std::hash::{Hash, Hasher};+use std::sync::atomic::{AtomicU32, Ordering};+use std::sync::Mutex;+use std::sync::OnceLock;use tauri::{image::Image,@@ -54,10 +54,9 @@ impl BadgeCache {pub fn setup(app: &AppHandle) -> tauri::Result<()> {let open_item = MenuItemBuilder::with_id("open", "OmniGet").build(app)?;- let downloads_item =- MenuItemBuilder::with_id("downloads", active_label(0))- .enabled(false)- .build(app)?;+ let downloads_item = MenuItemBuilder::with_id("downloads", active_label(0))+ .enabled(false)+ .build(app)?;DOWNLOADS_ITEM.set(downloads_item.clone()).ok();let quit_item = MenuItemBuilder::with_id("quit", "Quit").build(app)?;@@ -175,7 +174,6 @@ pub fn show_window(app: &AppHandle) {}}-fn glyph(ch: char) -> [[bool; 3]; 5] {match ch {'0' => [@@ -262,7 +260,6 @@ fn glyph(ch: char) -> [[bool; 3]; 5] {const GLYPH_W: u32 = 3;const GLYPH_H: u32 = 5;-fn render_badge(base: &[u8], w: u32, h: u32, count: u32) -> Vec<u8> {let mut buf = base.to_vec();let size = w.min(h) as f32;@@ -331,11 +328,7 @@ fn render_badge(base: &[u8], w: u32, h: u32, count: u32) -> Vec<u8> {for sx in 0..scale {let px = ox + (col * scale + sx) as i32;let py = text_y + (row * scale + sy) as i32;- if px >= 0- && py >= 0- && (px as u32) < w- && (py as u32) < h- {+ if px >= 0 && py >= 0 && (px as u32) < w && (py as u32) < h {let idx = ((py as u32 * w + px as u32) * 4) as usize;if idx + 3 < buf.len() {buf[idx] = 255;@@ -423,11 +416,7 @@ fn render_overlay_badge(_base: &[u8], w: u32, h: u32, count: u32) -> Vec<u8> {for sx in 0..scale {let px = ox + (col * scale + sx) as i32;let py = text_y + (row * scale + sy) as i32;- if px >= 0- && py >= 0- && (px as u32) < w- && (py as u32) < h- {+ if px >= 0 && py >= 0 && (px as u32) < w && (py as u32) < h {let idx = ((py as u32 * w + px as u32) * 4) as usize;if idx + 3 < buf.len() {buf[idx] = 255;