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 consistency
Tonhob408d0e7cbcf
diff --git a/src-tauri/omniget-core/src/core/cookie_parser.rs b/src-tauri/omniget-core/src/core/cookie_parser.rsindex 3fd87b2f..d695ed3c 100644--- a/src-tauri/omniget-core/src/core/cookie_parser.rs+++ b/src-tauri/omniget-core/src/core/cookie_parser.rs@@ -1,10 +1,13 @@use std::collections::HashMap;use std::sync::Arc;-fn cookie_domain_matches(request_domain: &str, cookie_domain: &str, include_subdomains: bool) -> bool {+fn cookie_domain_matches(+ request_domain: &str,+ cookie_domain: &str,+ include_subdomains: bool,+) -> bool {if include_subdomains {- request_domain == cookie_domain- || request_domain.ends_with(&format!(".{}", cookie_domain))+ request_domain == cookie_domain || request_domain.ends_with(&format!(".{}", cookie_domain))} else {request_domain == cookie_domain}@@ -309,27 +312,51 @@ mod tests {#[test]fn host_only_matches_exact_only() {assert!(cookie_domain_matches("example.com", "example.com", false));- assert!(!cookie_domain_matches("sub.example.com", "example.com", false));- assert!(!cookie_domain_matches("example.com", "sub.example.com", false));+ assert!(!cookie_domain_matches(+ "sub.example.com",+ "example.com",+ false+ ));+ assert!(!cookie_domain_matches(+ "example.com",+ "sub.example.com",+ false+ ));}#[test]fn include_subdomains_allows_proper_suffix() {assert!(cookie_domain_matches("example.com", "example.com", true));- assert!(cookie_domain_matches("sub.example.com", "example.com", true));- assert!(cookie_domain_matches("a.b.example.com", "example.com", true));+ assert!(cookie_domain_matches(+ "sub.example.com",+ "example.com",+ true+ ));+ assert!(cookie_domain_matches(+ "a.b.example.com",+ "example.com",+ true+ ));}#[test]fn substring_false_positive_rejected() {assert!(!cookie_domain_matches("foo.com", "oo.com", true));assert!(!cookie_domain_matches("foo.com", "oo.com", false));- assert!(!cookie_domain_matches("notexample.com", "example.com", true));+ assert!(!cookie_domain_matches(+ "notexample.com",+ "example.com",+ true+ ));}#[test]fn parent_does_not_match_child_cookie() {- assert!(!cookie_domain_matches("example.com", "sub.example.com", true));+ assert!(!cookie_domain_matches(+ "example.com",+ "sub.example.com",+ true+ ));}#[test]@@ -420,8 +447,14 @@ mod tests {let parsed = parse_cookie_input("sessionid=abc; csrftoken=xyz", "sessionid");assert_eq!(parsed.token, "abc");- assert_eq!(parsed.cookies.get("sessionid").map(|s| s.as_str()), Some("abc"));- assert_eq!(parsed.cookies.get("csrftoken").map(|s| s.as_str()), Some("xyz"));+ assert_eq!(+ parsed.cookies.get("sessionid").map(|s| s.as_str()),+ Some("abc")+ );+ assert_eq!(+ parsed.cookies.get("csrftoken").map(|s| s.as_str()),+ Some("xyz")+ );}#[test]@@ -519,7 +552,8 @@ mod tests {#[test]fn parse_bearer_input_falls_back_to_auth_like_cookie_name() {- let input = r#"{"cookies":[{"name":"auth_session","value":"long_enough_session_value_xyz"}]}"#;+ let input =+ r#"{"cookies":[{"name":"auth_session","value":"long_enough_session_value_xyz"}]}"#;assert_eq!(parse_bearer_input(input), "long_enough_session_value_xyz");}@@ -545,7 +579,11 @@ mod tests {let request_domain = "sub.example.com".trim_start_matches('.').to_lowercase();let include_subdomains = raw_domain.starts_with('.');- assert!(cookie_domain_matches(&request_domain, &cookie_domain, include_subdomains));+ assert!(cookie_domain_matches(+ &request_domain,+ &cookie_domain,+ include_subdomains+ ));}#[test]@@ -554,6 +592,10 @@ mod tests {let cookie_domain = raw_domain.trim_start_matches('.').to_lowercase();let request_domain = "sub.example.com".trim_start_matches('.').to_lowercase();- assert!(!cookie_domain_matches(&request_domain, &cookie_domain, false));+ assert!(!cookie_domain_matches(+ &request_domain,+ &cookie_domain,+ false+ ));}}diff --git a/src-tauri/omniget-core/src/core/direct_downloader.rs b/src-tauri/omniget-core/src/core/direct_downloader.rsindex a13848e1..c02d0b76 100644--- a/src-tauri/omniget-core/src/core/direct_downloader.rs+++ b/src-tauri/omniget-core/src/core/direct_downloader.rs@@ -248,8 +248,8 @@ async fn run_http_fetcher(..Default::default()};- let mut fetcher = HttpFetcher::new(client.clone(), url.to_string(), output.to_path_buf())- .with_config(cfg);+ let mut fetcher =+ HttpFetcher::new(client.clone(), url.to_string(), output.to_path_buf()).with_config(cfg);if let Some(h) = headers {fetcher = fetcher.with_headers(h);}diff --git a/src-tauri/omniget-core/src/core/http_client.rs b/src-tauri/omniget-core/src/core/http_client.rsindex d5c87f32..8e4e32ce 100644--- a/src-tauri/omniget-core/src/core/http_client.rs+++ b/src-tauri/omniget-core/src/core/http_client.rs@@ -70,10 +70,7 @@ pub fn apply_global_proxy(builder: reqwest::ClientBuilder) -> reqwest::ClientBuiapply_proxy(builder, &proxy)}-pub fn inject_ua_header(- headers: &mut reqwest::header::HeaderMap,- opts_ua: Option<&str>,-) {+pub fn inject_ua_header(headers: &mut reqwest::header::HeaderMap, opts_ua: Option<&str>) {if let Some(ua) = opts_ua {if let Ok(v) = reqwest::header::HeaderValue::from_str(ua) {headers.insert(reqwest::header::USER_AGENT, v);diff --git a/src-tauri/omniget-core/src/core/http_fetcher.rs b/src-tauri/omniget-core/src/core/http_fetcher.rsindex 9816ec0e..975ca21e 100644--- a/src-tauri/omniget-core/src/core/http_fetcher.rs+++ b/src-tauri/omniget-core/src/core/http_fetcher.rs@@ -137,7 +137,8 @@ impl Segment {0}} else {- let bytes_per_sec = (cur_d - baseline_d) as u128 * 1_000_000_000u128 / elapsed_ns as u128;+ let bytes_per_sec =+ (cur_d - baseline_d) as u128 * 1_000_000_000u128 / elapsed_ns as u128;if bytes_per_sec == 0 {u64::MAX / 2} else {@@ -219,7 +220,11 @@ impl HttpFetcher {let initial_segments = if self.config.use_sidecar_resume {load_resume_state(&resume_path)- .filter(|st| st.r#type == "http_segmented" && st.total_bytes == total && st.url_hash == url_hash)+ .filter(|st| {+ st.r#type == "http_segmented"+ && st.total_bytes == total+ && st.url_hash == url_hash+ }).map(|st| st.segments)} else {None@@ -227,13 +232,24 @@ impl HttpFetcher {let segments = match initial_segments {Some(segs) if !segs.is_empty() => segs,- _ => plan_segments(total, self.config.segment_size_hint, self.config.concurrent_segments),+ _ => plan_segments(+ total,+ self.config.segment_size_hint,+ self.config.concurrent_segments,+ ),};ensure_part_file(&part_path, total).await?;let result = self- .download_chunked(&part_path, total, segments, &resume_path, &url_hash, &progress_tx)+ .download_chunked(+ &part_path,+ total,+ segments,+ &resume_path,+ &url_hash,+ &progress_tx,+ ).await;match result {@@ -249,7 +265,9 @@ impl HttpFetcher {.await.map(|m| m.len()).unwrap_or(total);- Ok(HttpFetcherResult { bytes_written: bytes })+ Ok(HttpFetcherResult {+ bytes_written: bytes,+ })}Err(e) => Err(e),}@@ -320,7 +338,12 @@ impl HttpFetcher {}Ok(Some(Err(e))) => return Err(anyhow!("stream error: {}", e)),Ok(None) => break,- Err(_) => return Err(anyhow!("read timed out after {:?}", self.config.read_timeout)),+ Err(_) => {+ return Err(anyhow!(+ "read timed out after {:?}",+ self.config.read_timeout+ ))+ }}}@@ -546,7 +569,17 @@ async fn worker_loop(if cancel.is_cancelled() {return Ok(());}- match download_segment(&client, &url, headers.as_ref(), &part_path, &seg, &cancel, &cfg).await {+ match download_segment(+ &client,+ &url,+ headers.as_ref(),+ &part_path,+ &seg,+ &cancel,+ &cfg,+ )+ .await+ {Ok(()) => {seg.state.store(SEG_DONE, Ordering::Relaxed);break;@@ -604,10 +637,7 @@ async fn claim_pending_or_steal(None}-fn try_steal(- segs: &mut Vec<Arc<Segment>>,- cfg: &HttpFetcherConfig,-) -> Option<Arc<Segment>> {+fn try_steal(segs: &mut Vec<Arc<Segment>>, cfg: &HttpFetcherConfig) -> Option<Arc<Segment>> {let mut victim: Option<Arc<Segment>> = None;let mut victim_score: u64 = 0;for s in segs.iter() {@@ -642,7 +672,9 @@ fn try_steal(if new_begin_for_helper <= victim.begin + victim.downloaded.load(Ordering::Relaxed) {return None;}- victim.end_ceiling.store(new_end_for_victim, Ordering::Relaxed);+ victim+ .end_ceiling+ .store(new_end_for_victim, Ordering::Relaxed);let next_id = segs.iter().map(|s| s.id).max().unwrap_or(0) + 1;let helper = Arc::new(Segment::new(next_id, new_begin_for_helper, old_end, 0));@@ -968,10 +1000,8 @@ mod tests {#[tokio::test]async fn fetcher_downloads_small_file_streaming() {use std::io::Write;- let temp_dir = std::env::temp_dir().join(format!(- "omniget_http_fetcher_test_{}",- now_unix_nanos()- ));+ let temp_dir =+ std::env::temp_dir().join(format!("omniget_http_fetcher_test_{}", now_unix_nanos()));std::fs::create_dir_all(&temp_dir).unwrap();let payload: Vec<u8> = (0u8..=255).cycle().take(200_000).collect();@@ -980,7 +1010,9 @@ mod tests {let payload_for_server = payload.clone();tokio::spawn(async move {loop {- let Ok((mut stream, _)) = listener.accept().await else { break };+ let Ok((mut stream, _)) = listener.accept().await else {+ break;+ };let body = payload_for_server.clone();tokio::spawn(async move {use tokio::io::AsyncReadExt;@@ -1092,10 +1124,8 @@ mod tests {#[tokio::test]async fn fetcher_downloads_multi_segment_with_range() {- let temp_dir = std::env::temp_dir().join(format!(- "omniget_http_fetcher_chunked_{}",- now_unix_nanos()- ));+ let temp_dir =+ std::env::temp_dir().join(format!("omniget_http_fetcher_chunked_{}", now_unix_nanos()));std::fs::create_dir_all(&temp_dir).unwrap();let payload: Vec<u8> = (0u8..=255).cycle().take(2 * 1024 * 1024).collect();@@ -1212,10 +1242,8 @@ mod tests {#[tokio::test]async fn fetcher_resume_sidecar_round_trip() {- let temp_dir = std::env::temp_dir().join(format!(- "omniget_http_fetcher_resume_{}",- now_unix_nanos()- ));+ let temp_dir =+ std::env::temp_dir().join(format!("omniget_http_fetcher_resume_{}", now_unix_nanos()));std::fs::create_dir_all(&temp_dir).unwrap();let path = temp_dir.join("video.mp4.part.resume.json");let state = ResumeState {diff --git a/src-tauri/omniget-core/src/core/log_hook.rs b/src-tauri/omniget-core/src/core/log_hook.rsindex 145f38a0..6ebd5d04 100644--- a/src-tauri/omniget-core/src/core/log_hook.rs+++ b/src-tauri/omniget-core/src/core/log_hook.rs@@ -16,8 +16,13 @@ pub fn emit_log(id: u64, line: &str) {tokio::task_local! {pub static CURRENT_DOWNLOAD_ID: u64;+ pub static CURRENT_COOKIE_SLUG: Option<String>;}pub fn current_download_id() -> Option<u64> {CURRENT_DOWNLOAD_ID.try_with(|v| *v).ok()}++pub fn current_cookie_slug() -> Option<String> {+ CURRENT_COOKIE_SLUG.try_with(|v| v.clone()).ok().flatten()+}diff --git a/src-tauri/omniget-core/src/core/pdfium.rs b/src-tauri/omniget-core/src/core/pdfium.rsindex 01cb7d9c..88306683 100644--- a/src-tauri/omniget-core/src/core/pdfium.rs+++ b/src-tauri/omniget-core/src/core/pdfium.rs@@ -115,9 +115,7 @@ pub fn pdfium_version_marker_path() -> Option<PathBuf> {}pub fn is_installed() -> bool {- pdfium_target_path()- .map(|p| p.is_file())- .unwrap_or(false)+ pdfium_target_path().map(|p| p.is_file()).unwrap_or(false)}pub fn read_version_marker() -> Option<String> {@@ -135,14 +133,11 @@ pub async fn ensure_pdfium() -> anyhow::Result<PathBuf> {ensure_pdfium_with_variant(None).await}-pub async fn ensure_pdfium_with_variant(- variant: Option<String>,-) -> anyhow::Result<PathBuf> {+pub async fn ensure_pdfium_with_variant(variant: Option<String>) -> anyhow::Result<PathBuf> {let target_dir =pdfium_target_dir().ok_or_else(|| anyhow!("could not determine app data dir"))?;- std::fs::create_dir_all(&target_dir).with_context(|| {- format!("creating pdfium target dir {}", target_dir.display())- })?;+ std::fs::create_dir_all(&target_dir)+ .with_context(|| format!("creating pdfium target dir {}", target_dir.display()))?;let archive_name = archive_name_for_variant(variant.as_deref());let url = format!("{}/{}", PDFIUM_DOWNLOAD_BASE, archive_name);@@ -174,11 +169,12 @@ pub async fn ensure_pdfium_with_variant(let target_path_clone = target_path.clone();let target_dir_clone = target_dir.clone();let lib_name = lib_filename.to_string();- let extracted_version = tokio::task::spawn_blocking(move || -> anyhow::Result<Option<String>> {- extract_pdfium_archive(&bytes, &target_path_clone, &target_dir_clone, &lib_name)- })- .await- .map_err(|e| anyhow!("spawn_blocking failed: {}", e))??;+ let extracted_version =+ tokio::task::spawn_blocking(move || -> anyhow::Result<Option<String>> {+ extract_pdfium_archive(&bytes, &target_path_clone, &target_dir_clone, &lib_name)+ })+ .await+ .map_err(|e| anyhow!("spawn_blocking failed: {}", e))??;if let Some(version_marker) = pdfium_version_marker_path() {let base = extracted_version.unwrap_or_else(|| "latest".to_string());@@ -205,16 +201,12 @@ pub async fn ensure_pdfium_with_variant(pub fn set_pdfium_from_path(source: &Path) -> anyhow::Result<PathBuf> {if !source.is_file() {- return Err(anyhow!(- "source not a file: {}",- source.display()- ));+ return Err(anyhow!("source not a file: {}", source.display()));}let target_dir =pdfium_target_dir().ok_or_else(|| anyhow!("could not determine app data dir"))?;- std::fs::create_dir_all(&target_dir).with_context(|| {- format!("creating pdfium target dir {}", target_dir.display())- })?;+ std::fs::create_dir_all(&target_dir)+ .with_context(|| format!("creating pdfium target dir {}", target_dir.display()))?;let lib_filename = pdfium_lib_filename();let target_path = target_dir.join(lib_filename);@@ -263,15 +255,13 @@ fn extract_pdfium_archive(let mut buf = Vec::new();entry.read_to_end(&mut buf)?;let tmp = target_dir.join(format!(".{}.tmp", lib_filename));- std::fs::write(&tmp, &buf).with_context(|| {- format!("writing temp pdfium lib {}", tmp.display())- })?;+ std::fs::write(&tmp, &buf)+ .with_context(|| format!("writing temp pdfium lib {}", tmp.display()))?;if target_path.exists() {let _ = std::fs::remove_file(target_path);}- std::fs::rename(&tmp, target_path).with_context(|| {- format!("moving pdfium to {}", target_path.display())- })?;+ std::fs::rename(&tmp, target_path)+ .with_context(|| format!("moving pdfium to {}", target_path.display()))?;found_lib = true;} else if file_name == "VERSION" {let mut buf = String::new();@@ -281,10 +271,7 @@ fn extract_pdfium_archive(}if !found_lib {- return Err(anyhow!(- "{} not found inside pdfium archive",- lib_filename- ));+ return Err(anyhow!("{} not found inside pdfium archive", lib_filename));}Ok(version)diff --git a/src-tauri/omniget-core/src/core/ytdlp.rs b/src-tauri/omniget-core/src/core/ytdlp.rsindex a01258ba..4f61b09c 100644--- a/src-tauri/omniget-core/src/core/ytdlp.rs+++ b/src-tauri/omniget-core/src/core/ytdlp.rs@@ -22,6 +22,7 @@ type TranslateMetadataFn = Box<dyn Fn() -> Option<String> + Send + Sync>;type SponsorBlockFn = Box<dyn Fn() -> bool + Send + Sync>;type SplitChaptersFn = Box<dyn Fn() -> bool + Send + Sync>;type PerDomainCookieFn = Box<dyn Fn(&str) -> Option<PathBuf> + Send + Sync>;+type ManagedCookiesOnlyFn = Box<dyn Fn() -> bool + Send + Sync>;static EXT_COOKIE_PATH_FN: OnceLock<ExtCookiePathFn> = OnceLock::new();static GLOBAL_COOKIE_FILE_FN: OnceLock<GlobalCookieFileFn> = OnceLock::new();@@ -30,6 +31,7 @@ static MANUAL_COOKIE_HEADER_FN: OnceLock<ManualCookieHeaderFn> = OnceLock::new()static EXT_REFERER_FN: OnceLock<ExtRefererFn> = OnceLock::new();static INCLUDE_AUTO_SUBS_FN: OnceLock<IncludeAutoSubsFn> = OnceLock::new();static PER_DOMAIN_COOKIE_FN: OnceLock<PerDomainCookieFn> = OnceLock::new();+static MANAGED_COOKIES_ONLY_FN: OnceLock<ManagedCookiesOnlyFn> = OnceLock::new();static TRANSLATE_METADATA_FN: OnceLock<TranslateMetadataFn> = OnceLock::new();static SPONSORBLOCK_FN: OnceLock<SponsorBlockFn> = OnceLock::new();static SPLIT_CHAPTERS_FN: OnceLock<SplitChaptersFn> = OnceLock::new();@@ -42,6 +44,14 @@ pub fn set_per_domain_cookie_fn(f: impl Fn(&str) -> Option<PathBuf> + Send + Synlet _ = PER_DOMAIN_COOKIE_FN.set(Box::new(f));}+pub fn set_managed_cookies_only_fn(f: impl Fn() -> bool + Send + Sync + 'static) {+ let _ = MANAGED_COOKIES_ONLY_FN.set(Box::new(f));+}++fn managed_cookies_only() -> bool {+ MANAGED_COOKIES_ONLY_FN.get().map(|f| f()).unwrap_or(true)+}+pub fn set_global_cookie_file_fn(f: impl Fn() -> Option<String> + Send + Sync + 'static) {let _ = GLOBAL_COOKIE_FILE_FN.set(Box::new(f));}@@ -63,10 +73,7 @@ pub fn set_include_auto_subs_fn(f: impl Fn() -> bool + Send + Sync + 'static) {}fn include_auto_subs_setting() -> bool {- INCLUDE_AUTO_SUBS_FN- .get()- .map(|f| f())- .unwrap_or(false)+ INCLUDE_AUTO_SUBS_FN.get().map(|f| f()).unwrap_or(false)}pub fn set_translate_metadata_fn(f: impl Fn() -> Option<String> + Send + Sync + 'static) {@@ -112,10 +119,7 @@ pub fn clear_ext_user_agent(url: &str) {}fn ext_user_agent_for_url(url: &str) -> Option<String> {- ext_ua_map()- .lock()- .ok()- .and_then(|m| m.get(url).cloned())+ ext_ua_map().lock().ok().and_then(|m| m.get(url).cloned())}static ETA_BY_DOWNLOAD: OnceLock<Mutex<HashMap<u64, u64>>> = OnceLock::new();@@ -131,7 +135,10 @@ pub fn record_eta(download_id: u64, eta_seconds: u64) {}pub fn get_eta(download_id: u64) -> Option<u64> {- eta_map().lock().ok().and_then(|m| m.get(&download_id).copied())+ eta_map()+ .lock()+ .ok()+ .and_then(|m| m.get(&download_id).copied())}pub fn clear_eta(download_id: u64) {@@ -177,7 +184,10 @@ fn cookies_from_browser_setting() -> String {}fn manual_cookie_header_setting() -> Option<String> {- let raw = MANUAL_COOKIE_HEADER_FN.get().map(|f| f()).unwrap_or_default();+ let raw = MANUAL_COOKIE_HEADER_FN+ .get()+ .map(|f| f())+ .unwrap_or_default();let trimmed = raw.trim();if trimmed.is_empty() {return None;@@ -1254,7 +1264,25 @@ pub async fn download_video();let format_selector = if let Some(fid) = format_id {- fid.to_string()+ if let Some(h) = quality_height.filter(|h| *h > 0) {+ let fallback = match mode {+ "audio" => "ba/b".to_string(),+ "mute" => format!("bv*[height<={}]/bv*/b", h),+ _ => {+ if ffmpeg_available {+ format!(+ "bv*[height<={}]+ba[ext=m4a]/bv*[height<={}]+ba/b[height<={}]/b",+ h, h, h+ )+ } else {+ format!("b[height<={}]/bv*[height<={}]/b", h, h)+ }+ }+ };+ format!("{}/{}", fid, fallback)+ } else {+ fid.to_string()+ }} else {match mode {"audio" => "ba/b".to_string(),@@ -1301,42 +1329,98 @@ pub async fn download_video(} else {per_domain_cookie_file(url)};- let manual_cookie_header = if explicit_cookie_header- || cookie_file.is_some()- || per_domain_cookies.is_some()- {- None- } else {+ let managed_only = managed_cookies_only();+ let allow_fallback = !managed_only+ && !explicit_cookie_header+ && cookie_file.is_none()+ && per_domain_cookies.is_none();++ let manual_cookie_header = if allow_fallback {manual_cookie_header_setting()+ } else {+ None};let manual_cookie_enabled = manual_cookie_header.is_some();- let global_cookie_file = if manual_cookie_enabled || per_domain_cookies.is_some() {- None- } else {+ let global_cookie_file = if allow_fallback && !manual_cookie_enabled {global_cookie_file()+ } else {+ None};- let ext_cookies = if cookie_file.is_none()- && global_cookie_file.is_none()- && !manual_cookie_enabled- && per_domain_cookies.is_none()- {+ let ext_cookies = if allow_fallback && !manual_cookie_enabled && global_cookie_file.is_none() {extension_cookie_file()} else {None};+ let had_global_cookie_file = global_cookie_file.is_some();+ let had_ext_cookies = ext_cookies.is_some();+let effective_cookie_file = cookie_file.map(|p| p.to_path_buf()).or_else(|| per_domain_cookies.clone()).or_else(|| global_cookie_file.map(std::path::PathBuf::from)).or(ext_cookies);- let cfb_setting = if manual_cookie_enabled || explicit_cookie_header || effective_cookie_file.is_some() {+ let cfb_setting = if !allow_fallback+ || manual_cookie_enabled+ || explicit_cookie_header+ || effective_cookie_file.is_some()+ {String::new()} else {cookies_from_browser_setting()};++ if let Some(dl_id) = log_hook::current_download_id() {+ let host = url::Url::parse(url)+ .ok()+ .and_then(|u| u.host_str().map(|s| s.to_string()))+ .unwrap_or_else(|| url.to_string());+ let slug = log_hook::current_cookie_slug();+ let line = if explicit_cookie_header {+ "[cookies] using explicit Cookie header from extra flags".to_string()+ } else if cookie_file.is_some() {+ "[cookies] using caller-supplied cookie file".to_string()+ } else if let Some(ref p) = per_domain_cookies {+ let slug_label = slug.as_deref().unwrap_or("_default");+ format!(+ "[cookies] using managed cookie for {} (account: {}) → {}",+ host,+ slug_label,+ p.file_name()+ .map(|s| s.to_string_lossy().to_string())+ .unwrap_or_default()+ )+ } else if manual_cookie_enabled {+ format!(+ "[cookies] no managed cookie for {}; using manual Cookie header from settings",+ host+ )+ } else if had_global_cookie_file {+ format!(+ "[cookies] no managed cookie for {}; using global cookie file from settings",+ host+ )+ } else if had_ext_cookies {+ format!(+ "[cookies] no managed cookie for {}; using browser-extension cookies",+ host+ )+ } else if !cfb_setting.is_empty() {+ format!(+ "[cookies] no managed cookie for {}; using --cookies-from-browser {}",+ host, cfb_setting+ )+ } else {+ format!(+ "[cookies] no cookies available for {} — downloading without auth",+ host+ )+ };+ log_hook::emit_log(dl_id, &line);+ }+let mut base_args = vec!["-f".to_string(),format_selector,@@ -1347,9 +1431,9 @@ pub async fn download_video(];base_args.extend(js_runtime_args());- if format_id.is_none() && mode == "audio" {+ if mode == "audio" {let target_fmt = audio_format.unwrap_or("m4a");- if target_fmt == "m4a" {+ if format_id.is_none() && target_fmt == "m4a" {base_args.push("-S".to_string());base_args.push("+codec:aac:m4a".to_string());} else {@@ -2017,8 +2101,7 @@ fn translate_ytdlp_error(stderr: &str) -> anyhow::Error {|| stderr.contains("需要登录")|| stderr.contains("登录后可")|| stderr.contains("仅登录用户")- || lower.contains("this video is only available")- && lower.contains("members")+ || lower.contains("this video is only available") && lower.contains("members"){return anyhow!("This video requires login. Import cookies for this site in Settings → Cookies, then retry."@@ -2375,10 +2458,7 @@ mod tests {#[test]fn parse_progress_with_eta_field() {- assert_eq!(- parse_progress_line("download: 45.2%|eta:30"),- Some(45.2)- );+ assert_eq!(parse_progress_line("download: 45.2%|eta:30"), Some(45.2));}#[test]diff --git a/src-tauri/omniget-core/src/models/media.rs b/src-tauri/omniget-core/src/models/media.rsindex 1d4ac250..06a90fb0 100644--- a/src-tauri/omniget-core/src/models/media.rs+++ b/src-tauri/omniget-core/src/models/media.rs@@ -56,6 +56,7 @@ pub struct DownloadOptions {pub ytdlp_path: Option<PathBuf>,pub torrent_listen_port: Option<u16>,pub torrent_id_slot: Option<std::sync::Arc<tokio::sync::Mutex<Option<usize>>>>,+ pub custom_ytdlp_args: Option<Vec<String>>,}#[derive(Debug, Clone, Serialize, Deserialize)]diff --git a/src-tauri/omniget-core/src/models/settings.rs b/src-tauri/omniget-core/src/models/settings.rsindex 1bee40dc..dbfd0aa2 100644--- a/src-tauri/omniget-core/src/models/settings.rs+++ b/src-tauri/omniget-core/src/models/settings.rs@@ -131,6 +131,8 @@ pub struct DownloadSettings {pub copy_to_clipboard_on_hotkey: bool,#[serde(default)]pub cookie_file: String,+ #[serde(default = "default_true")]+ pub always_use_managed_cookies: bool,#[serde(default)]pub continuous_lecture_numbers: bool,}@@ -358,6 +360,7 @@ impl Default for AppSettings {extra_ytdlp_flags: Vec::new(),copy_to_clipboard_on_hotkey: true,cookie_file: String::new(),+ always_use_managed_cookies: true,continuous_lecture_numbers: false,},advanced: AdvancedSettings {diff --git a/src-tauri/omniget-plugin-sdk/src/host.rs b/src-tauri/omniget-plugin-sdk/src/host.rsindex a79c8b6a..d7fd6bd0 100644--- a/src-tauri/omniget-plugin-sdk/src/host.rs+++ b/src-tauri/omniget-plugin-sdk/src/host.rs@@ -106,6 +106,17 @@ pub trait PluginHost: Send + Sync {fn cookie_status(&self, _domain: &str) -> CookieStatus {CookieStatus::Missing}++ /// Append a line to the user-visible download log for `download_id`.+ ///+ /// Plugins should use this to surface progress and errors that the user+ /// can see and copy when reporting a bug. The host routes the line through+ /// the same `download-log-update` Tauri event the core uses for the queue,+ /// so the line appears in the `DownloadLog` component for that download.+ ///+ /// Default impl is a no-op so plugins compiled against SDK ≥ this version+ /// still load on older hosts without ABI breakage.+ fn emit_download_log(&self, _download_id: u64, _line: &str) {}}#[derive(Debug, Clone)]diff --git a/src-tauri/src/commands/browser_extension.rs b/src-tauri/src/commands/browser_extension.rsindex 73a9443e..4544b7b8 100644--- a/src-tauri/src/commands/browser_extension.rs+++ b/src-tauri/src/commands/browser_extension.rs@@ -15,7 +15,10 @@ pub struct BrowserExtensionStatus {fn read_bundled_manifest_version(app: &AppHandle, browser: &str) -> Option<String> {let resource = format!("browser-extension/{}/manifest.json", browser);- let path = app.path().resolve(resource, tauri::path::BaseDirectory::Resource).ok()?;+ let path = app+ .path()+ .resolve(resource, tauri::path::BaseDirectory::Resource)+ .ok()?;let raw = std::fs::read_to_string(&path).ok()?;let v: serde_json::Value = serde_json::from_str(&raw).ok()?;v.get("version")?.as_str().map(|s| s.to_string())@@ -96,7 +99,7 @@ pub async fn browser_extension_export(if browser != "chrome" && browser != "firefox" {return Err(format!("browser '{}' não suportado pra export", browser));}- let resource = format!("../browser-extension/{}", browser);+ let resource = format!("browser-extension/{}", browser);let src = app.path().resolve(resource, tauri::path::BaseDirectory::Resource)diff --git a/src-tauri/src/commands/dependencies.rs b/src-tauri/src/commands/dependencies.rsindex c9c3671e..2b1d3fab 100644--- a/src-tauri/src/commands/dependencies.rs+++ b/src-tauri/src/commands/dependencies.rs@@ -57,10 +57,7 @@ pub async fn check_ytdlp_available() -> Result<bool, String> {}#[tauri::command]-pub async fn install_dependency(- name: String,- variant: Option<String>,-) -> Result<String, String> {+pub async fn install_dependency(name: String, variant: Option<String>) -> Result<String, String> {match name.as_str() {"yt-dlp" => {crate::core::ytdlp::ensure_ytdlp()@@ -79,8 +76,7 @@ pub async fn install_dependency(let _path: PathBuf = pdfium::ensure_pdfium_with_variant(variant).await.map_err(|e| e.to_string())?;- return Ok(pdfium::read_version_marker()- .unwrap_or_else(|| "installed".to_string()));+ return Ok(pdfium::read_version_marker().unwrap_or_else(|| "installed".to_string()));}_ => return Err(format!("Unknown dependency: {}", name)),}@@ -128,12 +124,8 @@ pub fn set_dependency_path(name: String, source_path: String) -> Result<String,match name.as_str() {"PDFium" => {pdfium::set_pdfium_from_path(&src).map_err(|e| e.to_string())?;- Ok(pdfium::read_version_marker()- .unwrap_or_else(|| "custom".to_string()))+ Ok(pdfium::read_version_marker().unwrap_or_else(|| "custom".to_string()))}- _ => Err(format!(- "Custom file path not supported for: {}",- name- )),+ _ => Err(format!("Custom file path not supported for: {}", name)),}}diff --git a/src-tauri/src/commands/downloads.rs b/src-tauri/src/commands/downloads.rsindex 115067dd..5178cecd 100644--- a/src-tauri/src/commands/downloads.rs+++ b/src-tauri/src/commands/downloads.rs@@ -1,3 +1,5 @@+use std::sync::Arc;+use serde::Serialize;use crate::core::queue::{self, emit_queue_state_from_state, QueueItemInfo};@@ -156,6 +158,7 @@ pub async fn download_from_url(quality: Option<String>,format_id: Option<String>,referer: Option<String>,+ cookie_slug: Option<String>,) -> Result<DownloadStarted, String> {let _timer_start = std::time::Instant::now();let platform = Platform::from_url(&url);@@ -223,6 +226,8 @@ pub async fn download_from_url(downloader,ytdlp_path,false,+ cookie_slug,+ None,);let next_ids = q.next_queued_ids();@@ -270,6 +275,108 @@ pub async fn download_from_url(})}+#[cfg(not(target_os = "android"))]+#[tauri::command]+pub async fn download_with_custom_args(+ app: tauri::AppHandle,+ state: tauri::State<'_, AppState>,+ url: String,+ output_dir: String,+ custom_args: Vec<String>,+ cookie_slug: Option<String>,+) -> Result<DownloadStarted, String> {+ if url.trim().is_empty() {+ return Err("URL is required".to_string());+ }+ if let Err(err) = crate::core::path_limits::validate_output_dir(&output_dir) {+ return Err(format!(+ "PathTooLong|{}|{}|{}",+ err.limit, err.current, err.reserve+ ));+ }++ let download_id = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default()+ .as_millis() as u64;++ let download_queue = state.download_queue.clone();+ {+ let settings = config::load_settings(&app);+ let mut q = download_queue.lock().await;+ q.max_concurrent = settings.advanced.max_concurrent_downloads.max(1);+ q.stagger_delay_ms = settings.advanced.stagger_delay_ms;+ q.default_max_retries = settings.advanced.max_retries;+ if q.has_url(&url) {+ return Err("Download already in progress for this URL".to_string());+ }+ }++ let downloader: Arc<dyn crate::platforms::traits::PlatformDownloader> =+ Arc::new(crate::platforms::generic_ytdlp::GenericYtdlpDownloader::new());++ let title = url.clone();+ let ytdlp_path = ytdlp::find_ytdlp_cached().await;++ let state_to_emit = {+ let mut q = download_queue.lock().await;+ q.enqueue(+ download_id,+ url,+ "generic".to_string(),+ title.clone(),+ output_dir,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ downloader,+ ytdlp_path,+ false,+ cookie_slug,+ Some(custom_args),+ );+ let next_ids = q.next_queued_ids();+ for nid in &next_ids {+ q.mark_active(*nid);+ }+ q.get_state()+ };+ emit_queue_state_from_state(&app, state_to_emit);++ let q_clone = download_queue.clone();+ let app_clone = app.clone();+ tokio::spawn(async move {+ let ids_to_start = {+ let q = q_clone.lock().await;+ q.items+ .iter()+ .filter(|i| i.status == queue::QueueStatus::Active)+ .filter(|i| i.id == download_id)+ .map(|i| i.id)+ .collect::<Vec<_>>()+ };+ for nid in ids_to_start {+ let a = app_clone.clone();+ let qc = q_clone.clone();+ tokio::spawn(async move {+ queue::spawn_download(a, qc, nid).await;+ });+ }+ });++ Ok(DownloadStarted {+ id: download_id,+ title,+ })+}+#[tauri::command]pub async fn cancel_generic_download(app: tauri::AppHandle,@@ -472,6 +579,7 @@ pub async fn restore_recovery(item.quality,item.format_id,item.referer,+ None,).await{@@ -484,8 +592,7 @@ pub async fn restore_recovery(#[tauri::command]pub fn parse_batch_file(path: String) -> Result<Vec<String>, String> {- let content = std::fs::read_to_string(&path)- .map_err(|e| format!("Read error: {}", e))?;+ let content = std::fs::read_to_string(&path).map_err(|e| format!("Read error: {}", e))?;let mut urls = Vec::new();for raw in content.lines() {let line = raw.trim();diff --git a/src-tauri/src/commands/extension_cookies.rs b/src-tauri/src/commands/extension_cookies.rsindex 16147eeb..150db0d2 100644--- a/src-tauri/src/commands/extension_cookies.rs+++ b/src-tauri/src/commands/extension_cookies.rs@@ -110,10 +110,13 @@ const WELL_KNOWN_NAMES: &[&str] = &["PREF",];-fn cookie_domain_matches(request_domain: &str, cookie_domain: &str, include_subdomains: bool) -> bool {+fn cookie_domain_matches(+ request_domain: &str,+ cookie_domain: &str,+ include_subdomains: bool,+) -> bool {if include_subdomains {- request_domain == cookie_domain- || request_domain.ends_with(&format!(".{}", cookie_domain))+ request_domain == cookie_domain || request_domain.ends_with(&format!(".{}", cookie_domain))} else {request_domain == cookie_domain}diff --git a/src-tauri/src/commands/host_queue.rs b/src-tauri/src/commands/host_queue.rsindex 69ed5284..57629b9e 100644--- a/src-tauri/src/commands/host_queue.rs+++ b/src-tauri/src/commands/host_queue.rs@@ -48,7 +48,9 @@ pub async fn enqueue_external_inner(forced_id: Option<u64>,) -> Result<u64, String> {let queue_id = forced_id.unwrap_or_else(next_external_id);- let kind = args.kind.unwrap_or_else(|| kind_from_platform(&args.platform));+ let kind = args+ .kind+ .unwrap_or_else(|| kind_from_platform(&args.platform));let output_dir = args.output_path.parent()@@ -92,6 +94,8 @@ pub async fn enqueue_external_inner(concurrent_segments: None,segment_size_bytes: None,eta_seconds: None,+ cookie_slug: None,+ custom_ytdlp_args: None,};{@@ -106,7 +110,12 @@ pub async fn enqueue_external_inner(};emit_queue_state_from_state(app, snapshot);- tracing::info!("[host-queue] enqueue_external id={} platform={} kind={:?}", queue_id, args.platform, kind);+ tracing::info!(+ "[host-queue] enqueue_external id={} platform={} kind={:?}",+ queue_id,+ args.platform,+ kind+ );Ok(queue_id)}@@ -203,7 +212,10 @@ pub async fn report_complete_inner(}it.status = QueueStatus::Complete { success: true };} else {- let msg = args.error.clone().unwrap_or_else(|| "Unknown error".to_string());+ let msg = args+ .error+ .clone()+ .unwrap_or_else(|| "Unknown error".to_string());let retryable = crate::core::queue::is_retryable_error_message(&msg);it.status = QueueStatus::Error {message: msg,@@ -256,7 +268,9 @@ pub fn register_event_listeners(app: &AppHandle) {let app = app_for_enqueue.clone();tauri::async_runtime::spawn(async move {let state = app.state::<AppState>();- if let Err(e) = enqueue_external_inner(&app, &state, p.args, Some(p.queue_id)).await {+ if let Err(e) =+ enqueue_external_inner(&app, &state, p.args, Some(p.queue_id)).await+ {tracing::warn!("[host-queue] enqueue listener failed: {}", e);}});diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rsindex 91d8a693..83cbd8ad 100644--- a/src-tauri/src/commands/mod.rs+++ b/src-tauri/src/commands/mod.rs@@ -1,11 +1,11 @@pub mod app_lifecycle;pub mod auth_webview;-pub mod browser_extension;-pub mod extension_cookies;pub mod autostart;+pub mod browser_extension;pub mod clip;pub mod diagnostics;pub mod downloads;+pub mod extension_cookies;pub mod host_queue;pub mod integration;pub mod p2p;@@ -13,6 +13,7 @@ pub mod plugins;pub mod reencode;pub mod rpc;pub mod settings;+pub mod yt_templates;#[cfg(not(target_os = "android"))]pub mod dependencies;diff --git a/src-tauri/src/commands/plugins.rs b/src-tauri/src/commands/plugins.rsindex f78a0995..b5d6ceb4 100644--- a/src-tauri/src/commands/plugins.rs+++ b/src-tauri/src/commands/plugins.rs@@ -400,7 +400,10 @@ pub async fn ensure_default_plugins(state: Arc<tokio::sync::RwLock<PluginManagerfor (plugin_id, repo) in DEFAULT_PLUGINS {let already_installed = {let manager = state.read().await;- manager.installed_plugins().iter().any(|p| p.id == *plugin_id)+ manager+ .installed_plugins()+ .iter()+ .any(|p| p.id == *plugin_id)};if already_installed {tracing::debug!("default plugin '{}' already installed, skipping", plugin_id);diff --git a/src-tauri/src/commands/reencode.rs b/src-tauri/src/commands/reencode.rsindex e0c4ea7a..3865b7e8 100644--- a/src-tauri/src/commands/reencode.rs+++ b/src-tauri/src/commands/reencode.rs@@ -44,9 +44,7 @@ pub async fn reencode_video(req: ReencodeRequest) -> Result<ReencodeResult, Striif !input.is_file() {return Err(format!("source not found: {}", req.input_path));}- let original_size = std::fs::metadata(&input)- .map(|m| m.len())- .unwrap_or(0);+ let original_size = std::fs::metadata(&input).map(|m| m.len()).unwrap_or(0);let output = req.output_path.clone().unwrap_or_else(|| {let stem = input.file_stem().and_then(|s| s.to_str()).unwrap_or("out");diff --git a/src-tauri/src/commands/rpc.rs b/src-tauri/src/commands/rpc.rsindex eeb4cd1b..44b88992 100644--- a/src-tauri/src/commands/rpc.rs+++ b/src-tauri/src/commands/rpc.rs@@ -35,10 +35,7 @@ pub async fn rpc_set_source(}#[tauri::command]-pub async fn rpc_clear_source(- app: tauri::AppHandle,- source: String,-) -> Result<Value, String> {+pub async fn rpc_clear_source(app: tauri::AppHandle, source: String) -> Result<Value, String> {let settings = config::load_settings(&app);rpc::clear_source(settings.rpc.clone(), source).await}diff --git a/src-tauri/src/commands/yt_templates.rs b/src-tauri/src/commands/yt_templates.rsnew file mode 100644index 00000000..74ef3c8d--- /dev/null+++ b/src-tauri/src/commands/yt_templates.rs@@ -0,0 +1,110 @@+use std::fs;+use std::path::PathBuf;++use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct YtTemplate {+ pub id: String,+ pub name: String,+ pub args: Vec<String>,+ pub created_at_ms: i64,+ pub updated_at_ms: i64,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct YtTemplateStore {+ #[serde(default)]+ pub templates: Vec<YtTemplate>,+}++fn templates_path() -> PathBuf {+ crate::core::paths::app_data_dir()+ .unwrap_or_else(|| PathBuf::from("."))+ .join("yt_templates.json")+}++fn load() -> YtTemplateStore {+ let path = templates_path();+ if !path.exists() {+ return YtTemplateStore::default();+ }+ fs::read_to_string(&path)+ .ok()+ .and_then(|s| serde_json::from_str(&s).ok())+ .unwrap_or_default()+}++fn save(store: &YtTemplateStore) -> Result<(), String> {+ let path = templates_path();+ if let Some(parent) = path.parent() {+ fs::create_dir_all(parent).map_err(|e| e.to_string())?;+ }+ let serialized = serde_json::to_string_pretty(store).map_err(|e| e.to_string())?;+ fs::write(&path, serialized).map_err(|e| e.to_string())+}++fn now_ms() -> i64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_millis() as i64)+ .unwrap_or(0)+}++#[tauri::command]+pub fn yt_templates_list() -> Result<Vec<YtTemplate>, String> {+ Ok(load().templates)+}++#[derive(Debug, Deserialize)]+pub struct SaveRequest {+ pub id: Option<String>,+ pub name: String,+ pub args: Vec<String>,+}++#[tauri::command]+pub fn yt_templates_save(request: SaveRequest) -> Result<YtTemplate, String> {+ let name = request.name.trim().to_string();+ if name.is_empty() {+ return Err("Template name cannot be empty".to_string());+ }+ let now = now_ms();+ let mut store = load();+ let id = request.id.unwrap_or_else(|| format!("tpl-{}", now));+ let existing = store.templates.iter_mut().find(|t| t.id == id);+ let template = if let Some(t) = existing {+ t.name = name;+ t.args = request.args;+ t.updated_at_ms = now;+ t.clone()+ } else {+ let t = YtTemplate {+ id,+ name,+ args: request.args,+ created_at_ms: now,+ updated_at_ms: now,+ };+ store.templates.push(t.clone());+ t+ };+ save(&store)?;+ Ok(template)+}++#[derive(Debug, Deserialize)]+pub struct DeleteRequest {+ pub id: String,+}++#[tauri::command]+pub fn yt_templates_delete(request: DeleteRequest) -> Result<(), String> {+ let mut store = load();+ let before = store.templates.len();+ store.templates.retain(|t| t.id != request.id);+ if store.templates.len() == before {+ return Err(format!("template not found: {}", request.id));+ }+ save(&store)+}diff --git a/src-tauri/src/cookies/commands.rs b/src-tauri/src/cookies/commands.rsindex 3f0b00f0..22fd990a 100644--- a/src-tauri/src/cookies/commands.rs+++ b/src-tauri/src/cookies/commands.rs@@ -4,9 +4,7 @@ use serde::{Deserialize, Serialize};use super::parsers;use super::platform::PlatformKind;-use super::storage::{- self, AccountEntry, CookieRegistry, IngestSource,-};+use super::storage::{self, AccountEntry, CookieRegistry, IngestSource};#[derive(Debug, Serialize)]pub struct CookieListResponse {@@ -76,14 +74,19 @@ const DEFAULT_SLUG: &str = "_default";pub async fn cookies_list() -> Result<CookieListResponse, String> {let registry = storage::load_registry();let cookies_dir = storage::cookies_root().to_string_lossy().into_owned();- Ok(CookieListResponse { registry, cookies_dir })+ Ok(CookieListResponse {+ registry,+ cookies_dir,+ })}#[tauri::command]pub async fn cookies_read(request: ReadRequest) -> Result<ReadResponse, String> {let slug = request.slug.as_deref().unwrap_or(DEFAULT_SLUG);let content = storage::read_account_file(&request.domain, slug).map_err(|e| e.to_string())?;- let path = storage::account_file(&request.domain, slug).to_string_lossy().into_owned();+ let path = storage::account_file(&request.domain, slug)+ .to_string_lossy()+ .into_owned();Ok(ReadResponse { content, path })}@@ -93,7 +96,9 @@ pub async fn cookies_import(request: ImportRequest) -> Result<ImportResponse, Stif cookies.is_empty() {return Err("No cookies found in payload".to_string());}- let label = request.source_label.unwrap_or_else(|| "Manual import".to_string());+ let label = request+ .source_label+ .unwrap_or_else(|| "Manual import".to_string());let written = storage::ingest_batch(&cookies,IngestSource {@@ -108,7 +113,11 @@ pub async fn cookies_import(request: ImportRequest) -> Result<ImportResponse, St.into_iter().map(|(domain, cookie_count)| {let platform_kind = PlatformKind::from_domain(&domain).as_str().to_string();- BucketWrite { domain, cookie_count, platform_kind }+ BucketWrite {+ domain,+ cookie_count,+ platform_kind,+ }}).collect();Ok(ImportResponse { buckets_written })@@ -143,6 +152,75 @@ pub async fn cookies_detect_platform(domain: String) -> Result<String, String> {Ok(PlatformKind::from_domain(&domain).as_str().to_string())}+#[derive(Debug, Serialize)]+pub struct AccountsForUrlResponse {+ pub domain: String,+ pub accounts: Vec<AccountEntry>,+}++#[derive(Debug, Serialize)]+pub struct CookieJsonEntry {+ pub name: String,+ pub value: String,+ pub domain: String,+ pub path: String,+ pub secure: bool,+ pub expires: i64,+ #[serde(rename = "httpOnly")]+ pub http_only: bool,+}++#[derive(Debug, Deserialize)]+pub struct ReadAsJsonRequest {+ pub domain: String,+ #[serde(default)]+ pub slug: Option<String>,+}++#[tauri::command]+pub async fn cookies_read_as_json(+ request: ReadAsJsonRequest,+) -> Result<Vec<CookieJsonEntry>, String> {+ let slug = request.slug.as_deref().unwrap_or(DEFAULT_SLUG);+ let content = storage::read_account_file(&request.domain, slug).map_err(|e| e.to_string())?;+ let parsed = parsers::parse_netscape(&content).map_err(|e| e.to_string())?;+ Ok(parsed+ .into_iter()+ .map(|c| CookieJsonEntry {+ name: c.name,+ value: c.value,+ domain: c.domain,+ path: c.path,+ secure: c.secure,+ expires: c.expires,+ http_only: c.http_only,+ })+ .collect())+}++#[tauri::command]+pub async fn cookies_accounts_for_url(url: String) -> Result<AccountsForUrlResponse, String> {+ let parsed = url::Url::parse(&url).map_err(|e| e.to_string())?;+ let host = parsed.host_str().unwrap_or("");+ let root = super::platform::root_domain_of(host);+ if root.is_empty() {+ return Ok(AccountsForUrlResponse {+ domain: String::new(),+ accounts: Vec::new(),+ });+ }+ let registry = storage::load_registry();+ let accounts = registry+ .buckets+ .get(&root)+ .map(|b| b.accounts.clone())+ .unwrap_or_default();+ Ok(AccountsForUrlResponse {+ domain: root,+ accounts,+ })+}+#[derive(Debug, Deserialize)]pub struct ImportFileRequest {pub path: String,@@ -177,7 +255,11 @@ pub async fn cookies_import_file(request: ImportFileRequest) -> Result<ImportRes.into_iter().map(|(domain, cookie_count)| {let platform_kind = PlatformKind::from_domain(&domain).as_str().to_string();- BucketWrite { domain, cookie_count, platform_kind }+ BucketWrite {+ domain,+ cookie_count,+ platform_kind,+ }}).collect();Ok(ImportResponse { buckets_written })diff --git a/src-tauri/src/cookies/mod.rs b/src-tauri/src/cookies/mod.rsindex 0941c047..7ba804d8 100644--- a/src-tauri/src/cookies/mod.rs+++ b/src-tauri/src/cookies/mod.rs@@ -20,5 +20,6 @@ pub mod storage;pub use platform::{root_domain_of, PlatformKind};pub use storage::{account_path_for_consumer, ingest_batch, ingest_to_account, load_registry,- migrate_legacy_if_needed, AccountEntry, BucketEntry, CookieRegistry, IngestSource,+ migrate_legacy_if_needed, touch_last_used, AccountEntry, BucketEntry, CookieRegistry,+ IngestSource,};diff --git a/src-tauri/src/cookies/parsers.rs b/src-tauri/src/cookies/parsers.rsindex 1e030377..d8083c38 100644--- a/src-tauri/src/cookies/parsers.rs+++ b/src-tauri/src/cookies/parsers.rs@@ -31,7 +31,10 @@ pub fn detect_format(content: &str) -> CookieFormat {if first == '[' || first == '{' {return CookieFormat::Json;}- if trimmed.starts_with("# Netscape") || trimmed.starts_with("#HttpOnly_") || trimmed.contains('\t') {+ if trimmed.starts_with("# Netscape")+ || trimmed.starts_with("#HttpOnly_")+ || trimmed.contains('\t')+ {return CookieFormat::Netscape;}CookieFormat::Unknown@@ -109,8 +112,8 @@ struct JsonCookie {}pub fn parse_json(content: &str) -> anyhow::Result<Vec<ExtensionCookie>> {- let raw: serde_json::Value = serde_json::from_str(content)- .map_err(|e| anyhow::anyhow!("invalid JSON: {e}"))?;+ let raw: serde_json::Value =+ serde_json::from_str(content).map_err(|e| anyhow::anyhow!("invalid JSON: {e}"))?;let arr = match raw {serde_json::Value::Array(a) => a,serde_json::Value::Object(_) => vec![raw],@@ -148,17 +151,26 @@ mod tests {#[test]fn detect_netscape_header() {- assert_eq!(detect_format("# Netscape HTTP Cookie File\n.foo\tTRUE\t/\tTRUE\t0\ta\tb"), CookieFormat::Netscape);+ assert_eq!(+ detect_format("# Netscape HTTP Cookie File\n.foo\tTRUE\t/\tTRUE\t0\ta\tb"),+ CookieFormat::Netscape+ );}#[test]fn detect_json_array() {- assert_eq!(detect_format("[{\"domain\":\"x.com\"}]"), CookieFormat::Json);+ assert_eq!(+ detect_format("[{\"domain\":\"x.com\"}]"),+ CookieFormat::Json+ );}#[test]fn detect_tab_separated_without_header() {- assert_eq!(detect_format(".x.com\tTRUE\t/\tTRUE\t0\tname\tvalue"), CookieFormat::Netscape);+ assert_eq!(+ detect_format(".x.com\tTRUE\t/\tTRUE\t0\tname\tvalue"),+ CookieFormat::Netscape+ );}#[test]@@ -169,7 +181,8 @@ mod tests {#[test]fn parse_netscape_basic() {- let raw = "# Netscape HTTP Cookie File\n.youtube.com\tTRUE\t/\tTRUE\t1830000000\tSID\tabc123\n";+ let raw =+ "# Netscape HTTP Cookie File\n.youtube.com\tTRUE\t/\tTRUE\t1830000000\tSID\tabc123\n";let cookies = parse_netscape(raw).unwrap();assert_eq!(cookies.len(), 1);assert_eq!(cookies[0].domain, ".youtube.com");diff --git a/src-tauri/src/cookies/platform.rs b/src-tauri/src/cookies/platform.rsindex 149b285f..b442e1c4 100644--- a/src-tauri/src/cookies/platform.rs+++ b/src-tauri/src/cookies/platform.rs@@ -90,23 +90,44 @@ mod tests {#[test]fn youtube_variants_map_correctly() {- assert_eq!(PlatformKind::from_domain("youtube.com"), PlatformKind::Youtube);- assert_eq!(PlatformKind::from_domain(".youtube.com"), PlatformKind::Youtube);- assert_eq!(PlatformKind::from_domain("www.youtube.com"), PlatformKind::Youtube);- assert_eq!(PlatformKind::from_domain("music.youtube.com"), PlatformKind::YoutubeMusic);+ assert_eq!(+ PlatformKind::from_domain("youtube.com"),+ PlatformKind::Youtube+ );+ assert_eq!(+ PlatformKind::from_domain(".youtube.com"),+ PlatformKind::Youtube+ );+ assert_eq!(+ PlatformKind::from_domain("www.youtube.com"),+ PlatformKind::Youtube+ );+ assert_eq!(+ PlatformKind::from_domain("music.youtube.com"),+ PlatformKind::YoutubeMusic+ );assert_eq!(PlatformKind::from_domain("youtu.be"), PlatformKind::Youtube);}#[test]fn twitter_x_share_kind() {assert_eq!(PlatformKind::from_domain("x.com"), PlatformKind::XTwitter);- assert_eq!(PlatformKind::from_domain("twitter.com"), PlatformKind::XTwitter);+ assert_eq!(+ PlatformKind::from_domain("twitter.com"),+ PlatformKind::XTwitter+ );}#[test]fn unknown_falls_to_generic() {- assert_eq!(PlatformKind::from_domain("example.com"), PlatformKind::Generic);- assert_eq!(PlatformKind::from_domain("bandcamp.com"), PlatformKind::Generic);+ assert_eq!(+ PlatformKind::from_domain("example.com"),+ PlatformKind::Generic+ );+ assert_eq!(+ PlatformKind::from_domain("bandcamp.com"),+ PlatformKind::Generic+ );}#[test]diff --git a/src-tauri/src/cookies/storage.rs b/src-tauri/src/cookies/storage.rsindex 63ac4192..f3afdff5 100644--- a/src-tauri/src/cookies/storage.rs+++ b/src-tauri/src/cookies/storage.rs@@ -76,7 +76,13 @@ pub fn trash_dir() -> PathBuf {fn safe_domain_segment(domain: &str) -> String {let h = domain.trim_start_matches('.').to_lowercase();h.chars()- .map(|c| if c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_' { c } else { '_' })+ .map(|c| {+ if c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_' {+ c+ } else {+ '_'+ }+ }).collect()}@@ -84,9 +90,19 @@ fn safe_slug_segment(slug: &str) -> String {let lowered = slug.to_lowercase();let cleaned: String = lowered.chars()- .map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '-' })+ .map(|c| {+ if c.is_ascii_alphanumeric() || c == '-' || c == '_' {+ c+ } else {+ '-'+ }+ }).collect();- if cleaned.is_empty() { DEFAULT_SLUG.to_string() } else { cleaned }+ if cleaned.is_empty() {+ DEFAULT_SLUG.to_string()+ } else {+ cleaned+ }}pub fn load_registry() -> CookieRegistry {@@ -125,7 +141,10 @@ fn format_cookie_line(c: &ExtensionCookie, session_ttl: u64) -> String {let http_only_prefix = if c.http_only { "#HttpOnly_" } else { "" };let is_host_only = c.host_only.unwrap_or_else(|| !raw_domain.starts_with('.'));let (domain, include_subdomains) = if is_host_only {- let stripped = raw_domain.strip_prefix('.').unwrap_or(&raw_domain).to_string();+ let stripped = raw_domain+ .strip_prefix('.')+ .unwrap_or(&raw_domain)+ .to_string();(stripped, "FALSE")} else if raw_domain.starts_with('.') {(raw_domain.clone(), "TRUE")@@ -133,7 +152,11 @@ fn format_cookie_line(c: &ExtensionCookie, session_ttl: u64) -> String {(format!(".{}", raw_domain), "TRUE")};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+ };format!("{}{}\t{}\t{}\t{}\t{}\t{}\t{}\n",http_only_prefix, domain, include_subdomains, path_field, secure, expires, name, value,@@ -141,7 +164,9 @@ fn format_cookie_line(c: &ExtensionCookie, session_ttl: u64) -> String {}fn sanitize_field(s: &str) -> String {- s.chars().filter(|c| *c != '\n' && *c != '\r' && *c != '\t').collect()+ s.chars()+ .filter(|c| *c != '\n' && *c != '\r' && *c != '\t')+ .collect()}pub struct IngestSource {@@ -199,17 +224,16 @@ pub fn ingest_batch(for (root, group) in by_root.iter() {let count = write_account_file(root, DEFAULT_SLUG, group)?;let platform = PlatformKind::from_domain(root);- let bucket = registry.buckets.entry(root.clone()).or_insert_with(|| BucketEntry {- platform_kind: platform.as_str().to_string(),- accounts: Vec::new(),- });+ let bucket = registry+ .buckets+ .entry(root.clone())+ .or_insert_with(|| BucketEntry {+ platform_kind: platform.as_str().to_string(),+ accounts: Vec::new(),+ });bucket.platform_kind = platform.as_str().to_string();- let alias_default = format!(- "{} · {}",- platform_display(platform),- human_date(now),- );+ let alias_default = format!("{} · {}", platform_display(platform), human_date(now),);let new_alias = source.alias_hint.clone().unwrap_or(alias_default);if let Some(existing) = bucket.accounts.iter_mut().find(|a| a.slug == DEFAULT_SLUG) {@@ -284,7 +308,12 @@ pub fn move_to_trash(domain: &str, slug: &str) -> anyhow::Result<()> {let trash = trash_dir();fs::create_dir_all(&trash)?;let stamp = current_unix_ms();- let dst_name = format!("{}__{}__{}.txt", safe_domain_segment(domain), safe_slug_segment(slug), stamp);+ let dst_name = format!(+ "{}__{}__{}.txt",+ safe_domain_segment(domain),+ safe_slug_segment(slug),+ stamp+ );let dst = trash.join(dst_name);fs::rename(&src, &dst)?;@@ -363,12 +392,7 @@ pub fn ingest_to_account(});let mut slug = if requested_slug.trim().is_empty() {- slugify_alias(- source- .alias_hint- .as_deref()- .unwrap_or(""),- )+ slugify_alias(source.alias_hint.as_deref().unwrap_or(""))} else {slugify_alias(requested_slug)};@@ -386,7 +410,11 @@ pub fn ingest_to_account(let count = write_account_file(&root, &final_slug, &scoped)?;let now = current_unix_ms();let alias = source.alias_hint.clone().unwrap_or_else(|| {- format!("{} · {}", platform_display(PlatformKind::from_domain(&root)), human_date(now))+ format!(+ "{} · {}",+ platform_display(PlatformKind::from_domain(&root)),+ human_date(now)+ )});bucket.accounts.push(AccountEntry {@@ -422,7 +450,22 @@ pub fn rename_account(domain: &str, slug: &str, new_alias: &str) -> anyhow::Resupub fn account_path_for_consumer(domain: &str, slug: Option<&str>) -> Option<PathBuf> {let slug = slug.unwrap_or(DEFAULT_SLUG);let path = account_file(domain, slug);- if path.exists() { Some(path) } else { None }+ if path.exists() {+ Some(path)+ } else {+ None+ }+}++pub fn touch_last_used(domain: &str, slug: &str) {+ let mut registry = load_registry();+ let now = current_unix_ms();+ if let Some(bucket) = registry.buckets.get_mut(domain) {+ if let Some(account) = bucket.accounts.iter_mut().find(|a| a.slug == slug) {+ account.last_used_at_ms = Some(now);+ let _ = save_registry(®istry);+ }+ }}pub fn migrate_legacy_if_needed() -> anyhow::Result<usize> {diff --git a/src-tauri/src/core/host_limiter.rs b/src-tauri/src/core/host_limiter.rsindex 8320ff3b..24ec7c3b 100644--- a/src-tauri/src/core/host_limiter.rs+++ b/src-tauri/src/core/host_limiter.rs@@ -39,7 +39,10 @@ pub fn host_key_for_url(url: &str) -> String {fn canonicalize_host(host: &str) -> String {let trimmed = host.trim_start_matches("www.");- if trimmed.contains("youtube.com") || trimmed.contains("youtu.be") || trimmed.contains("googlevideo.com") {+ if trimmed.contains("youtube.com")+ || trimmed.contains("youtu.be")+ || trimmed.contains("googlevideo.com")+ {return "youtube".to_string();}if trimmed.contains("instagram.com") || trimmed.contains("cdninstagram.com") {@@ -48,10 +51,14 @@ fn canonicalize_host(host: &str) -> String {if trimmed.contains("tiktok.com") || trimmed.contains("tiktokcdn.com") {return "tiktok".to_string();}- if trimmed.contains("twitter.com") || trimmed.contains("x.com") || trimmed.contains("twimg.com") {+ if trimmed.contains("twitter.com") || trimmed.contains("x.com") || trimmed.contains("twimg.com")+ {return "twitter".to_string();}- if trimmed.contains("reddit.com") || trimmed.contains("redd.it") || trimmed.contains("redditmedia.com") {+ if trimmed.contains("reddit.com")+ || trimmed.contains("redd.it")+ || trimmed.contains("redditmedia.com")+ {return "reddit".to_string();}if trimmed.contains("vimeo.com") || trimmed.contains("vimeocdn.com") {@@ -152,15 +159,24 @@ mod tests {#[test]fn youtube_variants_canonicalize() {- assert_eq!(host_key_for_url("https://www.youtube.com/watch?v=abc"), "youtube");+ assert_eq!(+ host_key_for_url("https://www.youtube.com/watch?v=abc"),+ "youtube"+ );assert_eq!(host_key_for_url("https://youtu.be/abc"), "youtube");- assert_eq!(host_key_for_url("https://r5---sn-foo.googlevideo.com/x"), "youtube");+ assert_eq!(+ host_key_for_url("https://r5---sn-foo.googlevideo.com/x"),+ "youtube"+ );}#[test]fn x_and_twitter_share_bucket() {assert_eq!(host_key_for_url("https://x.com/jack/status/1"), "twitter");- assert_eq!(host_key_for_url("https://twitter.com/jack/status/1"), "twitter");+ assert_eq!(+ host_key_for_url("https://twitter.com/jack/status/1"),+ "twitter"+ );}#[test]diff --git a/src-tauri/src/core/queue.rs b/src-tauri/src/core/queue.rsindex f35c4ac6..fa883d57 100644--- a/src-tauri/src/core/queue.rs+++ b/src-tauri/src/core/queue.rs@@ -71,8 +71,8 @@ pub enum QueueKind {pub fn kind_from_platform(platform: &str) -> QueueKind {let p = platform.to_ascii_lowercase();match p.as_str() {- "youtube" | "vimeo" | "twitch" | "bilibili" | "tiktok" | "twitter" | "x"- | "instagram" | "reddit" | "bluesky" | "facebook" | "generic_ytdlp" => QueueKind::Video,+ "youtube" | "vimeo" | "twitch" | "bilibili" | "tiktok" | "twitter" | "x" | "instagram"+ | "reddit" | "bluesky" | "facebook" | "generic_ytdlp" => QueueKind::Video,"soundcloud" | "spotify" => QueueKind::Audio,"pinterest" => QueueKind::Image,"magnet" | "p2p" | "torrent" => QueueKind::Generic,@@ -168,6 +168,8 @@ pub struct QueueItem {pub concurrent_segments: Option<usize>,pub segment_size_bytes: Option<u64>,pub eta_seconds: Option<u64>,+ pub cookie_slug: Option<String>,+ pub custom_ytdlp_args: Option<Vec<String>>,}impl QueueItem {@@ -185,10 +187,11 @@ impl QueueItem {file_path: self.file_path.clone(),file_size_bytes: self.file_size_bytes,file_count: self.file_count,- thumbnail_url: self- .thumbnail_url_override- .clone()- .or_else(|| self.media_info.as_ref().and_then(|m| m.thumbnail_url.clone())),+ thumbnail_url: self.thumbnail_url_override.clone().or_else(|| {+ self.media_info+ .as_ref()+ .and_then(|m| m.thumbnail_url.clone())+ }),kind: self.kind,external: self.external,eta_seconds: self.eta_seconds,@@ -236,6 +239,8 @@ impl DownloadQueue {downloader: Arc<dyn PlatformDownloader>,ytdlp_path: Option<PathBuf>,from_hotkey: bool,+ cookie_slug: Option<String>,+ custom_ytdlp_args: Option<Vec<String>>,) {let computed_kind = Some(kind_from_platform(&platform));let item = QueueItem {@@ -274,6 +279,8 @@ impl DownloadQueue {concurrent_segments: None,segment_size_bytes: None,eta_seconds: None,+ cookie_slug,+ custom_ytdlp_args,};crate::core::recovery::persist(crate::core::recovery::RecoveryItem {id: item.id,@@ -355,6 +362,8 @@ impl DownloadQueue {concurrent_segments: None,segment_size_bytes: None,eta_seconds: None,+ cookie_slug: None,+ custom_ytdlp_args: None,};self.items.push(item);}@@ -422,10 +431,11 @@ impl DownloadQueue {success,error: if success { None } else { error_for_history },completed_at: crate::core::queue_history::now_unix_seconds(),- thumbnail_url: item- .thumbnail_url_override- .clone()- .or_else(|| item.media_info.as_ref().and_then(|m| m.thumbnail_url.clone())),+ thumbnail_url: item.thumbnail_url_override.clone().or_else(|| {+ item.media_info+ .as_ref()+ .and_then(|m| m.thumbnail_url.clone())+ }),kind: item.kind,};crate::core::queue_history::record(entry);@@ -537,8 +547,7 @@ impl DownloadQueue {}pub fn reorder(&mut self, ids_in_order: Vec<u64>) -> bool {- let mut slots: Vec<Option<QueueItem>> =- self.items.drain(..).map(Some).collect();+ let mut slots: Vec<Option<QueueItem>> = self.items.drain(..).map(Some).collect();let queued_slot_indices: Vec<usize> = slots.iter()@@ -560,8 +569,7 @@ impl DownloadQueue {.map(|idx| (slots[*idx].as_ref().unwrap().id, *idx)).collect();- let mut new_queued_order: Vec<QueueItem> =- Vec::with_capacity(queued_slot_indices.len());+ let mut new_queued_order: Vec<QueueItem> = Vec::with_capacity(queued_slot_indices.len());let mut seen: std::collections::HashSet<u64> = std::collections::HashSet::new();for id in &ids_in_order {@@ -711,7 +719,12 @@ impl DownloadQueue {let to_remove: Vec<u64> = self.items.iter()- .filter(|i| matches!(i.status, QueueStatus::Complete { .. } | QueueStatus::Error { .. }))+ .filter(|i| {+ matches!(+ i.status,+ QueueStatus::Complete { .. } | QueueStatus::Error { .. }+ )+ }).map(|i| i.id).collect();for id in &to_remove {@@ -960,6 +973,8 @@ async fn spawn_download_inner(downloader,ytdlp_path,from_hotkey,+ cookie_slug,+ custom_ytdlp_args,) = {let q = queue.lock().await;let item = match q.items.iter().find(|i| i.id == item_id) {@@ -982,6 +997,8 @@ async fn spawn_download_inner(item.downloader.clone(),item.ytdlp_path.clone(),item.from_hotkey,+ item.cookie_slug.clone(),+ item.custom_ytdlp_args.clone(),)};@@ -1129,6 +1146,7 @@ async fn spawn_download_inner(ytdlp_path,torrent_listen_port: Some(settings.advanced.torrent_listen_port),torrent_id_slot: Some(torrent_id_slot.clone()),+ custom_ytdlp_args: custom_ytdlp_args.clone(),};let total_bytes = info.file_size_bytes;@@ -1241,8 +1259,11 @@ async fn spawn_download_inner(}}};- let result = omniget_core::core::log_hook::CURRENT_DOWNLOAD_ID- .scope(item_id, dl_future)+ let result = omniget_core::core::log_hook::CURRENT_COOKIE_SLUG+ .scope(+ cookie_slug.clone(),+ omniget_core::core::log_hook::CURRENT_DOWNLOAD_ID.scope(item_id, dl_future),+ ).await;omniget_core::core::ytdlp::clear_ext_user_agent(&url);omniget_core::core::ytdlp::clear_ext_headers(&url);@@ -1666,7 +1687,10 @@ mod kind_tests {#[test]fn telegram_kind() {assert_eq!(kind_from_platform("telegram"), QueueKind::TelegramMedia);- assert_eq!(kind_from_platform("telegram_media"), QueueKind::TelegramMedia);+ assert_eq!(+ kind_from_platform("telegram_media"),+ QueueKind::TelegramMedia+ );}#[test]diff --git a/src-tauri/src/core/rpc.rs b/src-tauri/src/core/rpc.rsindex 1d1d8e5f..fad9fe9f 100644--- a/src-tauri/src/core/rpc.rs+++ b/src-tauri/src/core/rpc.rs@@ -158,7 +158,9 @@ fn format_count_short(count: u64) -> String {fn redact(settings: &RpcSettings) -> Value {let connected = match RPC.lock() {- Ok(g) => g.connected && !settings.app_id.is_empty() && g.connected_app_id == settings.app_id,+ Ok(g) => {+ g.connected && !settings.app_id.is_empty() && g.connected_app_id == settings.app_id+ }Err(_) => false,};json!({@@ -248,11 +250,18 @@ fn apply_top_activity(default_image: &str) -> bool {None => {let details = "omniget".to_string();let state_text = idle_state_text(idle_stats);- (details, state_text, "idle".to_string(), default_image.to_string())+ (+ details,+ state_text,+ "idle".to_string(),+ default_image.to_string(),+ )}};- let assets = Assets::new().large_image(&img_key_owned).large_text(APP_LARGE_TEXT);+ let assets = Assets::new()+ .large_image(&img_key_owned)+ .large_text(APP_LARGE_TEXT);let buttons = vec![Button::new(GITHUB_BUTTON_LABEL, GITHUB_BUTTON_URL)];let start = if session_start > 0 {@@ -365,7 +374,9 @@ pub async fn set_presence_source(return false;}if let Ok(mut state) = RPC.lock() {- state.activities.insert(source_owned.clone(), activity_record);+ state+ .activities+ .insert(source_owned.clone(), activity_record);}apply_top_activity(&default_img)})@@ -473,7 +484,10 @@ mod tests {#[test]fn format_position_duration_basic() {- assert_eq!(format_position_duration(83, 245), Some("1:23 / 4:05".into()));+ assert_eq!(+ format_position_duration(83, 245),+ Some("1:23 / 4:05".into())+ );}#[test]diff --git a/src-tauri/src/extension_storage.rs b/src-tauri/src/extension_storage.rsindex 5841a631..5b9ca778 100644--- a/src-tauri/src/extension_storage.rs+++ b/src-tauri/src/extension_storage.rs@@ -96,9 +96,7 @@ fn format_cookie_line(c: &ExtensionCookie, session_ttl: u64) -> String {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 is_host_only = c- .host_only- .unwrap_or_else(|| !raw_domain.starts_with('.'));+ let is_host_only = c.host_only.unwrap_or_else(|| !raw_domain.starts_with('.'));let (domain, include_subdomains) = if is_host_only {let stripped = raw_domain.strip_prefix('.')@@ -140,10 +138,8 @@ pub fn write_extension_cookies(cookies: &[ExtensionCookie]) -> anyhow::Result<()// Merge with existing file: keep cookies whose root domain is NOT in the// incoming batch. Each platform capture only ships its own domains, so// overwriting the file would wipe other platforms' auth.- let incoming_roots: std::collections::HashSet<String> = cookies- .iter()- .map(|c| root_domain_of(&c.domain))- .collect();+ let incoming_roots: std::collections::HashSet<String> =+ cookies.iter().map(|c| root_domain_of(&c.domain)).collect();let mut preserved: Vec<String> = Vec::new();if let Ok(existing) = fs::read_to_string(&path) {@@ -219,10 +215,7 @@ fn load_metadata_map(path: &std::path::Path) -> serde_json::Map<String, serde_js}}-fn prune_expired_metadata(- map: &mut serde_json::Map<String, serde_json::Value>,- now: u64,-) {+fn prune_expired_metadata(map: &mut serde_json::Map<String, serde_json::Value>, now: u64) {map.retain(|_, v| {v.get("timestamp").and_then(|t| t.as_u64())diff --git a/src-tauri/src/external_url.rs b/src-tauri/src/external_url.rsindex b3d497a4..6ba77a66 100644--- a/src-tauri/src/external_url.rs+++ b/src-tauri/src/external_url.rs@@ -257,6 +257,8 @@ pub async fn queue_url_with_defaults(downloader,ytdlp_path,from_hotkey,+ None,+ None,);let next_ids = q.next_queued_ids();diff --git a/src-tauri/src/hotkey.rs b/src-tauri/src/hotkey.rsindex a169c000..3fd74015 100644--- a/src-tauri/src/hotkey.rs+++ b/src-tauri/src/hotkey.rs@@ -79,7 +79,10 @@ pub fn on_hotkey_pressed(app: &tauri::AppHandle, shortcut: &Shortcut) {}fn matches_binding(pressed: &Shortcut, binding: &str) -> bool {- binding.parse::<Shortcut>().map(|s| s == *pressed).unwrap_or(false)+ binding+ .parse::<Shortcut>()+ .map(|s| s == *pressed)+ .unwrap_or(false)}fn handle_download_clipboard(app: &tauri::AppHandle) {diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex bb437fda..ebe75b34 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -140,7 +140,15 @@ pub fn run() {if root.is_empty() {return None;}- crate::cookies::account_path_for_consumer(&root, None)+ let slug = omniget_core::core::log_hook::current_cookie_slug();+ let path = crate::cookies::account_path_for_consumer(&root, slug.as_deref())?;+ crate::cookies::touch_last_used(&root, slug.as_deref().unwrap_or("_default"));+ Some(path)+ });+ core::ytdlp::set_managed_cookies_only_fn(|| {+ storage::config::load_settings_standalone()+ .download+ .always_use_managed_cookies});core::ytdlp::set_global_cookie_file_fn(|| {let s = storage::config::load_settings_standalone();@@ -194,18 +202,16 @@ pub fn run() {});{let app_handle = app.handle().clone();- omniget_core::core::log_hook::set_log_sink(std::sync::Arc::new(- move |id, line| {- let should_emit = core::download_log::push_line(id, line);- if should_emit {- let _ = tauri::Emitter::emit(- &app_handle,- "download-log-update",- serde_json::json!({ "id": id }),- );- }- },- ));+ omniget_core::core::log_hook::set_log_sink(std::sync::Arc::new(move |id, line| {+ let should_emit = core::download_log::push_line(id, line);+ if should_emit {+ let _ = tauri::Emitter::emit(+ &app_handle,+ "download-log-update",+ serde_json::json!({ "id": id }),+ );+ }+ }));}core::recovery::init_from_disk();core::queue_history::init_from_disk();@@ -410,6 +416,8 @@ pub fn run() {cookies::commands::cookies_rename,cookies::commands::cookies_migrate_legacy,cookies::commands::cookies_detect_platform,+ cookies::commands::cookies_accounts_for_url,+ cookies::commands::cookies_read_as_json,cookies::commands::cookies_import_file,cookies::commands::cookies_export_to,cookies::commands::cookies_add_account,@@ -423,7 +431,11 @@ pub fn run() {commands::downloads::get_media_formats,commands::downloads::prefetch_media_info,commands::downloads::download_from_url,+ commands::downloads::download_with_custom_args,commands::downloads::cancel_generic_download,+ commands::yt_templates::yt_templates_list,+ commands::yt_templates::yt_templates_save,+ commands::yt_templates::yt_templates_delete,commands::downloads::pause_download,commands::downloads::resume_download,commands::downloads::pause_all_downloads,diff --git a/src-tauri/src/local_bridge.rs b/src-tauri/src/local_bridge.rsindex 21117abe..79d25df8 100644--- a/src-tauri/src/local_bridge.rs+++ b/src-tauri/src/local_bridge.rs@@ -36,8 +36,7 @@ use tokio::net::TcpListener;use tower_http::cors::{Any, CorsLayer};use crate::extension_storage::{- cookie_limit, write_extension_metadata, ExtensionCookie,- ExtensionPayload,+ cookie_limit, write_extension_metadata, ExtensionCookie, ExtensionPayload,};use crate::storage::config;@@ -138,10 +137,7 @@ async fn bind_listener(preferred: u16) -> std::io::Result<(u16, TcpListener)> {/// Ensure `settings.bridge.{token,port}` are populated and persisted./// Returns the resolved (token, port) pair to use for this run.-fn ensure_bridge_settings(- app: &AppHandle,- bound_port: u16,-) -> anyhow::Result<(String, u16)> {+fn ensure_bridge_settings(app: &AppHandle, bound_port: u16) -> anyhow::Result<(String, u16)> {let mut settings = config::load_settings(app);let mut dirty = false;@@ -249,7 +245,10 @@ fn check_bearer(headers: &HeaderMap, expected: &str) -> bool {Ok(s) => s,Err(_) => return false,};- let provided = match raw.strip_prefix("Bearer ").or_else(|| raw.strip_prefix("bearer ")) {+ let provided = match raw+ .strip_prefix("Bearer ")+ .or_else(|| raw.strip_prefix("bearer "))+ {Some(s) => s.trim(),None => return false,};@@ -303,7 +302,10 @@ async fn enqueue(if let Err(error) = crate::cookies::ingest_batch(cookies,crate::cookies::IngestSource {- source_url: payload.page_url.clone().or_else(|| Some(payload.url.clone())),+ source_url: payload+ .page_url+ .clone()+ .or_else(|| Some(payload.url.clone())),source_label: "Browser extension".to_string(),alias_hint: payload.title.clone(),},@@ -330,9 +332,7 @@ async fn enqueue(let app = state.app.clone();let url = payload.url.clone();tauri::async_runtime::spawn(async move {- if let Err(error) =- crate::external_url::handle_external_url(&app, url, "bridge").await- {+ if let Err(error) = crate::external_url::handle_external_url(&app, url, "bridge").await {tracing::warn!("failed to handle bridge URL: {error}");}});diff --git a/src-tauri/src/pets/download.rs b/src-tauri/src/pets/download.rsindex 48ae62bb..97240848 100644--- a/src-tauri/src/pets/download.rs+++ b/src-tauri/src/pets/download.rs@@ -96,10 +96,14 @@ pub async fn fetch_manifest() -> anyhow::Result<RemoteManifest> {message: e.to_string(),retryable: true,})?;- let res = client.get(MANIFEST_URL).send().await.map_err(|e| RetryError {- message: e.to_string(),- retryable: true,- })?;+ let res = client+ .get(MANIFEST_URL)+ .send()+ .await+ .map_err(|e| RetryError {+ message: e.to_string(),+ retryable: true,+ })?;let status = res.status();if !status.is_success() {let retryable = is_retryable(Some(status.as_u16()));@@ -125,7 +129,11 @@ pub fn fallback_bundle_url() -> &'static str {FALLBACK_BUNDLE_URL}-pub async fn fetch_bytes(url: &str, max_bytes: usize, timeout_secs: u64) -> anyhow::Result<Vec<u8>> {+pub async fn fetch_bytes(+ url: &str,+ max_bytes: usize,+ timeout_secs: u64,+) -> anyhow::Result<Vec<u8>> {let label = format!("GET {}", url);with_retry(&label, || async {let client = build_client(timeout_secs).map_err(|e| RetryError {diff --git a/src-tauri/src/pets/install.rs b/src-tauri/src/pets/install.rsindex 8eaf63d5..7c2b851e 100644--- a/src-tauri/src/pets/install.rs+++ b/src-tauri/src/pets/install.rs@@ -9,8 +9,8 @@ use tauri::{AppHandle, Emitter};use tokio::sync::Mutex;use super::download::{- extract_ext_from_url, fallback_bundle_url, fetch_bundle_zip, fetch_pet_json,- fetch_spritesheet, RemoteManifest, RemotePet,+ extract_ext_from_url, fallback_bundle_url, fetch_bundle_zip, fetch_pet_json, fetch_spritesheet,+ RemoteManifest, RemotePet,};use super::manifest::{discover_local_pets, ensure_root, load, manifest_path, now_iso, pet_dir, save_atomic,@@ -69,7 +69,11 @@ pub fn refresh_index(app_data_dir: &Path) -> std::io::Result<LocalIndex> {discover_local_pets(app_data_dir, &mut manifest)?;save_atomic(app_data_dir, &manifest)?;let mut pets: Vec<LocalPetEntry> = manifest.pets.values().cloned().collect();- pets.sort_by(|a, b| a.display_name.to_lowercase().cmp(&b.display_name.to_lowercase()));+ pets.sort_by(|a, b| {+ a.display_name+ .to_lowercase()+ .cmp(&b.display_name.to_lowercase())+ });let total = pets.len();Ok(LocalIndex {pets,@@ -463,7 +467,11 @@ pub async fn install_bundle(let lower = name.to_lowercase();let dest = dir.join(&name);if lower == "spritesheet.webp" || lower == "spritesheet.png" {- sprite_ext = if lower.ends_with(".png") { "png".into() } else { "webp".into() };+ sprite_ext = if lower.ends_with(".png") {+ "png".into()+ } else {+ "webp".into()+ };if atomic_write(&dest, &bytes).is_ok() {sizes.insert("spritesheet".into(), bytes.len() as u64);wrote_sprite = true;diff --git a/src-tauri/src/pets/mod.rs b/src-tauri/src/pets/mod.rsindex c6465213..81c6bdbc 100644--- a/src-tauri/src/pets/mod.rs+++ b/src-tauri/src/pets/mod.rs@@ -11,8 +11,8 @@ use tokio::sync::Mutex;use download::{fetch_manifest, RemoteManifest};use install::{diff as compute_diff, force_refresh as install_force_refresh,- install_bundle as install_bundle_impl, install_missing as install_missing_impl,- refresh_index, uninstall as uninstall_impl, DiffReport, InstallReport, LocalIndex,+ install_bundle as install_bundle_impl, install_missing as install_missing_impl, refresh_index,+ uninstall as uninstall_impl, DiffReport, InstallReport, LocalIndex,};use manifest::{ensure_root, load, now_iso, pets_root, save_atomic};@@ -86,7 +86,9 @@ fn read_active(app: &AppHandle) -> Option<String> {let path = pref_file(app).ok()?;let raw = std::fs::read_to_string(&path).ok()?;let v: serde_json::Value = serde_json::from_str(&raw).ok()?;- v.get("slug").and_then(|s| s.as_str()).map(|s| s.to_string())+ v.get("slug")+ .and_then(|s| s.as_str())+ .map(|s| s.to_string())}fn write_active(app: &AppHandle, slug: &str) -> Result<(), String> {diff --git a/src-tauri/src/platforms/bluesky/mod.rs b/src-tauri/src/platforms/bluesky/mod.rsindex 0729d895..dde93ce5 100644--- a/src-tauri/src/platforms/bluesky/mod.rs+++ b/src-tauri/src/platforms/bluesky/mod.rs@@ -283,8 +283,8 @@ impl PlatformDownloader for BlueskyDownloader {let output_path = opts.output_dir.join(&filename);let output_str = output_path.to_string_lossy().to_string();- let downloader = HlsDownloader::new()- .with_user_agent_override(opts.user_agent.clone());+ let downloader =+ HlsDownloader::new().with_user_agent_override(opts.user_agent.clone());let _ = progress.send(0.0).await;let result = downloaderdiff --git a/src-tauri/src/platforms/generic_ytdlp/mod.rs b/src-tauri/src/platforms/generic_ytdlp/mod.rsindex c34ba6b8..2672ddd8 100644--- a/src-tauri/src/platforms/generic_ytdlp/mod.rs+++ b/src-tauri/src/platforms/generic_ytdlp/mod.rs@@ -433,7 +433,8 @@ impl PlatformDownloader for GenericYtdlpDownloader {ytdlp::ensure_ytdlp().await?};- let quality_height = requested_height.or_else(|| Self::extract_quality_height(&selected.label));+ let quality_height =+ requested_height.or_else(|| Self::extract_quality_height(&selected.label));let video_url = &selected.url;let referer = opts@@ -448,6 +449,11 @@ impl PlatformDownloader for GenericYtdlpDownloader {};let mut last_err: Option<anyhow::Error> = None;+ let extra_flags_owned: Vec<String> = opts+ .custom_ytdlp_args+ .as_deref()+ .map(|v| v.to_vec())+ .unwrap_or_default();for (idx, override_format) in format_fallbacks.iter().enumerate() {let effective_format = override_format.or(opts.format_id.as_deref());let attempt_progress = progress.clone();@@ -465,7 +471,7 @@ impl PlatformDownloader for GenericYtdlpDownloader {None,opts.concurrent_fragments,opts.download_subtitles,- &[],+ &extra_flags_owned,opts.audio_format.as_deref(),).await;diff --git a/src-tauri/src/platforms/instagram/mod.rs b/src-tauri/src/platforms/instagram/mod.rsindex 8d66d51f..743417a8 100644--- a/src-tauri/src/platforms/instagram/mod.rs+++ b/src-tauri/src/platforms/instagram/mod.rs@@ -594,7 +594,9 @@ impl InstagramDownloader {opts.download_mode.as_deref(),opts.format_id.as_deref(),opts.filename_template.as_deref(),- opts.referer.as_deref().or(Some("https://www.instagram.com/")),+ opts.referer+ .as_deref()+ .or(Some("https://www.instagram.com/")),opts.cancel_token.clone(),None,opts.concurrent_fragments,@@ -893,6 +895,7 @@ mod tests {ytdlp_path: None,torrent_listen_port: None,torrent_id_slot: None,+ custom_ytdlp_args: None,}}diff --git a/src-tauri/src/platforms/mod.rs b/src-tauri/src/platforms/mod.rsindex 4760a68d..25ab522f 100644--- a/src-tauri/src/platforms/mod.rs+++ b/src-tauri/src/platforms/mod.rs@@ -1,8 +1,8 @@pub use omniget_core::platforms::traits;pub use omniget_core::platforms::Platform;-pub mod noop;pub mod bluesky;+pub mod noop;pub mod pinterest;pub mod tiktok;pub mod twitch;diff --git a/src-tauri/src/platforms/pinterest/mod.rs b/src-tauri/src/platforms/pinterest/mod.rsindex 0e9f3542..70a274d9 100644--- a/src-tauri/src/platforms/pinterest/mod.rs+++ b/src-tauri/src/platforms/pinterest/mod.rs@@ -214,7 +214,9 @@ impl PlatformDownloader for PinterestDownloader {opts.download_mode.as_deref(),opts.format_id.as_deref(),opts.filename_template.as_deref(),- opts.referer.as_deref().or(Some("https://www.pinterest.com/")),+ opts.referer+ .as_deref()+ .or(Some("https://www.pinterest.com/")),opts.cancel_token.clone(),None,opts.concurrent_fragments,diff --git a/src-tauri/src/platforms/twitter/mod.rs b/src-tauri/src/platforms/twitter/mod.rsindex 9263eea1..d968a171 100644--- a/src-tauri/src/platforms/twitter/mod.rs+++ b/src-tauri/src/platforms/twitter/mod.rs@@ -77,10 +77,7 @@ impl TwitterDownloader {}fn clone_media_array(value: &serde_json::Value) -> Option<Vec<serde_json::Value>> {- value- .as_array()- .filter(|items| !items.is_empty())- .cloned()+ value.as_array().filter(|items| !items.is_empty()).cloned()}fn find_first_array_for_key(@@ -116,7 +113,9 @@ impl TwitterDownloader {None}- fn media_arrays_from_tweet_result(tweet_result: &serde_json::Value) -> Option<Vec<serde_json::Value>> {+ fn media_arrays_from_tweet_result(+ tweet_result: &serde_json::Value,+ ) -> Option<Vec<serde_json::Value>> {let candidate_paths = ["/legacy/extended_entities/media","/tweet/legacy/extended_entities/media",@@ -163,8 +162,14 @@ impl TwitterDownloader {return Some(TwitterMediaType::Video);}- if media_item.get("media_url_https").and_then(|v| v.as_str()).is_some()- || media_item.get("media_url").and_then(|v| v.as_str()).is_some()+ if media_item+ .get("media_url_https")+ .and_then(|v| v.as_str())+ .is_some()+ || media_item+ .get("media_url")+ .and_then(|v| v.as_str())+ .is_some(){return Some(TwitterMediaType::Photo);}@@ -473,18 +478,25 @@ impl TwitterDownloader {fn extract_syndication_media(json: &serde_json::Value,) -> anyhow::Result<Vec<serde_json::Value>> {- let typename = json.get("__typename").and_then(|v| v.as_str()).unwrap_or("");+ let typename = json+ .get("__typename")+ .and_then(|v| v.as_str())+ .unwrap_or("");if typename == "TweetTombstone" || typename == "TweetUnavailable" {tracing::warn!("[twitter] syndication tombstone typename={}", typename);return Err(anyhow!("Post not available"));}- let media = json.get("mediaDetails")+ let media = json+ .get("mediaDetails").and_then(Self::clone_media_array).or_else(|| Self::find_first_array_for_key(json, "mediaDetails")).ok_or_else(|| anyhow!("No media found in tweet"))?;- tracing::debug!("[twitter] syndication extracted {} media entries", media.len());+ tracing::debug!(+ "[twitter] syndication extracted {} media entries",+ media.len()+ );Ok(media)}@@ -561,37 +573,35 @@ impl TwitterDownloader {fn parse_media_items(media: &[serde_json::Value]) -> anyhow::Result<TwitterMedia> {let items: Vec<TwitterMediaItem> = media.iter()- .filter_map(|m| {- match Self::infer_media_type(m)? {- TwitterMediaType::Photo => {- let (url, ext) = Self::best_photo_url(m)?;- Some(TwitterMediaItem {- media_type: TwitterMediaType::Photo,- url,- extension: ext,- })- }- TwitterMediaType::Video => {- let url = Self::best_video_url(m)?;- let extension = if url.contains(".m3u8") || url.contains("mpegurl") {- "ytdlp"- } else {- "mp4"- };- Some(TwitterMediaItem {- media_type: TwitterMediaType::Video,- url,- extension: extension.to_string(),- })- }- TwitterMediaType::AnimatedGif => {- let url = Self::best_video_url(m)?;- Some(TwitterMediaItem {- media_type: TwitterMediaType::AnimatedGif,- url,- extension: "mp4".to_string(),- })- }+ .filter_map(|m| match Self::infer_media_type(m)? {+ TwitterMediaType::Photo => {+ let (url, ext) = Self::best_photo_url(m)?;+ Some(TwitterMediaItem {+ media_type: TwitterMediaType::Photo,+ url,+ extension: ext,+ })+ }+ TwitterMediaType::Video => {+ let url = Self::best_video_url(m)?;+ let extension = if url.contains(".m3u8") || url.contains("mpegurl") {+ "ytdlp"+ } else {+ "mp4"+ };+ Some(TwitterMediaItem {+ media_type: TwitterMediaType::Video,+ url,+ extension: extension.to_string(),+ })+ }+ TwitterMediaType::AnimatedGif => {+ let url = Self::best_video_url(m)?;+ Some(TwitterMediaItem {+ media_type: TwitterMediaType::AnimatedGif,+ url,+ extension: "mp4".to_string(),+ })}}).collect();@@ -615,7 +625,10 @@ impl TwitterDownloader {}}- fn media_info_from_twitter_media(filename_base: String, twitter_media: TwitterMedia) -> MediaInfo {+ fn media_info_from_twitter_media(+ filename_base: String,+ twitter_media: TwitterMedia,+ ) -> MediaInfo {match twitter_media {TwitterMedia::Single(item) => {let media_type = Self::media_type_for_item(&item);@@ -840,7 +853,11 @@ 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"))?;- tracing::debug!("[twitter] native_get_media_info tweet_id={} url={}", tweet_id, url);+ tracing::debug!(+ "[twitter] native_get_media_info tweet_id={} url={}",+ tweet_id,+ url+ );let filename_base = format!("twitter_{}", tweet_id);@@ -859,7 +876,10 @@ impl TwitterDownloader {let twitter_media = Self::parse_media_items(&media_items)?;- Ok(Self::media_info_from_twitter_media(filename_base, twitter_media))+ Ok(Self::media_info_from_twitter_media(+ filename_base,+ twitter_media,+ ))}async fn try_graphql(&self, tweet_id: &str) -> anyhow::Result<Vec<serde_json::Value>> {diff --git a/src-tauri/src/platforms/twitter/tests.rs b/src-tauri/src/platforms/twitter/tests.rsnew file mode 100644index 00000000..8b137891--- /dev/null+++ b/src-tauri/src/platforms/twitter/tests.rs@@ -0,0 +1 @@+diff --git a/src-tauri/src/plugin_host.rs b/src-tauri/src/plugin_host.rsindex 3d26bec7..ba92957b 100644--- a/src-tauri/src/plugin_host.rs+++ b/src-tauri/src/plugin_host.rs@@ -163,4 +163,8 @@ impl<R: Runtime + 'static> PluginHost for PluginHostImpl<R> {cookie_count: primary.cookie_count,}}++ fn emit_download_log(&self, download_id: u64, line: &str) {+ omniget_core::core::log_hook::emit_log(download_id, line);+ }}diff --git a/src-tauri/src/plugin_loader.rs b/src-tauri/src/plugin_loader.rsindex 7fcf019a..82efa931 100644--- a/src-tauri/src/plugin_loader.rs+++ b/src-tauri/src/plugin_loader.rs@@ -179,14 +179,13 @@ fn load_single_plugin(PluginLoadError::simple("manifest_parse", format!("Invalid plugin.json: {e}"))})?;- let lib_path = find_native_lib(plugin_dir, manifest.rust_crate.as_deref()).ok_or_else(- || {+ let lib_path =+ find_native_lib(plugin_dir, manifest.rust_crate.as_deref()).ok_or_else(|| {PluginLoadError::simple("no_native_lib",format!("No native library found in {}", plugin_dir.display()),)- },- )?;+ })?;let lib = unsafe { libloading::Library::new(&lib_path) }.map_err(|e| {PluginLoadError::simple(@@ -227,9 +226,9 @@ fn load_single_plugin(})?;let mut plugin = unsafe { Box::from_raw(init_fn()) };- plugin.initialize(host).map_err(|e| {- PluginLoadError::simple("initialize", format!("Plugin init failed: {e}"))- })?;+ plugin+ .initialize(host)+ .map_err(|e| PluginLoadError::simple("initialize", format!("Plugin init failed: {e}")))?;Ok(LoadedPlugin {_lib: Some(lib),