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
Feat:add delete-multi-cookies and fix cookie handling, downloads, subtitles, and platform extraction (#134)
silverashe15f1a587290
diff --git a/src-tauri/omniget-core/src/core/ytdlp.rs b/src-tauri/omniget-core/src/core/ytdlp.rsindex 69e36dde..16ef2269 100644--- a/src-tauri/omniget-core/src/core/ytdlp.rs+++ b/src-tauri/omniget-core/src/core/ytdlp.rs@@ -19,6 +19,8 @@ type CookiesFromBrowserFn = Box<dyn Fn() -> String + Send + Sync>;type ManualCookieHeaderFn = Box<dyn Fn() -> String + Send + Sync>;type ExtRefererFn = Box<dyn Fn(&str) -> Option<String> + Send + Sync>;type IncludeAutoSubsFn = Box<dyn Fn() -> bool + Send + Sync>;+type CaptionLocaleFn = Box<dyn Fn() -> String + Send + Sync>;+type KeepVttFn = Box<dyn Fn() -> bool + Send + Sync>;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>;@@ -39,6 +41,8 @@ static COOKIES_FROM_BROWSER_FN: OnceLock<CookiesFromBrowserFn> = OnceLock::new()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 CAPTION_LOCALE_FN: OnceLock<CaptionLocaleFn> = OnceLock::new();+static KEEP_VTT_FN: OnceLock<KeepVttFn> = 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();@@ -93,6 +97,40 @@ fn include_auto_subs_setting() -> bool {INCLUDE_AUTO_SUBS_FN.get().map(|f| f()).unwrap_or(false)}+pub fn set_caption_locale_fn(f: impl Fn() -> String + Send + Sync + 'static) {+ let _ = CAPTION_LOCALE_FN.set(Box::new(f));+}++fn caption_locale_setting() -> String {+ let lang = CAPTION_LOCALE_FN+ .get()+ .map(|f| f())+ .unwrap_or_else(|| "en".to_string());+ let lang = lang.trim();+ if lang.is_empty() {+ "en".to_string()+ } else {+ lang.to_string()+ }+}++fn requested_caption_locales() -> Vec<String> {+ caption_locale_setting()+ .split(',')+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .map(ToString::to_string)+ .collect()+}++pub fn set_keep_vtt_fn(f: impl Fn() -> bool + Send + Sync + 'static) {+ let _ = KEEP_VTT_FN.set(Box::new(f));+}++fn keep_vtt_setting() -> bool {+ KEEP_VTT_FN.get().map(|f| f()).unwrap_or(false)+}+pub fn set_translate_metadata_fn(f: impl Fn() -> Option<String> + Send + Sync + 'static) {let _ = TRANSLATE_METADATA_FN.set(Box::new(f));}@@ -101,6 +139,63 @@ fn translate_metadata_lang() -> Option<String> {TRANSLATE_METADATA_FN.get().and_then(|f| f())}+static ACTIVE_PROCESS_PIDS: OnceLock<std::sync::Mutex<HashMap<u64, u32>>> = OnceLock::new();++fn active_process_pids() -> &'static std::sync::Mutex<HashMap<u64, u32>> {+ ACTIVE_PROCESS_PIDS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))+}++fn register_download_process(download_id: u64, pid: u32) {+ if let Ok(mut pids) = active_process_pids().lock() {+ pids.insert(download_id, pid);+ }+}++fn unregister_download_process(download_id: u64) {+ if let Ok(mut pids) = active_process_pids().lock() {+ pids.remove(&download_id);+ }+}++#[cfg(unix)]+fn signal_download_process(download_id: u64, signal: &str) -> bool {+ let pid = active_process_pids()+ .lock()+ .ok()+ .and_then(|pids| pids.get(&download_id).copied());+ let Some(pid) = pid else {+ return false;+ };+ std::process::Command::new("kill")+ .arg(signal)+ .arg(pid.to_string())+ .status()+ .map(|s| s.success())+ .unwrap_or(false)+}++#[cfg(not(unix))]+fn signal_download_process(_download_id: u64, _signal: &str) -> bool {+ false+}++pub fn pause_download_process(download_id: u64) -> bool {+ signal_download_process(download_id, "-STOP")+}++pub fn resume_download_process(download_id: u64) -> bool {+ signal_download_process(download_id, "-CONT")+}++fn normalize_youtube_lang(lang: &str) -> String {+ match lang.trim() {+ "zh" | "zh-CN" | "zh-cn" | "zh-Hans" | "zh-hans" => "zh-CN".to_string(),+ "zh-TW" | "zh-tw" | "zh-Hant" | "zh-hant" => "zh-TW".to_string(),+ "zh-HK" | "zh-hk" => "zh-HK".to_string(),+ other => other.to_string(),+ }+}+pub fn set_sponsorblock_fn(f: impl Fn() -> bool + Send + Sync + 'static) {let _ = SPONSORBLOCK_FN.set(Box::new(f));}@@ -420,6 +515,78 @@ fn append_cookie_header(args: &mut Vec<String>, cookie_header: &str) {args.push(format!("Cookie:{}", cookie_header));}+enum MetadataCookieSource {+ PerDomain(PathBuf),+ ManualHeader(String),+ CookieFile(PathBuf),+ Browser(String),+ None,+ ExplicitHeader,+}++fn metadata_cookie_source(url: &str, extra_flags: &[String]) -> MetadataCookieSource {+ if has_explicit_cookie_header(extra_flags) {+ return MetadataCookieSource::ExplicitHeader;+ }++ if let Some(path) = per_domain_cookie_file(url) {+ return MetadataCookieSource::PerDomain(path);+ }++ if let Some(header) = manual_cookie_header_setting() {+ return MetadataCookieSource::ManualHeader(header);+ }++ if let Some(path) = extension_cookie_file() {+ return MetadataCookieSource::CookieFile(path);+ }++ if let Some(path) = global_cookie_file().map(PathBuf::from) {+ return MetadataCookieSource::CookieFile(path);+ }++ let browser = cookies_from_browser_setting();+ if !browser.is_empty() {+ return MetadataCookieSource::Browser(browser);+ }++ MetadataCookieSource::None+}++fn append_metadata_cookie_args(+ args: &mut Vec<String>,+ url: &str,+ extra_flags: &[String],+ context: &str,+) {+ match metadata_cookie_source(url, extra_flags) {+ MetadataCookieSource::PerDomain(path) => {+ args.push("--cookies".to_string());+ args.push(path.to_string_lossy().to_string());+ tracing::debug!("[yt-dlp] using per-domain cookies for {}", context);+ }+ MetadataCookieSource::ManualHeader(header) => {+ append_cookie_header(args, &header);+ tracing::debug!("[yt-dlp] using manual cookie header for {}", context);+ }+ MetadataCookieSource::CookieFile(path) => {+ args.push("--cookies".to_string());+ args.push(path.to_string_lossy().to_string());+ }+ MetadataCookieSource::Browser(browser) => {+ args.push("--cookies-from-browser".to_string());+ args.push(browser);+ }+ MetadataCookieSource::ExplicitHeader => {+ tracing::debug!(+ "[yt-dlp] skipping cookies-from-browser for {} because explicit Cookie header was provided",+ context+ );+ }+ MetadataCookieSource::None => {}+ }+}+struct YtRateLimiter {semaphore: tokio::sync::Semaphore,last_request_ns: AtomicU64,@@ -1101,51 +1268,7 @@ pub async fn get_video_info(args.push(extractor_args.to_string());}- let explicit_cookie_header = has_explicit_cookie_header(extra_flags);- let per_domain_cookies = if explicit_cookie_header {- None- } else {- per_domain_cookie_file(url)- };- let manual_cookie_header = if explicit_cookie_header || per_domain_cookies.is_some() {- None- } else {- manual_cookie_header_setting()- };- let extension_cookies = if per_domain_cookies.is_none() && manual_cookie_header.is_none() {- extension_cookie_file()- } else {- None- };- let global_cf = if per_domain_cookies.is_none() && manual_cookie_header.is_none() {- global_cookie_file()- } else {- None- };- if let Some(ref cf) = per_domain_cookies {- args.push("--cookies".to_string());- args.push(cf.to_string_lossy().to_string());- tracing::debug!("[yt-dlp] using per-domain cookies from cookies manager");- } else if let Some(ref cookie_header) = manual_cookie_header {- append_cookie_header(&mut args, cookie_header);- tracing::debug!("[yt-dlp] using manual cookie header from settings");- } else if let Some(ref cf) = extension_cookies {- args.push("--cookies".to_string());- args.push(cf.to_string_lossy().to_string());- } else if let Some(ref cf) = global_cf {- args.push("--cookies".to_string());- args.push(cf.clone());- } else if !explicit_cookie_header {- let cfb = cookies_from_browser_setting();- if !cfb.is_empty() {- args.push("--cookies-from-browser".to_string());- args.push(cfb);- }- } else {- tracing::debug!(- "[yt-dlp] skipping cookies-from-browser because explicit Cookie header was provided"- );- }+ append_metadata_cookie_args(&mut args, url, extra_flags, "video info");args.extend(proxy_args());args.extend(extra_flags.iter().cloned());@@ -1235,6 +1358,140 @@ pub async fn get_video_info(Err(translate_ytdlp_error(&last_error))}+async fn select_available_subtitle_lang(+ ytdlp: &Path,+ url: &str,+ extra_flags: &[String],+ include_auto: bool,+) -> anyhow::Result<Option<String>> {+ let requested = requested_caption_locales();+ let json = get_video_info(ytdlp, url, extra_flags).await?;+ let (manual, auto) = subtitle_languages_from_json(&json);+ let available: Vec<String> = if include_auto {+ manual.iter().chain(auto.iter()).cloned().collect()+ } else {+ manual.clone()+ };++ let selected = requested+ .iter()+ .find_map(|lang| matching_subtitle_lang(lang, &available));+ if selected.is_some() {+ return Ok(selected);+ }++ let requested_label = if requested.is_empty() {+ "(empty)".to_string()+ } else {+ requested.join(", ")+ };+ let manual_label = format_lang_list(&manual);+ let auto_label = format_lang_list(&auto);+ let line = if manual.is_empty() && auto.is_empty() {+ format!(+ "[subtitles] 没有可下载字幕;继续下载视频,不下载字幕。您选择的字幕语言: {}",+ requested_label+ )+ } else if manual.is_empty() && !auto.is_empty() && !include_auto {+ format!(+ "[subtitles] 没有手工字幕;自动字幕可用但未启用。继续下载视频,不下载字幕。您选择: {}; 自动字幕: {}",+ requested_label, auto_label+ )+ } else {+ format!(+ "[subtitles] 没有您选择的字幕;继续下载视频,不下载字幕。您选择: {}; 可用手工字幕: {}; 可用自动字幕: {}",+ requested_label, manual_label, auto_label+ )+ };+ tracing::warn!("{}", line);+ if let Some(dl_id) = log_hook::current_download_id() {+ log_hook::emit_log(dl_id, &line);+ }++ Ok(None)+}++fn subtitle_languages_from_json(json: &serde_json::Value) -> (Vec<String>, Vec<String>) {+ fn collect(map: Option<&serde_json::Value>) -> Vec<String> {+ let mut langs = Vec::new();+ if let Some(obj) = map.and_then(|v| v.as_object()) {+ for (lang, formats) in obj {+ if lang == "live_chat" {+ continue;+ }+ if formats.as_array().map(|a| !a.is_empty()).unwrap_or(false) {+ langs.push(lang.clone());+ }+ }+ }+ langs.sort_by_key(|s| s.to_ascii_lowercase());+ langs.dedup_by(|a, b| a.eq_ignore_ascii_case(b));+ langs+ }++ (+ collect(json.get("subtitles")),+ collect(json.get("automatic_captions")),+ )+}++fn matching_subtitle_lang(requested: &str, available: &[String]) -> Option<String> {+ available+ .iter()+ .find(|lang| normalize_lang_token(lang) == normalize_lang_token(requested))+ .cloned()+ .or_else(|| {+ available+ .iter()+ .find(|lang| subtitle_lang_matches(requested, lang))+ .cloned()+ })+}++fn subtitle_lang_matches(requested: &str, available: &str) -> bool {+ let requested = normalize_lang_token(requested);+ let available = normalize_lang_token(available);+ if requested.is_empty() || available.is_empty() {+ return false;+ }+ if requested == available {+ return true;+ }++ let req_base = requested.split('-').next().unwrap_or("");+ let avail_base = available.split('-').next().unwrap_or("");+ if req_base != avail_base {+ return false;+ }++ if req_base == "zh" {+ return zh_subtitle_group(&requested) == zh_subtitle_group(&available)+ || requested == "zh"+ || available == "zh";+ }++ requested == req_base || available == avail_base+}++fn normalize_lang_token(lang: &str) -> String {+ lang.trim().replace('_', "-").to_ascii_lowercase()+}++fn zh_subtitle_group(lang: &str) -> &'static str {+ match lang {+ "zh-tw" | "zh-hant" | "zh-hk" | "zh-mo" => "traditional",+ _ => "simplified",+ }+}++fn format_lang_list(langs: &[String]) -> String {+ if langs.is_empty() {+ "none".to_string()+ } else {+ langs.join(", ")+ }+}+pub async fn get_playlist_info(ytdlp: &Path,url: &str,@@ -1268,6 +1525,8 @@ pub async fn get_playlist_info(args.push("youtube:player_client=default".to_string());}+ append_metadata_cookie_args(&mut args, url, extra_flags, "playlist info");+args.extend(proxy_args());args.extend(extra_flags.iter().cloned());args.push(url.to_string());@@ -1401,10 +1660,8 @@ pub async fn get_playlist_info_incremental(yt_rate_limiter().acquire().await;}- let archive_path = std::env::temp_dir().join(format!(- "omniget-chan-archive-{}.txt",- std::process::id()- ));+ let archive_path =+ std::env::temp_dir().join(format!("omniget-chan-archive-{}.txt", std::process::id()));{let mut content = String::with_capacity(seen_ids.len() * 24);for id in seen_ids {@@ -1550,6 +1807,7 @@ pub async fn download_video(}let _ = progress.send(ProgressUpdate::percent(-1.0)).await;+ let download_started_at = std::time::SystemTime::now();let mode = download_mode.unwrap_or("auto");let is_audio_only = mode == "audio";@@ -1851,7 +2109,7 @@ pub async fn download_video(if let Some(lang) = translate_metadata_lang() {base_args.push("--extractor-args".to_string());- base_args.push(format!("youtube:lang={}", lang));+ base_args.push(format!("youtube:lang={}", normalize_youtube_lang(&lang)));}if sponsorblock_enabled() && is_youtube_url(url) {@@ -1904,20 +2162,51 @@ pub async fn download_video(base_args.push("--windows-filenames".to_string());}- let should_download_subs = download_subtitles && rate_limit_429_count() < 2;+ let include_auto_subs = include_auto_subs_setting();+ let mut selected_subtitle_lang: Option<String> = None;+ let mut should_download_subs = download_subtitles && rate_limit_429_count() < 2;+ if should_download_subs {+ match select_available_subtitle_lang(ytdlp, url, extra_flags, include_auto_subs).await {+ Ok(Some(lang)) => {+ if let Some(dl_id) = log_hook::current_download_id() {+ log_hook::emit_log(+ dl_id,+ &format!("[subtitles] using selected subtitle language: {}", lang),+ );+ }+ selected_subtitle_lang = Some(lang);+ }+ Ok(None) => {+ should_download_subs = false;+ }+ Err(err) => {+ should_download_subs = false;+ let line = format!(+ "[subtitles] could not check subtitles; continuing without subtitles: {}",+ err+ );+ tracing::warn!("{}", line);+ if let Some(dl_id) = log_hook::current_download_id() {+ log_hook::emit_log(dl_id, &line);+ }+ }+ }+ }let subtitle_args = if should_download_subs {let mut args = vec!["--write-sub".to_string()];- if include_auto_subs_setting() {+ if include_auto_subs {args.push("--write-auto-sub".to_string());}+ let caption_locale = selected_subtitle_lang.unwrap_or_else(caption_locale_setting);args.extend(["--sub-lang".to_string(),- "en,pt,es".to_string(),+ caption_locale,"--sub-format".to_string(),"best".to_string(),- "--convert-subs".to_string(),- "srt".to_string(),]);+ if !keep_vtt_setting() {+ args.extend(["--convert-subs".to_string(), "srt".to_string()]);+ }args} else {Vec::new()@@ -1991,12 +2280,18 @@ pub async fn download_video(args.extend(extra_args.iter().cloned());args.push(url.to_string());- let mut child = crate::core::process::command(ytdlp)- .args(&args)+ let mut cmd = crate::core::process::command(ytdlp);+ cmd.args(&args).stdout(Stdio::piped()).stderr(Stdio::piped())+ .kill_on_drop(true);+ let mut child = cmd.spawn().map_err(|e| anyhow!("Failed to start yt-dlp: {}", e))?;+ let registered_download_id = log_hook::current_download_id();+ if let (Some(download_id), Some(pid)) = (registered_download_id, child.id()) {+ register_download_process(download_id, pid);+ }tracing::debug!("[perf] download_video: yt-dlp process spawned at {:?} (attempt {})",_timer_start.elapsed(),@@ -2060,9 +2355,12 @@ pub async fn download_video(}}if line.contains("[Merger]") {- if 99.0 > max_reported {- max_reported = 99.0;- let _ = progress_tx.send(ProgressUpdate::percent(99.0)).await;+ let merging_progress = max_reported.max(95.0).min(98.0);+ if merging_progress > max_reported {+ max_reported = merging_progress;+ let _ = progress_tx+ .send(ProgressUpdate::percent(merging_progress))+ .await;last_send = std::time::Instant::now();}continue;@@ -2105,16 +2403,13 @@ pub async fn download_video(last_send = std::time::Instant::now();}}- } else if line.trim_start().starts_with("download:")- || line.contains("[download]")+ } else if line.trim_start().starts_with("download:") || line.contains("[download]"){let dl = parse_downloaded_bytes_line(&line).or_else(|| parse_default_download_line(&line).map(|(d, _)| d as u64));let speed = parse_speed_line(&line).or_else(|| parse_default_download_line(&line).map(|(_, s)| s));- if (dl.is_some() || speed.is_some())- && last_send.elapsed() >= throttle- {+ if (dl.is_some() || speed.is_some()) && last_send.elapsed() >= throttle {let _ = progress_tx.send(ProgressUpdate::rich(0.0, dl, None, speed, None)).await;@@ -2143,6 +2438,9 @@ pub async fn download_video(s = child.wait() => s.map_err(|e| anyhow!("yt-dlp process failed: {}", e))?,_ = cancel_token.cancelled() => {let _ = child.kill().await;+ if let Some(download_id) = registered_download_id {+ unregister_download_process(download_id);+ }let _ = line_reader.await;let _ = stderr_reader.await;cleanup_part_files(output_dir).await;@@ -2151,6 +2449,10 @@ pub async fn download_video(}};+ if let Some(download_id) = registered_download_id {+ unregister_download_process(download_id);+ }+let _ = line_reader.await;let stderr_content = stderr_reader.await.unwrap_or_default();@@ -2183,6 +2485,21 @@ pub async fn download_video(}_ => find_downloaded_file(output_dir, url).await?,};+ if download_subtitles {+ let moved = ensure_subtitles_next_to_media(+ output_dir,+ &file_path,+ download_started_at,+ url,+ );+ if moved > 0 {+ tracing::info!(+ "[yt-dlp] moved {} subtitle file(s) next to {}",+ moved,+ file_path.display()+ );+ }+ }let meta = std::fs::metadata(&file_path)?;tracing::debug!("[perf] download_video took {:?}", _timer_start.elapsed());@@ -2401,6 +2718,130 @@ async fn cleanup_part_files(dir: &Path) {}}+fn ensure_subtitles_next_to_media(+ output_dir: &Path,+ media_path: &Path,+ started_at: std::time::SystemTime,+ url: &str,+) -> usize {+ let Some(media_dir) = media_path.parent() else {+ return 0;+ };+ let Some(media_stem) = media_path.file_stem().and_then(|s| s.to_str()) else {+ return 0;+ };+ let media_stem = media_stem.to_string();+ let video_id = extract_id_from_url(url).unwrap_or_default();+ let cutoff = started_at+ .checked_sub(std::time::Duration::from_secs(5))+ .unwrap_or(started_at);+ let mut candidates = Vec::new();+ collect_subtitle_candidates(output_dir, cutoff, &mut candidates, 0);++ let mut moved = 0usize;+ for path in candidates {+ if path.parent() == Some(media_dir) {+ continue;+ }+ let name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");+ let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");+ let matches_media = stem.starts_with(&media_stem)+ || media_stem.starts_with(stem)+ || (!video_id.is_empty() && name.contains(&video_id));+ if !matches_media {+ continue;+ }+ let Some(file_name) = path.file_name() else {+ continue;+ };+ let dest = unique_sidecar_path(media_dir.join(file_name));+ if move_file_best_effort(&path, &dest) {+ moved += 1;+ }+ }+ moved+}++fn collect_subtitle_candidates(+ dir: &Path,+ cutoff: std::time::SystemTime,+ out: &mut Vec<PathBuf>,+ depth: usize,+) {+ if depth > 3 {+ return;+ }+ let Ok(entries) = std::fs::read_dir(dir) else {+ return;+ };+ for entry in entries.flatten() {+ let path = entry.path();+ if path.is_dir() {+ collect_subtitle_candidates(&path, cutoff, out, depth + 1);+ continue;+ }+ if !path.is_file() || !is_subtitle_path(&path) {+ continue;+ }+ let Ok(meta) = entry.metadata() else {+ continue;+ };+ if meta.len() == 0 {+ continue;+ }+ if meta.modified().map(|m| m >= cutoff).unwrap_or(false) {+ out.push(path);+ }+ }+}++fn is_subtitle_path(path: &Path) -> bool {+ let ext = path+ .extension()+ .and_then(|e| e.to_str())+ .unwrap_or("")+ .to_ascii_lowercase();+ matches!(+ ext.as_str(),+ "vtt" | "srt" | "ass" | "ssa" | "sub" | "lrc" | "ttml"+ )+}++fn unique_sidecar_path(path: PathBuf) -> PathBuf {+ if !path.exists() {+ return path;+ }+ let parent = path.parent().map(Path::to_path_buf).unwrap_or_default();+ let stem = path+ .file_stem()+ .and_then(|s| s.to_str())+ .unwrap_or("subtitle");+ let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("");+ for idx in 1..1000 {+ let file_name = if ext.is_empty() {+ format!("{} ({})", stem, idx)+ } else {+ format!("{} ({}).{}", stem, idx, ext)+ };+ let candidate = parent.join(file_name);+ if !candidate.exists() {+ return candidate;+ }+ }+ path+}++fn move_file_best_effort(from: &Path, to: &Path) -> bool {+ if std::fs::rename(from, to).is_ok() {+ return true;+ }+ if std::fs::copy(from, to).is_ok() {+ let _ = std::fs::remove_file(from);+ return true;+ }+ false+}+fn sanitize_log_line(line: &str) -> String {let mut result = String::with_capacity(line.len());let mut remaining = line;@@ -2615,9 +3056,7 @@ fn parse_downloaded_bytes_line(line: &str) -> Option<u64> {fn parse_size_token(token: &str) -> Option<f64> {let t = token.trim().trim_end_matches("/s").trim();- let split = t- .find(|c: char| c.is_ascii_alphabetic())- .unwrap_or(t.len());+ let split = t.find(|c: char| c.is_ascii_alphabetic()).unwrap_or(t.len());let (num, unit) = t.split_at(split);let value: f64 = num.trim().parse().ok()?;let mult = match unit.trim() {diff --git a/src-tauri/src/commands/auth_webview.rs b/src-tauri/src/commands/auth_webview.rsindex 00186e7f..1ac6b376 100644--- a/src-tauri/src/commands/auth_webview.rs+++ b/src-tauri/src/commands/auth_webview.rs@@ -192,7 +192,7 @@ pub async fn open_auth_webview(async fn poll_for_cookie(window: &tauri::WebviewWindow,default_domain: &str,- domains: &[String],+ _domains: &[String],target_cookie: &str,) -> Vec<AuthCookie> {let target_lower = target_cookie.to_lowercase();@@ -208,10 +208,10 @@ async fn poll_for_cookie("[auth_webview] cookie polling timed out after {:.1}s",elapsed.as_secs_f64());- return extract_cookies(window, default_domain, domains).await;+ return extract_cookies(window, default_domain, _domains).await;}- let cookies = extract_cookies(window, default_domain, domains).await;+ let cookies = extract_cookies(window, default_domain, _domains).await;let found = cookies.iter()@@ -245,6 +245,9 @@ async fn extract_cookies(default_domain: &str,domains: &[String],) -> Vec<AuthCookie> {+ #[cfg(not(windows))]+ let _ = domains;+#[cfg(windows)]{let native = extract_cookies_native(window, domains).await;diff --git a/src-tauri/src/commands/bilibili_auth.rs b/src-tauri/src/commands/bilibili_auth.rsindex 65505cd8..937b2031 100644--- a/src-tauri/src/commands/bilibili_auth.rs+++ b/src-tauri/src/commands/bilibili_auth.rs@@ -84,9 +84,7 @@ pub async fn bilibili_webview_login(}#[tauri::command]-pub async fn bilibili_qr_generate(- user_agent: Option<String>,-) -> Result<qr::QrSession, String> {+pub async fn bilibili_qr_generate(user_agent: Option<String>) -> Result<qr::QrSession, String> {let _ = crate::platforms::bilibili::cookie::ensure_fresh().await;let client = build_anonymous_client(user_agent)?;qr::generate(&client)@@ -321,7 +319,9 @@ pub async fn bilibili_import_history(slug: String) -> Result<BilibiliImportResul}#[tauri::command]-pub async fn bilibili_account_status(slug: Option<String>) -> Result<BilibiliAccountStatus, String> {+pub async fn bilibili_account_status(+ slug: Option<String>,+) -> Result<BilibiliAccountStatus, String> {let client = match slug.as_deref() {Some(s) if !s.is_empty() => ApiClient::new().map_err(|e| e.i18n_key().to_string())?diff --git a/src-tauri/src/commands/downloads.rs b/src-tauri/src/commands/downloads.rsindex caa0fb04..983e6b12 100644--- a/src-tauri/src/commands/downloads.rs+++ b/src-tauri/src/commands/downloads.rs@@ -869,7 +869,7 @@ pub async fn download_from_url());}- let download_id = std::time::SystemTime::now()+ let mut download_id = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_millis() as u64;@@ -886,6 +886,7 @@ pub async fn download_from_url(tracing::debug!("[perf] download_from_url took {:?}", _timer_start.elapsed());return Err("Download already in progress for this URL".to_string());}+ download_id = q.next_available_id(download_id);}let downloader = match state.registry.find_platform(&url) {@@ -1018,7 +1019,7 @@ pub async fn download_with_custom_args());}- let download_id = std::time::SystemTime::now()+ let mut download_id = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_millis() as u64;@@ -1033,6 +1034,7 @@ pub async fn download_with_custom_args(if q.has_url(&url) {return Err("Download already in progress for this URL".to_string());}+ download_id = q.next_available_id(download_id);}let downloader: Arc<dyn crate::platforms::traits::PlatformDownloader> =diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rsindex 87c24836..0b107955 100644--- a/src-tauri/src/commands/mod.rs+++ b/src-tauri/src/commands/mod.rs@@ -1,8 +1,8 @@pub mod ai;pub mod app_lifecycle;pub mod auth_webview;-pub mod bilibili_auth;pub mod autostart;+pub mod bilibili_auth;pub mod browser_extension;pub mod channels;pub mod clip;diff --git a/src-tauri/src/cookies/commands.rs b/src-tauri/src/cookies/commands.rsindex 6cb4fe29..86d6fb6e 100644--- a/src-tauri/src/cookies/commands.rs+++ b/src-tauri/src/cookies/commands.rs@@ -23,6 +23,17 @@ pub struct ImportRequest {pub alias: Option<String>,}+fn domain_from_url(raw: &str) -> Option<String> {+ let parsed = url::Url::parse(raw).ok()?;+ let host = parsed.host_str()?;+ let root = super::platform::root_domain_of(host);+ if root.is_empty() {+ None+ } else {+ Some(root)+ }+}+#[derive(Debug, Serialize)]pub struct ImportResponse {pub buckets_written: Vec<BucketWrite>,@@ -55,6 +66,11 @@ pub struct ClearRequest {pub slug: Option<String>,}+#[derive(Debug, Deserialize)]+pub struct ClearBatchRequest {+ pub items: Vec<ClearRequest>,+}+#[derive(Debug, Deserialize)]pub struct RenameRequest {pub domain: String,@@ -68,6 +84,12 @@ pub struct OkResponse {pub ok: bool,}+#[derive(Debug, Serialize)]+pub struct ClearBatchResponse {+ pub ok: bool,+ pub cleared: usize,+}+const DEFAULT_SLUG: &str = "_default";#[tauri::command]@@ -92,7 +114,12 @@ pub async fn cookies_read(request: ReadRequest) -> Result<ReadResponse, String>#[tauri::command]pub async fn cookies_import(request: ImportRequest) -> Result<ImportResponse, String> {- let cookies = parsers::parse(&request.content).map_err(|e| e.to_string())?;+ let source_domain = request.source_url.as_deref().and_then(domain_from_url);+ let cookies = match source_domain.as_deref() {+ Some(domain) => parsers::parse_for_domain(&request.content, domain),+ None => parsers::parse(&request.content),+ }+ .map_err(|e| e.to_string())?;if cookies.is_empty() {return Err("No cookies found in payload".to_string());}@@ -130,6 +157,17 @@ pub async fn cookies_clear(request: ClearRequest) -> Result<OkResponse, String>Ok(OkResponse { ok: true })}+#[tauri::command]+pub async fn cookies_clear_batch(request: ClearBatchRequest) -> Result<ClearBatchResponse, String> {+ let mut cleared = 0usize;+ for item in request.items {+ let slug = item.slug.as_deref().unwrap_or(DEFAULT_SLUG);+ storage::move_to_trash(&item.domain, slug).map_err(|e| e.to_string())?;+ cleared += 1;+ }+ Ok(ClearBatchResponse { ok: true, cleared })+}+#[tauri::command]pub async fn cookies_rename(request: RenameRequest) -> Result<OkResponse, String> {let slug = request.slug.as_deref().unwrap_or(DEFAULT_SLUG);@@ -282,7 +320,8 @@ pub async fn cookies_add_account(request: AddAccountRequest) -> Result<AddAccounif request.alias.trim().is_empty() {return Err("Alias is required for a new account".to_string());}- let cookies = parsers::parse(&request.content).map_err(|e| e.to_string())?;+ let cookies =+ parsers::parse_for_domain(&request.content, &request.domain).map_err(|e| e.to_string())?;if cookies.is_empty() {return Err("No cookies found in payload".to_string());}@@ -374,8 +413,71 @@ pub struct CookieTestResponse {pub message: String,}+fn cookie_names_from_netscape(content: &str) -> std::collections::HashSet<String> {+ let mut names = std::collections::HashSet::new();+ for raw in content.lines() {+ let line = raw.trim();+ if line.is_empty() || line.starts_with("# Netscape") {+ continue;+ }+ let effective = line.strip_prefix("#HttpOnly_").unwrap_or(line);+ if effective.starts_with('#') {+ continue;+ }+ let cols: Vec<&str> = effective.split('\t').collect();+ if cols.len() >= 7 {+ names.insert(cols[5].to_string());+ }+ }+ names+}++fn test_x_twitter_cookie(slug: Option<&str>) -> CookieTestResponse {+ let path = storage::account_path_for_consumer("x.com", slug)+ .or_else(|| storage::account_path_for_consumer("twitter.com", slug));+ let Some(path) = path else {+ return CookieTestResponse {+ ok: false,+ message: "No X/Twitter cookie account found".to_string(),+ };+ };+ let Ok(content) = std::fs::read_to_string(path) else {+ return CookieTestResponse {+ ok: false,+ message: "Could not read X/Twitter cookie file".to_string(),+ };+ };+ let names = cookie_names_from_netscape(&content);+ let has_auth = names.contains("auth_token");+ let has_csrf = names.contains("ct0");+ if has_auth && has_csrf {+ CookieTestResponse {+ ok: true,+ message: "ok".to_string(),+ }+ } else {+ let mut missing = Vec::new();+ if !has_auth {+ missing.push("auth_token");+ }+ if !has_csrf {+ missing.push("ct0");+ }+ CookieTestResponse {+ ok: false,+ message: format!("Missing X/Twitter cookie fields: {}", missing.join(", ")),+ }+ }+}+#[tauri::command]pub async fn cookies_test(request: CookieTestRequest) -> Result<CookieTestResponse, String> {+ if let Some(domain) = domain_from_url(&request.url) {+ if matches!(domain.as_str(), "x.com" | "twitter.com") {+ return Ok(test_x_twitter_cookie(request.slug.as_deref()));+ }+ }+let ytdlp = crate::core::ytdlp::find_ytdlp_cached().await.ok_or_else(|| "yt-dlp unavailable".to_string())?;diff --git a/src-tauri/src/cookies/parsers.rs b/src-tauri/src/cookies/parsers.rsindex d8083c38..bb49c55e 100644--- a/src-tauri/src/cookies/parsers.rs+++ b/src-tauri/src/cookies/parsers.rs@@ -45,11 +45,97 @@ pub fn parse(content: &str) -> anyhow::Result<Vec<ExtensionCookie>> {CookieFormat::Netscape => parse_netscape(content),CookieFormat::Json => parse_json(content),CookieFormat::Unknown => {- anyhow::bail!("Unrecognized cookie format. Accepted: Netscape (yt-dlp), JSON (Edit-This-Cookie, Get-cookies.txt-LOCALLY).")+ anyhow::bail!("Unrecognized cookie format. Accepted: Netscape (yt-dlp), JSON (Edit-This-Cookie, Get-cookies.txt-LOCALLY), or a Cookie header when a target domain is provided.")}}}+pub fn parse_for_domain(content: &str, domain: &str) -> anyhow::Result<Vec<ExtensionCookie>> {+ match detect_format(content) {+ CookieFormat::Netscape => parse_netscape(content),+ CookieFormat::Json => parse_json(content),+ CookieFormat::Unknown if looks_like_cookie_header(content) => {+ parse_cookie_header(content, domain)+ }+ CookieFormat::Unknown => {+ anyhow::bail!("Unrecognized cookie format. Accepted: Netscape (yt-dlp), JSON (Edit-This-Cookie, Get-cookies.txt-LOCALLY), or Cookie header pairs like SESSDATA=...; bili_jct=... when a target domain is provided.")+ }+ }+}++fn looks_like_cookie_header(content: &str) -> bool {+ let trimmed = content.trim();+ if trimmed.is_empty() || trimmed.contains('\t') || trimmed.starts_with('#') {+ return false;+ }+ let body = trimmed.strip_prefix("Cookie:").unwrap_or(trimmed).trim();+ let mut found = 0usize;+ for part in body.split(';') {+ let p = part.trim();+ if p.is_empty() {+ continue;+ }+ let Some((name, value)) = p.split_once('=') else {+ return false;+ };+ let name = name.trim();+ if name.is_empty() || value.is_empty() || !is_cookie_name(name) {+ return false;+ }+ found += 1;+ }+ found > 0+}++fn is_cookie_name(name: &str) -> bool {+ name.bytes()+ .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))+}++pub fn parse_cookie_header(content: &str, domain: &str) -> anyhow::Result<Vec<ExtensionCookie>> {+ let root = domain.trim().trim_start_matches('.').to_lowercase();+ if root.is_empty() {+ anyhow::bail!("Target domain is required for Cookie header import.");+ }+ let cookie_domain = format!(".{}", root);+ let expires = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_secs() as i64)+ .unwrap_or(0)+ + 60 * 60 * 24 * 3;+ let body = content+ .trim()+ .strip_prefix("Cookie:")+ .unwrap_or(content.trim());+ let mut cookies = Vec::new();+ for part in body.split(';') {+ let p = part.trim();+ if p.is_empty() {+ continue;+ }+ let Some((name, value)) = p.split_once('=') else {+ continue;+ };+ let name = name.trim();+ let value = value.trim();+ if name.is_empty() || value.is_empty() || !is_cookie_name(name) {+ continue;+ }+ cookies.push(ExtensionCookie {+ domain: cookie_domain.clone(),+ http_only: name.eq_ignore_ascii_case("SESSDATA"),+ path: "/".to_string(),+ secure: true,+ expires,+ name: name.to_string(),+ value: value.to_string(),+ host_only: Some(false),+ same_site: None,+ });+ }+ Ok(cookies)+}+pub fn parse_netscape(content: &str) -> anyhow::Result<Vec<ExtensionCookie>> {let mut cookies = Vec::new();for raw in content.lines() {@@ -220,6 +306,24 @@ mod tests {assert!(cookies[0].secure);}+ #[test]+ fn parse_cookie_header_for_domain_marks_sessdata_and_expires_in_three_days() {+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_secs() as i64;+ let cookies =+ parse_for_domain("SESSDATA=abc; bili_jct=csrf; DedeUserID=42", "bilibili.com").unwrap();++ assert_eq!(cookies.len(), 3);+ assert_eq!(cookies[0].domain, ".bilibili.com");+ assert_eq!(cookies[0].name, "SESSDATA");+ assert!(cookies[0].http_only);+ assert!(cookies[0].secure);+ assert!(cookies[0].expires >= now + 60 * 60 * 24 * 3 - 2);+ assert!(cookies[0].expires <= now + 60 * 60 * 24 * 3 + 2);+ }+#[test]fn parse_json_session_cookie_zeros_expiration() {let raw = r#"[{"domain":"x.com","name":"sess","value":"v","session":true,"path":"/","secure":false}]"#;diff --git a/src-tauri/src/cookies/storage.rs b/src-tauri/src/cookies/storage.rsindex f3afdff5..b957e6f5 100644--- a/src-tauri/src/cookies/storage.rs+++ b/src-tauri/src/cookies/storage.rs@@ -169,6 +169,34 @@ fn sanitize_field(s: &str) -> String {.collect()}+fn site_source_url(root: &str) -> Option<String> {+ let root = root.trim_start_matches('.').to_lowercase();+ if root.is_empty() {+ return None;+ }+ let host = if root == "bilibili.com" {+ "www.bilibili.com"+ } else {+ root.as_str()+ };+ Some(format!("https://{}/", host))+}++fn normalize_source_url(source_url: Option<&str>, root: &str) -> Option<String> {+ let root = root_domain_of(root);+ if root.is_empty() {+ return None;+ }+ if let Some(parsed) = source_url.and_then(|u| url::Url::parse(u).ok()) {+ if let Some(host) = parsed.host_str() {+ if root_domain_of(host) == root {+ return site_source_url(&root);+ }+ }+ }+ site_source_url(&root)+}+pub struct IngestSource {pub source_url: Option<String>,pub source_label: String,@@ -224,6 +252,7 @@ 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 source_url = normalize_source_url(source.source_url.as_deref(), root);let bucket = registry.buckets.entry(root.clone())@@ -239,7 +268,7 @@ pub fn ingest_batch(if let Some(existing) = bucket.accounts.iter_mut().find(|a| a.slug == DEFAULT_SLUG) {existing.captured_at_ms = now;existing.cookie_count = count;- if let Some(ref u) = source.source_url {+ if let Some(ref u) = source_url {existing.source_url = Some(u.clone());}existing.source_label = Some(source.source_label.clone());@@ -250,7 +279,7 @@ pub fn ingest_batch(bucket.accounts.push(AccountEntry {slug: DEFAULT_SLUG.to_string(),alias: new_alias,- source_url: source.source_url.clone(),+ source_url,source_label: Some(source.source_label.clone()),captured_at_ms: now,cookie_count: count,@@ -409,6 +438,7 @@ pub fn ingest_to_account(let count = write_account_file(&root, &final_slug, &scoped)?;let now = current_unix_ms();+ let source_url = normalize_source_url(source.source_url.as_deref(), &root);let alias = source.alias_hint.clone().unwrap_or_else(|| {format!("{} · {}",@@ -420,7 +450,7 @@ pub fn ingest_to_account(bucket.accounts.push(AccountEntry {slug: final_slug.clone(),alias,- source_url: source.source_url.clone(),+ source_url,source_label: Some(source.source_label.clone()),captured_at_ms: now,cookie_count: count,@@ -553,4 +583,23 @@ mod tests {assert_eq!(parts[0], "youtube.com");assert_eq!(parts[1], "FALSE");}++ #[test]+ fn normalize_source_url_uses_site_home_for_bilibili_video_url() {+ assert_eq!(+ normalize_source_url(+ Some("https://www.bilibili.com/bangumi/play/ss48239?t=2"),+ "bilibili.com"+ ),+ Some("https://www.bilibili.com/".to_string())+ );+ }++ #[test]+ fn normalize_source_url_falls_back_to_cookie_root() {+ assert_eq!(+ normalize_source_url(Some("not a url"), ".youtube.com"),+ Some("https://youtube.com/".to_string())+ );+ }}diff --git a/src-tauri/src/core/queue.rs b/src-tauri/src/core/queue.rsindex 139e0851..3a909925 100644--- a/src-tauri/src/core/queue.rs+++ b/src-tauri/src/core/queue.rs@@ -12,6 +12,16 @@ pub fn now_ms() -> u64 {.unwrap_or(0)}+fn append_download_log(app: &tauri::AppHandle, id: u64, line: impl AsRef<str>) {+ crate::core::download_log::push_line(id, line.as_ref());+ let _ = app.emit(+ "download-log-update",+ serde_json::json!({+ "id": id,+ }),+ );+}+use serde::Serialize;use tauri::{Emitter, Manager};use tokio::sync::mpsc;@@ -407,8 +417,20 @@ impl DownloadQueue {.collect()}+ pub fn next_available_id(&self, preferred: u64) -> u64 {+ let mut id = preferred;+ while self.items.iter().any(|i| i.id == id) {+ id = id.saturating_add(1);+ }+ id+ }+pub fn mark_active(&mut self, id: u64) {- if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {+ if let Some(item) = self+ .items+ .iter_mut()+ .find(|i| i.id == id && i.status == QueueStatus::Queued)+ {item.status = QueueStatus::Active;item.cancel_token = CancellationToken::new();}@@ -516,8 +538,10 @@ impl DownloadQueue {pub fn pause(&mut self, id: u64) -> bool {if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {if item.status == QueueStatus::Active {- if item.platform != "magnet" {- item.cancel_token.cancel();+ if item.platform != "magnet"+ && !omniget_core::core::ytdlp::pause_download_process(id)+ {+ return false;}item.status = QueueStatus::Paused;item.speed_bytes_per_sec = 0.0;@@ -531,12 +555,12 @@ impl DownloadQueue {pub fn resume(&mut self, id: u64) -> bool {if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {if item.status == QueueStatus::Paused {- if item.platform == "magnet" {- item.status = QueueStatus::Active;- } else {- item.status = QueueStatus::Queued;- item.cancel_token = CancellationToken::new();+ if item.platform != "magnet"+ && !omniget_core::core::ytdlp::resume_download_process(id)+ {+ return false;}+ item.status = QueueStatus::Active;return true;}}@@ -547,8 +571,10 @@ impl DownloadQueue {let mut paused = Vec::new();for item in self.items.iter_mut() {if item.status == QueueStatus::Active {- if item.platform != "magnet" {- item.cancel_token.cancel();+ if item.platform != "magnet"+ && !omniget_core::core::ytdlp::pause_download_process(item.id)+ {+ continue;}item.status = QueueStatus::Paused;item.speed_bytes_per_sec = 0.0;@@ -564,12 +590,12 @@ impl DownloadQueue {for item in self.items.iter_mut() {if item.status == QueueStatus::Paused {let tid = item.torrent_id;- if item.platform == "magnet" {- item.status = QueueStatus::Active;- } else {- item.status = QueueStatus::Queued;- item.cancel_token = CancellationToken::new();+ if item.platform != "magnet"+ && !omniget_core::core::ytdlp::resume_download_process(item.id)+ {+ continue;}+ item.status = QueueStatus::Active;resumed.push((item.id, tid));}}@@ -1189,6 +1215,7 @@ async fn spawn_download_inner(let total_bytes = info.file_size_bytes;let item_title = info.title.clone();+ let log_title = item_title.clone();let item_platform = platform_name.clone();let (tx, mut rx) = mpsc::channel::<omniget_core::models::progress::ProgressUpdate>(32);@@ -1248,13 +1275,41 @@ async fn spawn_download_inner(}let now = std::time::Instant::now();- let clamped = percent.max(0.0);let resolved_total = update.total_bytes.or(total_bytes);- let downloaded_bytes = update.downloaded_bytes.unwrap_or_else(|| {+ let mut clamped = percent.clamp(0.0, 100.0);+ if percent >= 0.0 && percent < 100.0 {+ if clamped < last_percent {+ clamped = last_percent;+ }++ let metric_percent = update.downloaded_bytes.and_then(|downloaded| {+ resolved_total+ .filter(|total| *total > 0)+ .map(|total| (downloaded as f64 / total as f64 * 100.0).clamp(0.0, 100.0))+ });++ if let Some(metric) = metric_percent {+ let metric_ceiling = (metric + 15.0).max(last_percent);+ if clamped > metric_ceiling {+ clamped = metric_ceiling;+ }+ } else {+ let max_step = if update.has_real_metrics() { 12.0 } else { 6.0 };+ let ceiling = (last_percent + max_step).min(99.0);+ if clamped > ceiling {+ clamped = ceiling;+ }+ }+ }++ let mut downloaded_bytes = update.downloaded_bytes.unwrap_or_else(|| {resolved_total.map(|total| (clamped / 100.0 * total as f64) as u64).unwrap_or(last_bytes)});+ if downloaded_bytes < last_bytes && percent < 100.0 {+ downloaded_bytes = last_bytes;+ }if let Some(real) = update.speed_bps {current_speed = real;@@ -1279,7 +1334,8 @@ async fn spawn_download_inner(last_time = now;last_percent = clamped;- let phase = match percent {+ let phase_value = if percent < 0.0 { percent } else { clamped };+ let phase = match phase_value {p if p < -1.5 => "connecting",p if p < -0.5 => "starting",p if p > 99.5 => "finalizing",@@ -1293,9 +1349,8 @@ async fn spawn_download_inner(.or_else(|| {if current_speed > 0.0 {resolved_total.and_then(|total| {- (total > downloaded_bytes).then(|| {- ((total - downloaded_bytes) as f64 / current_speed) as u64- })+ (total > downloaded_bytes)+ .then(|| ((total - downloaded_bytes) as f64 / current_speed) as u64)})} else {None@@ -1342,6 +1397,14 @@ async fn spawn_download_inner(}let dl_start = std::time::Instant::now();+ append_download_log(+ &app,+ item_id,+ format!(+ "[omniget] starting download: platform={} title=\"{}\" url={}",+ platform_name, log_title, url+ ),+ );let dl_future = async {tokio::select! {r = downloader.download(&info, &opts, tx) => r,@@ -1387,6 +1450,15 @@ async fn spawn_download_inner(match result {Ok(dl) => {+ append_download_log(+ &app,+ item_id,+ format!(+ "[omniget] download finished: path={} size={} bytes",+ dl.file_path.to_string_lossy(),+ dl.file_size_bytes+ ),+ );if settings.download.embed_metadata&& platform_name != "magnet"&& ffmpeg::is_ffmpeg_available().await@@ -1452,6 +1524,11 @@ async fn spawn_download_inner(}Err(e) => {let raw_err = e.to_string();+ append_download_log(+ &app,+ item_id,+ format!("[omniget] download failed: {}", raw_err),+ );let (category, hint) = omniget_core::core::errors::classify_download_error(&raw_err);let user_msg = if category != "unknown" {format!("{} ({})", hint, raw_err)diff --git a/src-tauri/src/core/queue_history.rs b/src-tauri/src/core/queue_history.rsindex a9c554f3..94eb72d6 100644--- a/src-tauri/src/core/queue_history.rs+++ b/src-tauri/src/core/queue_history.rs@@ -59,10 +59,7 @@ fn schema(conn: &Connection) -> rusqlite::Result<()> {}fn db_upsert(conn: &Connection, e: &HistoryEntry) -> rusqlite::Result<()> {- let kind = e- .kind- .as_ref()- .and_then(|k| serde_json::to_string(k).ok());+ let kind = e.kind.as_ref().and_then(|k| serde_json::to_string(k).ok());conn.execute("INSERT OR REPLACE INTO history(id, url, platform, title, file_path, file_size_bytes, total_bytes,diff --git a/src-tauri/src/external_url.rs b/src-tauri/src/external_url.rsindex 885dcc45..66ecf3be 100644--- a/src-tauri/src/external_url.rs+++ b/src-tauri/src/external_url.rs@@ -116,7 +116,7 @@ pub async fn queue_url_with_defaults(.map(|p| p.to_string()).unwrap_or_else(|| "generic".to_string());- let download_id = std::time::SystemTime::now()+ let mut download_id = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_millis() as u64;@@ -238,6 +238,7 @@ pub async fn queue_url_with_defaults({let mut q = download_queue.lock().await;+ download_id = q.next_available_id(download_id);q.enqueue(download_id,url.clone(),diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 641c1651..6972e806 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -185,6 +185,16 @@ pub fn run() {.download.include_auto_subtitles});+ core::ytdlp::set_caption_locale_fn(|| {+ storage::config::load_settings_standalone()+ .download+ .caption_locale+ });+ core::ytdlp::set_keep_vtt_fn(|| {+ storage::config::load_settings_standalone()+ .download+ .keep_vtt+ });core::ytdlp::set_translate_metadata_fn(|| {let s = storage::config::load_settings_standalone();if s.download.translate_metadata {@@ -390,32 +400,36 @@ pub fn run() {let plugins_dir = core::paths::app_data_dir().unwrap_or_else(|| std::path::PathBuf::from(".")).join("plugins");- let host = std::sync::Arc::new(plugin_host::PluginHostImpl::new(- app.handle().clone(),- plugins_dir,- ));+ let host: std::sync::Arc<dyn omniget_plugin_sdk::PluginHost> = std::sync::Arc::new(+ plugin_host::PluginHostImpl::new(app.handle().clone(), plugins_dir),+ );let plugin_mgr = app.handle().state::<std::sync::Arc<tokio::sync::RwLock<plugin_loader::PluginManager>>>();-- let mgr_for_default = std::sync::Arc::clone(&*plugin_mgr);+ let mgr_for_plugins = std::sync::Arc::clone(&*plugin_mgr);std::thread::Builder::new()- .name("default-plugins".into())+ .name("plugins-bootstrap".into()).spawn(move || {+ {+ let mut mgr = mgr_for_plugins.blocking_write();+ mgr.load_all(std::sync::Arc::clone(&host));+ }+let rt = match tokio::runtime::Runtime::new() {Ok(rt) => rt,Err(e) => {- tracing::warn!("default-plugins runtime failed: {}", e);+ tracing::warn!("plugins-bootstrap runtime failed: {}", e);return;}};- rt.block_on(commands::plugins::ensure_default_plugins(mgr_for_default));- })- .ok()- .map(|h| h.join().ok());+ rt.block_on(commands::plugins::ensure_default_plugins(+ std::sync::Arc::clone(&mgr_for_plugins),+ ));- let mut mgr = plugin_mgr.blocking_write();- mgr.load_all(host);+ let mut mgr = mgr_for_plugins.blocking_write();+ mgr.load_all(host);+ })+ .ok();}std::thread::Builder::new()@@ -484,6 +498,7 @@ pub fn run() {cookies::commands::cookies_read,cookies::commands::cookies_import,cookies::commands::cookies_clear,+ cookies::commands::cookies_clear_batch,cookies::commands::cookies_rename,cookies::commands::cookies_accounts_for_url,cookies::commands::cookies_read_as_json,diff --git a/src-tauri/src/platforms/bilibili/api.rs b/src-tauri/src/platforms/bilibili/api.rsindex 07d7569a..3fd21fc1 100644--- a/src-tauri/src/platforms/bilibili/api.rs+++ b/src-tauri/src/platforms/bilibili/api.rs@@ -98,7 +98,9 @@ impl ApiClient {pub fn with_account(mut self, slug: impl Into<String>) -> Self {let slug = slug.into();self.cookie_header = build_cookie_header_for_account(&slug);- self.account_slug = Some(slug);+ if self.cookie_header.is_some() {+ self.account_slug = Some(slug);+ }self}@@ -170,10 +172,7 @@ impl ApiClient {last_err = Some(BilibiliError::Network(e));}}- tokio::time::sleep(Duration::from_millis(- RETRY_BACKOFF_MS * 2u64.pow(attempt),- ))- .await;+ tokio::time::sleep(Duration::from_millis(RETRY_BACKOFF_MS * 2u64.pow(attempt))).await;}Err(last_err.unwrap_or(BilibiliError::ContentUnavailable))}@@ -306,13 +305,24 @@ pub fn parse_data<T: DeserializeOwned>(value: &Value) -> Result<T> {fn build_cookie_header_for_account(slug: &str) -> Option<String> {let path = crate::cookies::account_path_for_consumer("bilibili.com", Some(slug))?;let content = std::fs::read_to_string(&path).ok()?;+ cookie_header_from_netscape(&content)+}++fn cookie_header_from_netscape(content: &str) -> Option<String> {let mut pairs: Vec<String> = Vec::new();- for line in content.lines() {- let line = line.trim();- if line.is_empty() || line.starts_with('#') {+ for raw in content.lines() {+ let line = raw.trim_end();+ if line.is_empty() {continue;}- let mut parts = line.split('\t');+ let effective = if let Some(rest) = line.strip_prefix("#HttpOnly_") {+ rest+ } else if line.starts_with('#') {+ continue;+ } else {+ line+ };+ let mut parts = effective.split('\t');let _domain = parts.next();let _include = parts.next();let _path = parts.next();@@ -330,3 +340,26 @@ fn build_cookie_header_for_account(slug: &str) -> Option<String> {Some(pairs.join("; "))}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn cookie_header_keeps_httponly_netscape_cookies() {+ let raw = "# Netscape HTTP Cookie File\n#HttpOnly_.bilibili.com\tTRUE\t/\tTRUE\t1830000000\tSESSDATA\tabc123\n.bilibili.com\tTRUE\t/\tTRUE\t1830000000\tbili_jct\tcsrf\n";+ let header = cookie_header_from_netscape(raw).unwrap();++ assert!(header.contains("SESSDATA=abc123"));+ assert!(header.contains("bili_jct=csrf"));+ assert!(!header.contains("#HttpOnly_"));+ }++ #[test]+ fn cookie_header_skips_regular_comments() {+ let raw = "# comment\n.bilibili.com\tTRUE\t/\tTRUE\t1830000000\tDedeUserID\t42\n";+ let header = cookie_header_from_netscape(raw).unwrap();++ assert_eq!(header, "DedeUserID=42");+ }+}diff --git a/src-tauri/src/platforms/bilibili/auth/mod.rs b/src-tauri/src/platforms/bilibili/auth/mod.rsindex cac45d05..0f5fcbe3 100644--- a/src-tauri/src/platforms/bilibili/auth/mod.rs+++ b/src-tauri/src/platforms/bilibili/auth/mod.rs@@ -28,7 +28,10 @@ pub async fn fetch_account_info(client: &ApiClient) -> Result<AccountInfo> {Some(&raw)}.ok_or(BilibiliError::ContentUnavailable)?;- let is_login = data.get("isLogin").and_then(Value::as_bool).unwrap_or(false);+ let is_login = data+ .get("isLogin")+ .and_then(Value::as_bool)+ .unwrap_or(false);if !is_login {return Err(BilibiliError::NotLoggedIn);}@@ -38,14 +41,8 @@ pub async fn fetch_account_info(client: &ApiClient) -> Result<AccountInfo> {.unwrap_or("").to_string();let mid = data.get("mid").and_then(Value::as_u64).unwrap_or(0);- let face = data- .get("face")- .and_then(Value::as_str)- .map(String::from);- let vip_status = data- .get("vipStatus")- .and_then(Value::as_u64)- .unwrap_or(0);+ let face = data.get("face").and_then(Value::as_str).map(String::from);+ let vip_status = data.get("vipStatus").and_then(Value::as_u64).unwrap_or(0);let vip_due_ms = data.get("vip_due_date").or_else(|| data.get("vipDueDate"))@@ -134,17 +131,15 @@ pub fn persist_account(existing.source_label = Some(source_label.to_string());existing.alias = alias;} else {- bucket- .accounts- .push(crate::cookies::storage::AccountEntry {- slug: slug.clone(),- alias,- source_url: Some("https://www.bilibili.com".to_string()),- source_label: Some(source_label.to_string()),- captured_at_ms: now_ms,- cookie_count: entries.len(),- last_used_at_ms: Some(now_ms),- });+ bucket.accounts.push(crate::cookies::storage::AccountEntry {+ slug: slug.clone(),+ alias,+ source_url: Some("https://www.bilibili.com".to_string()),+ source_label: Some(source_label.to_string()),+ captured_at_ms: now_ms,+ cookie_count: entries.len(),+ last_used_at_ms: Some(now_ms),+ });}crate::cookies::storage::save_registry(®istry).map_err(|e| e.to_string())?;diff --git a/src-tauri/src/platforms/bilibili/auth/qr.rs b/src-tauri/src/platforms/bilibili/auth/qr.rsindex a2a89eeb..e9f74d51 100644--- a/src-tauri/src/platforms/bilibili/auth/qr.rs+++ b/src-tauri/src/platforms/bilibili/auth/qr.rs@@ -52,7 +52,11 @@ pub async fn generate(client: &ApiClient) -> Result<QrSession> {}pub async fn poll(client: &ApiClient, qrcode_key: &str) -> Result<QrPollStatus> {- let url = format!("{}?qrcode_key={}", QR_POLL_URL, urlencoding::encode(qrcode_key));+ let url = format!(+ "{}?qrcode_key={}",+ QR_POLL_URL,+ urlencoding::encode(qrcode_key)+ );let raw = client.get_json(&url).await?;let data = check_api_response(&raw)?;let code = data.get("code").and_then(Value::as_i64).unwrap_or(-1);@@ -83,10 +87,7 @@ pub async fn poll(client: &ApiClient, qrcode_key: &str) -> Result<QrPollStatus>}}-async fn finalize(- base_client: &ApiClient,- cookies: Vec<(String, String)>,-) -> Result<QrPollStatus> {+async fn finalize(base_client: &ApiClient, cookies: Vec<(String, String)>) -> Result<QrPollStatus> {let cookie_header = cookies.iter().map(|(k, v)| format!("{}={}", k, v))diff --git a/src-tauri/src/platforms/bilibili/auth/sms.rs b/src-tauri/src/platforms/bilibili/auth/sms.rsindex 07cac076..c8620b17 100644--- a/src-tauri/src/platforms/bilibili/auth/sms.rs+++ b/src-tauri/src/platforms/bilibili/auth/sms.rs@@ -115,7 +115,11 @@ pub async fn verify(client: &ApiClient, input: SmsVerifyInput) -> Result<SmsVerifn extract_cookies(data: &Value) -> Vec<(String, String)> {let mut out: Vec<(String, String)> = Vec::new();- if let Some(arr) = data.get("cookie_info").and_then(|v| v.get("cookies")).and_then(Value::as_array) {+ if let Some(arr) = data+ .get("cookie_info")+ .and_then(|v| v.get("cookies"))+ .and_then(Value::as_array)+ {for c in arr {if let (Some(name), Some(value)) = (c.get("name").and_then(Value::as_str),diff --git a/src-tauri/src/platforms/bilibili/cdn.rs b/src-tauri/src/platforms/bilibili/cdn.rsindex 51e0ef24..7726f95d 100644--- a/src-tauri/src/platforms/bilibili/cdn.rs+++ b/src-tauri/src/platforms/bilibili/cdn.rs@@ -23,7 +23,10 @@ pub fn filter_blocked(urls: &[String]) -> Vec<String> {}pub fn host_is_blocked(url: &str) -> bool {- let host = match url::Url::parse(url).ok().and_then(|u| u.host_str().map(String::from)) {+ let host = match url::Url::parse(url)+ .ok()+ .and_then(|u| u.host_str().map(String::from))+ {Some(h) => h.to_lowercase(),None => return false,};@@ -36,7 +39,10 @@ pub fn replace_host(url: &str, new_host: &str) -> Option<String> {let parsed = url::Url::parse(url).ok()?;let scheme = parsed.scheme();let path = parsed.path();- let query = parsed.query().map(|q| format!("?{}", q)).unwrap_or_default();+ let query = parsed+ .query()+ .map(|q| format!("?{}", q))+ .unwrap_or_default();Some(format!("{}://{}{}{}", scheme, new_host, path, query))}diff --git a/src-tauri/src/platforms/bilibili/cookie.rs b/src-tauri/src/platforms/bilibili/cookie.rsindex 409abb21..63cdc0cc 100644--- a/src-tauri/src/platforms/bilibili/cookie.rs+++ b/src-tauri/src/platforms/bilibili/cookie.rs@@ -1,16 +1,17 @@use std::io::Cursor;use std::time::{SystemTime, UNIX_EPOCH};+use hmac::{Hmac, Mac};use rand::RngExt;use serde::{Deserialize, Serialize};use serde_json::Value;use sha2::Sha256;-use hmac::{Hmac, Mac};use super::api::{check_api_response, ApiClient, Result};const FINGER_SPI_URL: &str = "https://api.bilibili.com/x/frontend/finger/spi";-const GEN_TICKET_URL: &str = "https://api.bilibili.com/bapis/bilibili.api.ticket.v1.Ticket/GenWebTicket";+const GEN_TICKET_URL: &str =+ "https://api.bilibili.com/bapis/bilibili.api.ticket.v1.Ticket/GenWebTicket";const EXCLIMB_URL: &str = "https://api.bilibili.com/x/internal/gaia-gateway/ExClimbWuzhi";const ANONYMOUS_SLUG: &str = "_anonymous";const HMAC_KEY: &[u8] = b"XgwSnGZ1p";@@ -42,7 +43,11 @@ impl AnonymousCookieState {pub fn meta_file_path() -> Option<std::path::PathBuf> {let root = crate::core::paths::app_data_dir()?;- Some(root.join("cookies").join("bilibili.com").join("_anonymous_meta.json"))+ Some(+ root.join("cookies")+ .join("bilibili.com")+ .join("_anonymous_meta.json"),+ )}pub fn load_state() -> AnonymousCookieState {@@ -64,9 +69,8 @@ pub fn save_state(state: &AnonymousCookieState) -> std::io::Result<()> {if let Some(parent) = path.parent() {std::fs::create_dir_all(parent)?;}- let serialized = serde_json::to_string_pretty(state).map_err(|e| {- std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string())- })?;+ let serialized = serde_json::to_string_pretty(state)+ .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))?;std::fs::write(path, serialized)}@@ -184,10 +188,7 @@ pub fn build_cookie_header(state: &AnonymousCookieState) -> String {}if !state.bili_ticket.is_empty() {pairs.push(format!("bili_ticket={}", state.bili_ticket));- pairs.push(format!(- "bili_ticket_expires={}",- state.bili_ticket_expires- ));+ pairs.push(format!("bili_ticket_expires={}", state.bili_ticket_expires));}pairs.push("CURRENT_FNVAL=4048".to_string());pairs.push("CURRENT_QUALITY=0".to_string());@@ -224,10 +225,7 @@ fn write_netscape_for_anonymous(state: &AnonymousCookieState) -> std::io::Result("buvid3", state.buvid3.clone()),("buvid4", state.buvid4.clone()),("bili_ticket", state.bili_ticket.clone()),- (- "bili_ticket_expires",- state.bili_ticket_expires.to_string(),- ),+ ("bili_ticket_expires", state.bili_ticket_expires.to_string()),("CURRENT_FNVAL", "4048".to_string()),("CURRENT_QUALITY", "0".to_string()),];diff --git a/src-tauri/src/platforms/bilibili/danmaku/ass/render.rs b/src-tauri/src/platforms/bilibili/danmaku/ass/render.rsindex 70f87a70..7ea17a41 100644--- a/src-tauri/src/platforms/bilibili/danmaku/ass/render.rs+++ b/src-tauri/src/platforms/bilibili/danmaku/ass/render.rs@@ -105,7 +105,9 @@ pub fn render_ass(elems: &[DanmakuElem], opts: &AssRenderOptions) -> String {));out.push_str("[Events]\n");- out.push_str("Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n");+ out.push_str(+ "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n",+ );for ev in events {out.push_str(&ev);out.push('\n');diff --git a/src-tauri/src/platforms/bilibili/danmaku/mod.rs b/src-tauri/src/platforms/bilibili/danmaku/mod.rsindex e76e592d..8857a76f 100644--- a/src-tauri/src/platforms/bilibili/danmaku/mod.rs+++ b/src-tauri/src/platforms/bilibili/danmaku/mod.rs@@ -31,7 +31,11 @@ impl DanmakuFormat {}}-pub async fn fetch_elems(client: &ApiClient, cid: u64, duration_secs: u64) -> Result<Vec<DanmakuElem>> {+pub async fn fetch_elems(+ client: &ApiClient,+ cid: u64,+ duration_secs: u64,+) -> Result<Vec<DanmakuElem>> {let segments = ((duration_secs + SEGMENT_DURATION_SECS - 1) / SEGMENT_DURATION_SECS).max(1);let mut all: Vec<DanmakuElem> = Vec::new();for i in 1..=segments {diff --git a/src-tauri/src/platforms/bilibili/danmaku/proto.rs b/src-tauri/src/platforms/bilibili/danmaku/proto.rsindex 5101ad29..167e5d7e 100644--- a/src-tauri/src/platforms/bilibili/danmaku/proto.rs+++ b/src-tauri/src/platforms/bilibili/danmaku/proto.rs@@ -24,8 +24,7 @@ pub fn decode_segment(bytes: &[u8]) -> Result<Vec<DanmakuElem>> {let field = (key >> 3) as u32;let wire = (key & 0x07) as u8;if field == 1 && wire == 2 {- let (len, l_len) =- read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;+ let (len, l_len) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;idx += l_len;let end = idx.checked_add(len as usize)@@ -78,14 +77,14 @@ fn decode_elem(bytes: &[u8]) -> Result<DanmakuElem> {elem.color = v as u32;}(6, 2) => {- let (v, vl) = read_length_delimited(bytes, idx)- .ok_or(BilibiliError::ContentUnavailable)?;+ let (v, vl) =+ read_length_delimited(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;idx += vl;elem.mid_hash = String::from_utf8(v.to_vec()).unwrap_or_default();}(7, 2) => {- let (v, vl) = read_length_delimited(bytes, idx)- .ok_or(BilibiliError::ContentUnavailable)?;+ let (v, vl) =+ read_length_delimited(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;idx += vl;elem.content = String::from_utf8(v.to_vec()).unwrap_or_default();}diff --git a/src-tauri/src/platforms/bilibili/engine/fetch.rs b/src-tauri/src/platforms/bilibili/engine/fetch.rsindex 4a73dba2..fac59857 100644--- a/src-tauri/src/platforms/bilibili/engine/fetch.rs+++ b/src-tauri/src/platforms/bilibili/engine/fetch.rs@@ -26,11 +26,7 @@ fn build_client() -> Result<reqwest::Client> {.map_err(BilibiliError::Network)}-fn build_headers(- referer: &str,- user_agent: &str,- cookie_header: Option<&str>,-) -> HeaderMap {+fn build_headers(referer: &str, user_agent: &str, cookie_header: Option<&str>) -> HeaderMap {let mut h = HeaderMap::new();if let Ok(v) = HeaderValue::from_str(referer) {h.insert(REFERER, v);@@ -58,24 +54,21 @@ pub async fn fetch_stream() -> Result<HttpFetcherResult> {let client = build_client()?;let headers = build_headers(opts.referer, opts.user_agent, opts.cookie_header);- let mut fetcher = HttpFetcher::new(- client,- opts.url.to_string(),- opts.output_path.to_path_buf(),- )- .with_headers(headers)- .with_config(HttpFetcherConfig {- concurrent_segments: 8,- segment_size_hint: 4 * 1024 * 1024,- min_size_for_chunked: 8 * 1024 * 1024,- connect_timeout: Duration::from_secs(10),- read_timeout: Duration::from_secs(45),- max_retries_per_segment: 3,- steal_threshold: Duration::from_secs(3),- steal_min_chunk_size: 512 * 1024,- use_sidecar_resume: true,- resume_save_interval: Duration::from_secs(2),- });+ let mut fetcher =+ HttpFetcher::new(client, opts.url.to_string(), opts.output_path.to_path_buf())+ .with_headers(headers)+ .with_config(HttpFetcherConfig {+ concurrent_segments: 8,+ segment_size_hint: 4 * 1024 * 1024,+ min_size_for_chunked: 8 * 1024 * 1024,+ connect_timeout: Duration::from_secs(10),+ read_timeout: Duration::from_secs(45),+ max_retries_per_segment: 3,+ steal_threshold: Duration::from_secs(3),+ steal_min_chunk_size: 512 * 1024,+ use_sidecar_resume: true,+ resume_save_interval: Duration::from_secs(2),+ });if let Some(c) = opts.cancel {fetcher = fetcher.with_cancel(c);}diff --git a/src-tauri/src/platforms/bilibili/engine/mod.rs b/src-tauri/src/platforms/bilibili/engine/mod.rsindex 82e8510d..93633437 100644--- a/src-tauri/src/platforms/bilibili/engine/mod.rs+++ b/src-tauri/src/platforms/bilibili/engine/mod.rs@@ -62,13 +62,9 @@ pub async fn run_single(alt_hosts: opts.cdn_alt_hosts.clone(),prefer_alternatives: opts.cdn_prefer_alternatives,};- let video_url = query::resolve_best_url_with_cdn(- client,- &video.base_url,- &video.backup_urls,- &cdn_prefs,- )- .await?;+ let video_url =+ query::resolve_best_url_with_cdn(client, &video.base_url, &video.backup_urls, &cdn_prefs)+ .await?;let audio_resolved = if let Some(a) = audio {Some(query::resolve_best_url_with_cdn(client, &a.base_url, &a.backup_urls, &cdn_prefs)@@ -81,15 +77,9 @@ pub async fn run_single(std::fs::create_dir_all(&opts.output_dir).ok();let temp_stem = sanitize_for_temp(&opts.filename);- let temp_video = opts- .output_dir- .join(format!(".{}.video.tmp", temp_stem));- let temp_audio = opts- .output_dir- .join(format!(".{}.audio.tmp", temp_stem));- let temp_cover = opts- .output_dir- .join(format!(".{}.cover.tmp", temp_stem));+ let temp_video = opts.output_dir.join(format!(".{}.video.tmp", temp_stem));+ let temp_audio = opts.output_dir.join(format!(".{}.audio.tmp", temp_stem));+ let temp_cover = opts.output_dir.join(format!(".{}.cover.tmp", temp_stem));let (ua, cookie_header) = (client.user_agent().to_string(),@@ -190,10 +180,7 @@ pub async fn run_single(.await.map_err(|_| BilibiliError::ContentUnavailable)??;let audio_result = match audio_handle {- Some(h) => Some(- h.await- .map_err(|_| BilibiliError::ContentUnavailable)??,- ),+ Some(h) => Some(h.await.map_err(|_| BilibiliError::ContentUnavailable)??),None => None,};@@ -214,9 +201,9 @@ pub async fn run_single(let _ = progress.send(ProgressUpdate::percent(95.0)).await;- let final_path = opts- .output_dir- .join(format!("{}.{}", opts.filename, opts.container.extension()));+ let final_path =+ opts.output_dir+ .join(format!("{}.{}", opts.filename, opts.container.extension()));if let Some(parent) = final_path.parent() {std::fs::create_dir_all(parent).ok();}@@ -231,8 +218,7 @@ pub async fn run_single(}).await?;} else {- std::fs::rename(&temp_video, &final_path)- .map_err(|_| BilibiliError::ContentUnavailable)?;+ std::fs::rename(&temp_video, &final_path).map_err(|_| BilibiliError::ContentUnavailable)?;}if !opts.keep_streams {@@ -251,7 +237,11 @@ pub async fn run_single(if opts.danmaku_enabled {let cid = item.cid;let duration = item.duration_seconds.unwrap_or(0.0).max(0.0) as u64;- if let (Some(cid_v), format) = (cid, opts.danmaku_format.unwrap_or(super::danmaku::DanmakuFormat::Xml)) {+ if let (Some(cid_v), format) = (+ cid,+ opts.danmaku_format+ .unwrap_or(super::danmaku::DanmakuFormat::Xml),+ ) {if duration > 0 {match super::danmaku::fetch_elems(client, cid_v, duration).await {Ok(elems) => {@@ -381,16 +371,12 @@ async fn run_progressive(alt_hosts: opts.cdn_alt_hosts.clone(),prefer_alternatives: opts.cdn_prefer_alternatives,};- let resolved = query::resolve_best_url_with_cdn(- client,- &stream.base_url,- &stream.backup_urls,- &cdn_prefs,- )- .await?;- let final_path = opts- .output_dir- .join(format!("{}.{}", opts.filename, opts.container.extension()));+ let resolved =+ query::resolve_best_url_with_cdn(client, &stream.base_url, &stream.backup_urls, &cdn_prefs)+ .await?;+ let final_path =+ opts.output_dir+ .join(format!("{}.{}", opts.filename, opts.container.extension()));let referer = item.url.clone()diff --git a/src-tauri/src/platforms/bilibili/legacy.rs b/src-tauri/src/platforms/bilibili/legacy.rsindex 257c201d..4a3bcd38 100644--- a/src-tauri/src/platforms/bilibili/legacy.rs+++ b/src-tauri/src/platforms/bilibili/legacy.rs@@ -15,9 +15,7 @@ pub fn is_playlist_or_series(url: &str) -> bool {if path.starts_with("/bangumi/") || path.starts_with("/cheese/") {return true;}- if path.contains("/channel/")- || path.contains("/favlist/")- || path.contains("/medialist/")+ if path.contains("/channel/") || path.contains("/favlist/") || path.contains("/medialist/"){return true;}diff --git a/src-tauri/src/platforms/bilibili/mod.rs b/src-tauri/src/platforms/bilibili/mod.rsindex 3597154c..e15a243f 100644--- a/src-tauri/src/platforms/bilibili/mod.rs+++ b/src-tauri/src/platforms/bilibili/mod.rs@@ -48,16 +48,27 @@ pub fn has_active_account() -> bool {bucket.accounts.iter()- .any(|a| !a.slug.starts_with('_') && a.cookie_count > 0)+ .any(|a| a.slug != "_anonymous" && a.cookie_count > 0)}fn active_account_slug() -> Option<String> {let registry = crate::cookies::load_registry();let bucket = registry.buckets.get("bilibili.com")?;++ if let Some(selected) = omniget_core::core::log_hook::current_cookie_slug() {+ if bucket+ .accounts+ .iter()+ .any(|a| a.slug == selected && a.slug != "_anonymous" && a.cookie_count > 0)+ {+ return Some(selected);+ }+ }+bucket.accounts.iter()- .filter(|a| !a.slug.starts_with('_') && a.cookie_count > 0)+ .filter(|a| a.slug != "_anonymous" && a.cookie_count > 0).max_by_key(|a| a.last_used_at_ms.unwrap_or(a.captured_at_ms)).map(|a| a.slug.clone())}@@ -105,11 +116,7 @@ async fn api_engine_download(cheese: settings.download.bilibili_naming_cheese.clone(),collection: settings.download.bilibili_naming_collection.clone(),};- let first_item_owned = parsed- .items- .first()- .cloned()- .unwrap_or_default();+ let first_item_owned = parsed.items.first().cloned().unwrap_or_default();let naming_kind = naming::classify(&kind, &first_item_owned);let naming_inputs = naming::NamingInputs {item: &first_item_owned,@@ -174,8 +181,8 @@ fn build_api_client(slug: Option<&str>,user_agent: Option<&str>,) -> anyhow::Result<api::ApiClient> {- let mut client = api::ApiClient::new()- .map_err(|e| anyhow!("api client init failed: {}", e.i18n_key()))?;+ let mut client =+ api::ApiClient::new().map_err(|e| anyhow!("api client init failed: {}", e.i18n_key()))?;if let Some(ua) = user_agent.filter(|s| !s.is_empty()) {client = client.with_user_agent(ua);}diff --git a/src-tauri/src/platforms/bilibili/nfo.rs b/src-tauri/src/platforms/bilibili/nfo.rsindex 72f909e8..a3189a78 100644--- a/src-tauri/src/platforms/bilibili/nfo.rs+++ b/src-tauri/src/platforms/bilibili/nfo.rs@@ -28,9 +28,7 @@ pub fn classify(kind: &UrlKind) -> Option<NfoKind> {pub fn season_uses_tvshow(kind: &UrlKind) -> bool {matches!(kind,- UrlKind::BangumiSeason { .. }- | UrlKind::BangumiMedia { .. }- | UrlKind::CheeseSeason { .. }+ UrlKind::BangumiSeason { .. } | UrlKind::BangumiMedia { .. } | UrlKind::CheeseSeason { .. })}@@ -75,7 +73,11 @@ fn render_movie(item: &EpisodeItem, metadata: &ContentMetadata, tags: &[String])write_tag(&mut buf, "plot", plot);}if let Some(d) = item.duration_seconds {- write_tag(&mut buf, "runtime", &format!("{}", (d / 60.0).round() as i64));+ write_tag(+ &mut buf,+ "runtime",+ &format!("{}", (d / 60.0).round() as i64),+ );}if let Some((year, ymd)) = parse_date(item.pub_time_secs.or(metadata.premiered_secs)) {write_tag(&mut buf, "premiered", &ymd);@@ -90,7 +92,10 @@ fn render_movie(item: &EpisodeItem, metadata: &ContentMetadata, tags: &[String])write_tag(&mut buf, "genre", tag);}if let Some(b) = item.bvid.as_deref() {- buf.push_str(&format!(" <uniqueid type=\"bilibili\">{}</uniqueid>\n", escape(b)));+ buf.push_str(&format!(+ " <uniqueid type=\"bilibili\">{}</uniqueid>\n",+ escape(b)+ ));}buf.push_str("</movie>\n");buf@@ -119,7 +124,11 @@ fn render_tvshow(metadata: &ContentMetadata) -> String {write_tag(&mut buf, "director", uname);}if let Some(actors) = metadata.actors.as_deref() {- for actor in actors.split(['\n', ',', '/', '、']).map(|s| s.trim()).filter(|s| !s.is_empty()) {+ for actor in actors+ .split(['\n', ',', '/', '、'])+ .map(|s| s.trim())+ .filter(|s| !s.is_empty())+ {buf.push_str(" <actor>\n");write_tag_indented(&mut buf, " ", "name", actor);buf.push_str(" </actor>\n");@@ -135,10 +144,16 @@ fn render_tvshow(metadata: &ContentMetadata) -> String {write_tag(&mut buf, "country", area);}if let Some(sid) = metadata.season_id {- buf.push_str(&format!(" <uniqueid type=\"bilibili-ss\">{}</uniqueid>\n", sid));+ buf.push_str(&format!(+ " <uniqueid type=\"bilibili-ss\">{}</uniqueid>\n",+ sid+ ));}if let Some(mid) = metadata.media_id {- buf.push_str(&format!(" <uniqueid type=\"bilibili-md\">{}</uniqueid>\n", mid));+ buf.push_str(&format!(+ " <uniqueid type=\"bilibili-md\">{}</uniqueid>\n",+ mid+ ));}buf.push_str("</tvshow>\n");buf@@ -153,7 +168,11 @@ fn render_episode(item: &EpisodeItem, metadata: &ContentMetadata) -> String {write_tag(&mut buf, "plot", plot);}if let Some(d) = item.duration_seconds {- write_tag(&mut buf, "runtime", &format!("{}", (d / 60.0).round() as i64));+ write_tag(+ &mut buf,+ "runtime",+ &format!("{}", (d / 60.0).round() as i64),+ );}if let Some((year, ymd)) = parse_date(item.pub_time_secs.or(metadata.premiered_secs)) {write_tag(&mut buf, "premiered", &ymd);@@ -176,7 +195,10 @@ fn render_episode(item: &EpisodeItem, metadata: &ContentMetadata) -> String {write_tag(&mut buf, "country", area);}if let Some(ep_id) = item.ep_id {- buf.push_str(&format!(" <uniqueid type=\"bilibili-ep\">{}</uniqueid>\n", ep_id));+ buf.push_str(&format!(+ " <uniqueid type=\"bilibili-ep\">{}</uniqueid>\n",+ ep_id+ ));}buf.push_str("</episodedetails>\n");buf@@ -187,7 +209,13 @@ fn write_tag(buf: &mut String, name: &str, value: &str) {}fn write_tag_indented(buf: &mut String, indent: &str, name: &str, value: &str) {- buf.push_str(&format!("{}<{}>{}</{}>\n", indent, name, escape(value), name));+ buf.push_str(&format!(+ "{}<{}>{}</{}>\n",+ indent,+ name,+ escape(value),+ name+ ));}fn escape(s: &str) -> String {diff --git a/src-tauri/src/platforms/bilibili/parser/bangumi.rs b/src-tauri/src/platforms/bilibili/parser/bangumi.rsindex b26a31c5..bc997f52 100644--- a/src-tauri/src/platforms/bilibili/parser/bangumi.rs+++ b/src-tauri/src/platforms/bilibili/parser/bangumi.rs@@ -147,10 +147,7 @@ fn build_parsed_content(result: &Value, highlight_ep: Option<u64>) -> Result<Par}if let Some(secs) = result.get("section").and_then(Value::as_array) {for sec in secs {- let section_title = sec- .get("title")- .and_then(Value::as_str)- .map(String::from);+ let section_title = sec.get("title").and_then(Value::as_str).map(String::from);let is_preview = section_title.as_deref().map(|t| t.contains("预告") || t.contains("PV"))@@ -187,7 +184,10 @@ fn build_episode_item(let bvid = ep.get("bvid").and_then(Value::as_str)?;let cid = ep.get("cid").and_then(Value::as_u64);let aid = ep.get("aid").and_then(Value::as_u64);- let ep_id = ep.get("id").and_then(Value::as_u64).or_else(|| ep.get("ep_id").and_then(Value::as_u64));+ let ep_id = ep+ .get("id")+ .and_then(Value::as_u64)+ .or_else(|| ep.get("ep_id").and_then(Value::as_u64));let title = ep.get("long_title").and_then(Value::as_str)@@ -198,14 +198,10 @@ fn build_episode_item(.to_string();let duration_ms = ep.get("duration").and_then(Value::as_f64);let duration_seconds = duration_ms.map(|ms| ms / 1000.0);- let cover = ep- .get("cover")- .and_then(Value::as_str)- .map(String::from);+ let cover = ep.get("cover").and_then(Value::as_str).map(String::from);let pub_time = ep.get("pub_time").and_then(Value::as_u64);let badge_raw = ep.get("badge").and_then(Value::as_str).unwrap_or("");- let is_preview =- is_preview_section || badge_raw.contains("预告") || badge_raw.contains("PV");+ let is_preview = is_preview_section || badge_raw.contains("预告") || badge_raw.contains("PV");let badge = if is_preview {Some("badge.bilibili.preview".to_string())} else if badge_raw.contains("充电") {diff --git a/src-tauri/src/platforms/bilibili/parser/cheese.rs b/src-tauri/src/platforms/bilibili/parser/cheese.rsindex 4d827374..9510f34e 100644--- a/src-tauri/src/platforms/bilibili/parser/cheese.rs+++ b/src-tauri/src/platforms/bilibili/parser/cheese.rs@@ -25,10 +25,7 @@ fn build_parsed_content(data: &Value) -> Result<ParsedContent> {.and_then(Value::as_str).unwrap_or("Bilibili Course").to_string();- let cover = data- .get("cover")- .and_then(Value::as_str)- .map(String::from);+ let cover = data.get("cover").and_then(Value::as_str).map(String::from);let description = data.get("subtitle").and_then(Value::as_str)@@ -54,10 +51,7 @@ fn build_parsed_content(data: &Value) -> Result<ParsedContent> {let mut first_release: Option<u64> = None;if let Some(secs) = data.get("sections").and_then(Value::as_array) {for sec in secs {- let section_title = sec- .get("title")- .and_then(Value::as_str)- .map(String::from);+ let section_title = sec.get("title").and_then(Value::as_str).map(String::from);if let Some(eps) = sec.get("episodes").and_then(Value::as_array) {for ep in eps {let aid = ep.get("aid").and_then(Value::as_u64);@@ -72,10 +66,7 @@ fn build_parsed_content(data: &Value) -> Result<ParsedContent> {.unwrap_or("").to_string();let dur = ep.get("duration").and_then(Value::as_f64);- let cover_ep = ep- .get("cover")- .and_then(Value::as_str)- .map(String::from);+ let cover_ep = ep.get("cover").and_then(Value::as_str).map(String::from);let release = ep.get("release_date").and_then(Value::as_u64);if first_release.is_none() && release.is_some() {first_release = release;@@ -100,9 +91,8 @@ fn build_parsed_content(data: &Value) -> Result<ParsedContent> {episode_number: Some(counter),section_title: section_title.clone(),badge,- url: ep_id.map(|id| {- format!("https://www.bilibili.com/cheese/play/ep{}", id)- }),+ url: ep_id+ .map(|id| format!("https://www.bilibili.com/cheese/play/ep{}", id)),..EpisodeItem::default()});}diff --git a/src-tauri/src/platforms/bilibili/parser/favlist.rs b/src-tauri/src/platforms/bilibili/parser/favlist.rsindex 16a89ddc..195745c9 100644--- a/src-tauri/src/platforms/bilibili/parser/favlist.rs+++ b/src-tauri/src/platforms/bilibili/parser/favlist.rs@@ -60,10 +60,7 @@ pub async fn parse(client: &ApiClient, fid: u64, page: u32) -> Result<ParsedCont.unwrap_or("").to_string();let duration = m.get("duration").and_then(Value::as_f64);- let cover = m- .get("cover")- .and_then(Value::as_str)- .map(String::from);+ let cover = m.get("cover").and_then(Value::as_str).map(String::from);let pub_time = m.get("pubtime").and_then(Value::as_u64);let fav_time = m.get("fav_time").and_then(Value::as_u64);let is_ogv = m.get("ogv").is_some() && !m.get("ogv").unwrap_or(&Value::Null).is_null();@@ -86,7 +83,10 @@ pub async fn parse(client: &ApiClient, fid: u64, page: u32) -> Result<ParsedContpub_time_secs: fav_time.or(pub_time),badge,url: Some(if is_ogv {- format!("https://www.bilibili.com/bangumi/play/ep{}", ep_id.unwrap_or(0))+ format!(+ "https://www.bilibili.com/bangumi/play/ep{}",+ ep_id.unwrap_or(0)+ )} else {format!("https://www.bilibili.com/video/{}", bvid)}),diff --git a/src-tauri/src/platforms/bilibili/parser/history.rs b/src-tauri/src/platforms/bilibili/parser/history.rsindex e5446c96..affb1e73 100644--- a/src-tauri/src/platforms/bilibili/parser/history.rs+++ b/src-tauri/src/platforms/bilibili/parser/history.rs@@ -43,9 +43,7 @@ pub async fn parse(client: &ApiClient, page: u32) -> Result<ParsedContent> {.and_then(Value::as_str).unwrap_or("").to_string();- let cid = history- .and_then(|h| h.get("cid"))- .and_then(Value::as_u64);+ let cid = history.and_then(|h| h.get("cid")).and_then(Value::as_u64);if bvid.is_empty() && business == "archive" {continue;}@@ -75,15 +73,15 @@ pub async fn parse(client: &ApiClient, page: u32) -> Result<ParsedContent> {};let ep_id = history.and_then(|h| h.get("epid").and_then(Value::as_u64))- .or_else(|| {- history- .and_then(|h| h.get("ep_id"))- .and_then(Value::as_u64)- });+ .or_else(|| history.and_then(|h| h.get("ep_id")).and_then(Value::as_u64));items.push(EpisodeItem {episode_id: format!("history:{}:{}", business, bvid),title: composed_title,- bvid: if bvid.is_empty() { None } else { Some(bvid.clone()) },+ bvid: if bvid.is_empty() {+ None+ } else {+ Some(bvid.clone())+ },cid,ep_id,duration_seconds: duration,diff --git a/src-tauri/src/platforms/bilibili/parser/list.rs b/src-tauri/src/platforms/bilibili/parser/list.rsindex 6e4ffb61..8c2a4b98 100644--- a/src-tauri/src/platforms/bilibili/parser/list.rs+++ b/src-tauri/src/platforms/bilibili/parser/list.rs@@ -3,8 +3,7 @@ use serde_json::Value;use super::super::api::{check_api_response, ApiClient, BilibiliError, Result};use super::{ContentMetadata, EpisodeItem, PaginationInfo, ParsedContent};-const COLLECTION_URL: &str =- "https://api.bilibili.com/x/polymer/web-space/seasons_archives_list";+const COLLECTION_URL: &str = "https://api.bilibili.com/x/polymer/web-space/seasons_archives_list";const SERIES_ARCHIVES_URL: &str = "https://api.bilibili.com/x/series/archives";const SERIES_META_URL: &str = "https://api.bilibili.com/x/series/series";const PAGE_SIZE: u32 = 30;@@ -148,10 +147,7 @@ fn archives_to_items(archives: &[Value], prefix: String) -> Vec<EpisodeItem> {.and_then(Value::as_str).unwrap_or("").to_string();- let cover = a- .get("pic")- .and_then(Value::as_str)- .map(String::from);+ let cover = a.get("pic").and_then(Value::as_str).map(String::from);let duration = a.get("duration").and_then(Value::as_f64);let pub_time = a.get("pubdate").and_then(Value::as_u64);items.push(EpisodeItem {diff --git a/src-tauri/src/platforms/bilibili/parser/mod.rs b/src-tauri/src/platforms/bilibili/parser/mod.rsindex 8a973178..af1f9e1f 100644--- a/src-tauri/src/platforms/bilibili/parser/mod.rs+++ b/src-tauri/src/platforms/bilibili/parser/mod.rs@@ -88,15 +88,9 @@ impl ParsedContent {pub async fn parse(client: &ApiClient, kind: &UrlKind) -> Result<ParsedContent> {match kind {UrlKind::Video { bvid_or_av, page } => video::parse(client, bvid_or_av, *page).await,- UrlKind::BangumiEpisode { ep_id } => {- bangumi::parse_by_ep(client, *ep_id).await- }- UrlKind::BangumiSeason { season_id } => {- bangumi::parse_by_season(client, *season_id).await- }- UrlKind::BangumiMedia { media_id } => {- bangumi::parse_by_media(client, *media_id).await- }+ UrlKind::BangumiEpisode { ep_id } => bangumi::parse_by_ep(client, *ep_id).await,+ UrlKind::BangumiSeason { season_id } => bangumi::parse_by_season(client, *season_id).await,+ UrlKind::BangumiMedia { media_id } => bangumi::parse_by_media(client, *media_id).await,UrlKind::CheeseEpisode { ep_id } => cheese::parse_by_ep(client, *ep_id).await,UrlKind::CheeseSeason { season_id } => cheese::parse_by_season(client, *season_id).await,UrlKind::Space { mid } => space::parse(client, *mid, 1).await,diff --git a/src-tauri/src/platforms/bilibili/parser/popular.rs b/src-tauri/src/platforms/bilibili/parser/popular.rsindex 096b0bdd..cab8c549 100644--- a/src-tauri/src/platforms/bilibili/parser/popular.rs+++ b/src-tauri/src/platforms/bilibili/parser/popular.rs@@ -51,10 +51,7 @@ pub async fn parse(client: &ApiClient, num: u32) -> Result<ParsedContent> {.and_then(Value::as_str).unwrap_or("").to_string();- let cover = v- .get("pic")- .and_then(Value::as_str)- .map(String::from);+ let cover = v.get("pic").and_then(Value::as_str).map(String::from);let duration = v.get("duration").and_then(Value::as_f64);let pub_time = v.get("pubdate").and_then(Value::as_u64);items.push(EpisodeItem {diff --git a/src-tauri/src/platforms/bilibili/parser/space.rs b/src-tauri/src/platforms/bilibili/parser/space.rsindex 4ed98dac..76063384 100644--- a/src-tauri/src/platforms/bilibili/parser/space.rs+++ b/src-tauri/src/platforms/bilibili/parser/space.rs@@ -66,10 +66,7 @@ pub async fn parse(client: &ApiClient, mid: u64, page: u32) -> Result<ParsedCont.and_then(Value::as_str).unwrap_or("").to_string();- let cover = v- .get("pic")- .and_then(Value::as_str)- .map(String::from);+ let cover = v.get("pic").and_then(Value::as_str).map(String::from);let duration = v.get("length").and_then(Value::as_str)diff --git a/src-tauri/src/platforms/bilibili/parser/video.rs b/src-tauri/src/platforms/bilibili/parser/video.rsindex 0b69b60a..8f06796c 100644--- a/src-tauri/src/platforms/bilibili/parser/video.rs+++ b/src-tauri/src/platforms/bilibili/parser/video.rs@@ -24,10 +24,7 @@ pub async fn parse(.and_then(Value::as_str).unwrap_or("Bilibili Video").to_string();- let cover = data- .get("pic")- .and_then(Value::as_str)- .map(String::from);+ let cover = data.get("pic").and_then(Value::as_str).map(String::from);let uploader = data.get("owner").and_then(|o| o.get("name"))@@ -42,10 +39,7 @@ pub async fn parse(.and_then(|o| o.get("face")).and_then(Value::as_str).map(String::from);- let description = data- .get("desc")- .and_then(Value::as_str)- .map(String::from);+ let description = data.get("desc").and_then(Value::as_str).map(String::from);let pub_time = data.get("pubdate").and_then(Value::as_u64);let bvid_val = data.get("bvid")@@ -84,10 +78,7 @@ pub async fn parse(let mut items: Vec<EpisodeItem> = Vec::new();if let Some(secs) = sections {for sec in secs {- let section_title = sec- .get("title")- .and_then(Value::as_str)- .map(String::from);+ let section_title = sec.get("title").and_then(Value::as_str).map(String::from);if let Some(eps) = sec.get("episodes").and_then(Value::as_array) {for (i, ep) in eps.iter().enumerate() {let ep_bvid = ep@@ -103,16 +94,12 @@ pub async fn parse(.unwrap_or("").to_string();let arc = ep.get("arc");- let dur = arc- .and_then(|a| a.get("duration"))- .and_then(Value::as_f64);+ let dur = arc.and_then(|a| a.get("duration")).and_then(Value::as_f64);let cover_ep = arc.and_then(|a| a.get("pic")).and_then(Value::as_str).map(String::from);- let pub_ep = arc- .and_then(|a| a.get("pubdate"))- .and_then(Value::as_u64);+ let pub_ep = arc.and_then(|a| a.get("pubdate")).and_then(Value::as_u64);items.push(EpisodeItem {episode_id: format!("ugc:{}", ep_bvid),title: ep_title,@@ -193,10 +180,12 @@ pub async fn parse(}}- let cid = data- .get("cid")- .and_then(Value::as_u64)- .or_else(|| pages.and_then(|p| p.first()).and_then(|p| p.get("cid")).and_then(Value::as_u64));+ let cid = data.get("cid").and_then(Value::as_u64).or_else(|| {+ pages+ .and_then(|p| p.first())+ .and_then(|p| p.get("cid"))+ .and_then(Value::as_u64)+ });let duration = data.get("duration").and_then(Value::as_f64);let item = EpisodeItem {episode_id: format!("video:{}", bvid_val),diff --git a/src-tauri/src/platforms/bilibili/parser/watch_later.rs b/src-tauri/src/platforms/bilibili/parser/watch_later.rsindex 7f812668..66634d9d 100644--- a/src-tauri/src/platforms/bilibili/parser/watch_later.rs+++ b/src-tauri/src/platforms/bilibili/parser/watch_later.rs@@ -26,10 +26,7 @@ pub async fn parse(client: &ApiClient, page: u32) -> Result<ParsedContent> {let raw = client.get_json(&url).await?;let data = check_api_response(&raw)?;- let count = data- .get("count")- .and_then(Value::as_u64)- .unwrap_or(0) as u32;+ let count = data.get("count").and_then(Value::as_u64).unwrap_or(0) as u32;let total_pages = ((count + PAGE_SIZE - 1) / PAGE_SIZE).max(1);let list = data.get("list")@@ -54,10 +51,7 @@ pub async fn parse(client: &ApiClient, page: u32) -> Result<ParsedContent> {.and_then(Value::as_str).unwrap_or("").to_string();- let cover = v- .get("pic")- .and_then(Value::as_str)- .map(String::from);+ let cover = v.get("pic").and_then(Value::as_str).map(String::from);let duration = v.get("duration").and_then(Value::as_f64);let pub_time = v.get("pubdate").and_then(Value::as_u64);let add_at = v.get("add_at").and_then(Value::as_u64);diff --git a/src-tauri/src/platforms/bilibili/preview.rs b/src-tauri/src/platforms/bilibili/preview.rsindex 7f113281..3692d770 100644--- a/src-tauri/src/platforms/bilibili/preview.rs+++ b/src-tauri/src/platforms/bilibili/preview.rs@@ -225,11 +225,7 @@ pub fn audio_qn_label(qn: u32) -> &'static str {}}-pub async fn fetch(- client: &ApiClient,- item: &EpisodeItem,- kind: &UrlKind,-) -> Result<PreviewInfo> {+pub async fn fetch(client: &ApiClient, item: &EpisodeItem, kind: &UrlKind) -> Result<PreviewInfo> {match kind {UrlKind::BangumiEpisode { .. }| UrlKind::BangumiSeason { .. }@@ -295,7 +291,11 @@ fn build_preview(data: &Value) -> Result<PreviewInfo> {let accepted_qns: Vec<u32> = data.get("accept_quality").and_then(Value::as_array)- .map(|arr| arr.iter().filter_map(|v| v.as_u64().map(|n| n as u32)).collect())+ .map(|arr| {+ arr.iter()+ .filter_map(|v| v.as_u64().map(|n| n as u32))+ .collect()+ }).unwrap_or_default();let accepted_qn_labels: Vec<String> = data.get("accept_description")@@ -323,10 +323,7 @@ fn build_preview(data: &Value) -> Result<PreviewInfo> {}if let Some(durl) = data.get("durl").and_then(Value::as_array) {- let format = data- .get("format")- .and_then(Value::as_str)- .unwrap_or("mp4");+ let format = data.get("format").and_then(Value::as_str).unwrap_or("mp4");let container = if format.starts_with("flv") {MediaContainer::Flv} else {@@ -383,7 +380,10 @@ fn parse_dash_video(dash: &serde_json::Map<String, Value>) -> Vec<VideoStream> {let qn = entry.get("id").and_then(Value::as_u64).unwrap_or(0) as u32;let codec_id = entry.get("codecid").and_then(Value::as_u64).unwrap_or(0) as u32;let width = entry.get("width").and_then(Value::as_u64).map(|n| n as u32);- let height = entry.get("height").and_then(Value::as_u64).map(|n| n as u32);+ let height = entry+ .get("height")+ .and_then(Value::as_u64)+ .map(|n| n as u32);let frame_rate = entry.get("frame_rate").or_else(|| entry.get("frameRate"))diff --git a/src-tauri/src/platforms/bilibili/url_kind.rs b/src-tauri/src/platforms/bilibili/url_kind.rsindex 44b5f0b8..ac3f8aaf 100644--- a/src-tauri/src/platforms/bilibili/url_kind.rs+++ b/src-tauri/src/platforms/bilibili/url_kind.rs@@ -5,20 +5,47 @@ use super::api::{ApiClient, BilibiliError, Result};#[derive(Debug, Clone, PartialEq, Eq)]pub enum UrlKind {- Video { bvid_or_av: String, page: Option<u32> },- BangumiEpisode { ep_id: u64 },- BangumiSeason { season_id: u64 },- BangumiMedia { media_id: u64 },- CheeseEpisode { ep_id: u64 },- CheeseSeason { season_id: u64 },- Space { mid: u64 },- Favlist { fid: u64 },- Collection { mid: u64, sid: u64 },- Series { mid: u64, sid: u64 },- PopularWeek { num: u32 },+ Video {+ bvid_or_av: String,+ page: Option<u32>,+ },+ BangumiEpisode {+ ep_id: u64,+ },+ BangumiSeason {+ season_id: u64,+ },+ BangumiMedia {+ media_id: u64,+ },+ CheeseEpisode {+ ep_id: u64,+ },+ CheeseSeason {+ season_id: u64,+ },+ Space {+ mid: u64,+ },+ Favlist {+ fid: u64,+ },+ Collection {+ mid: u64,+ sid: u64,+ },+ Series {+ mid: u64,+ sid: u64,+ },+ PopularWeek {+ num: u32,+ },WatchLater,History,- Festival { url: String },+ Festival {+ url: String,+ },}impl UrlKind {@@ -42,24 +69,19 @@ impl UrlKind {}}-static RE_VIDEO_BV: Lazy<Regex> = Lazy::new(|| {- Regex::new(r"bilibili\.com/video/(BV[a-zA-Z0-9]+|av\d+)").unwrap()-});+static RE_VIDEO_BV: Lazy<Regex> =+ Lazy::new(|| Regex::new(r"bilibili\.com/video/(BV[a-zA-Z0-9]+|av\d+)").unwrap());static RE_BARE_BV: Lazy<Regex> = Lazy::new(|| Regex::new(r"(BV[a-zA-Z0-9]{8,})").unwrap());static RE_BARE_AV: Lazy<Regex> = Lazy::new(|| Regex::new(r"\bav(\d+)\b").unwrap());-static RE_BANGUMI: Lazy<Regex> = Lazy::new(|| {- Regex::new(r"bilibili\.com/bangumi/(?:play|media)/(ss\d+|ep\d+|md\d+)").unwrap()-});+static RE_BANGUMI: Lazy<Regex> =+ Lazy::new(|| Regex::new(r"bilibili\.com/bangumi/(?:play|media)/(ss\d+|ep\d+|md\d+)").unwrap());static RE_BARE_BANGUMI: Lazy<Regex> = Lazy::new(|| Regex::new(r"\b(ss\d+|ep\d+|md\d+)\b").unwrap());-static RE_CHEESE: Lazy<Regex> = Lazy::new(|| {- Regex::new(r"bilibili\.com/cheese/play/(ss\d+|ep\d+)").unwrap()-});-static RE_LIST_LISTS: Lazy<Regex> = Lazy::new(|| {- Regex::new(r"space\.bilibili\.com/(\d+)/lists(?:/(\d+))?").unwrap()-});-static RE_FAVLIST_SPACE: Lazy<Regex> = Lazy::new(|| {- Regex::new(r"space\.bilibili\.com/\d+/favlist").unwrap()-});+static RE_CHEESE: Lazy<Regex> =+ Lazy::new(|| Regex::new(r"bilibili\.com/cheese/play/(ss\d+|ep\d+)").unwrap());+static RE_LIST_LISTS: Lazy<Regex> =+ Lazy::new(|| Regex::new(r"space\.bilibili\.com/(\d+)/lists(?:/(\d+))?").unwrap());+static RE_FAVLIST_SPACE: Lazy<Regex> =+ Lazy::new(|| Regex::new(r"space\.bilibili\.com/\d+/favlist").unwrap());static RE_FAVLIST_LIST: Lazy<Regex> = Lazy::new(|| {Regex::new(r"bilibili\.com/(?:medialist/detail/)?ml(\d+)|bilibili\.com/list/ml(\d+)").unwrap()});@@ -89,9 +111,15 @@ fn detect_internal(url: &str, query_override: Option<&str>) -> Result<UrlKind> {if RE_VIDEO_BV.is_match(url) {if let Some(cap) = RE_VIDEO_BV.captures(url) {- let id = cap.get(1).map(|m| m.as_str().to_string()).unwrap_or_default();+ let id = cap+ .get(1)+ .map(|m| m.as_str().to_string())+ .unwrap_or_default();let page = extract_page_query(url, query_override);- return Ok(UrlKind::Video { bvid_or_av: id, page });+ return Ok(UrlKind::Video {+ bvid_or_av: id,+ page,+ });}}@@ -191,7 +219,10 @@ fn detect_internal(url: &str, query_override: Option<&str>) -> Result<UrlKind> {}if let Some(cap) = RE_BARE_BV.captures(url) {- let id = cap.get(1).map(|m| m.as_str().to_string()).unwrap_or_default();+ let id = cap+ .get(1)+ .map(|m| m.as_str().to_string())+ .unwrap_or_default();return Ok(UrlKind::Video {bvid_or_av: id,page: None,@@ -298,9 +329,8 @@ pub fn parse_video_id(input: &str) -> (Option<String>, Option<u64>) {}pub fn extract_festival_bvid(html: &str) -> Option<String> {- static RE_STATE: Lazy<Regex> = Lazy::new(|| {- Regex::new(r"window\.__INITIAL_STATE__\s*=\s*(\{.*?\});").unwrap()- });+ static RE_STATE: Lazy<Regex> =+ Lazy::new(|| Regex::new(r"window\.__INITIAL_STATE__\s*=\s*(\{.*?\});").unwrap());let cap = RE_STATE.captures(html)?;let json_str = cap.get(1)?.as_str();let v: serde_json::Value = serde_json::from_str(json_str).ok()?;@@ -413,10 +443,7 @@ mod tests {#[test]fn detects_series() {let url = "https://space.bilibili.com/123/lists/456?type=series";- assert_eq!(- detect(url).unwrap(),- UrlKind::Series { mid: 123, sid: 456 }- );+ assert_eq!(detect(url).unwrap(), UrlKind::Series { mid: 123, sid: 456 });}#[test]diff --git a/src-tauri/src/platforms/bilibili/wbi.rs b/src-tauri/src/platforms/bilibili/wbi.rsindex 4088fdff..edc53f12 100644--- a/src-tauri/src/platforms/bilibili/wbi.rs+++ b/src-tauri/src/platforms/bilibili/wbi.rs@@ -70,7 +70,9 @@ async fn fetch_keys(client: &ApiClient) -> Result<WbiKeys> {let raw = client.get_json(NAV_URL).await?;let data = match check_api_response(&raw) {Ok(d) => d,- Err(BilibiliError::NotLoggedIn) => raw.get("data").ok_or(BilibiliError::ContentUnavailable)?,+ Err(BilibiliError::NotLoggedIn) => {+ raw.get("data").ok_or(BilibiliError::ContentUnavailable)?+ }Err(e) => return Err(e),};let wbi_img = data@@ -116,10 +118,7 @@ pub fn sign(params: &[(&str, String)], keys: &WbiKeys) -> String {format!("{}&w_rid={}", query, w_rid)}-pub async fn signed_query(- client: &ApiClient,- params: &[(&str, String)],-) -> Result<String> {+pub async fn signed_query(client: &ApiClient, params: &[(&str, String)]) -> Result<String> {let k = keys(client).await?;Ok(sign(params, &k))}@@ -174,7 +173,8 @@ mod tests {sub_key: "4932caff0ff746eab6f01bf08b70ac45".to_string(),fetched_at_secs: 0,};- let params: Vec<(&str, String)> = vec![("foo", "114".to_string()), ("bar", "514".to_string())];+ let params: Vec<(&str, String)> =+ vec![("foo", "114".to_string()), ("bar", "514".to_string())];let query = sign(¶ms, &k);assert!(query.contains("w_rid="));assert!(query.contains("wts="));diff --git a/src-tauri/src/platforms/bluesky/mod.rs b/src-tauri/src/platforms/bluesky/mod.rsindex dc0f4263..dd4d4cb1 100644--- a/src-tauri/src/platforms/bluesky/mod.rs+++ b/src-tauri/src/platforms/bluesky/mod.rs@@ -1,6 +1,6 @@-use omniget_core::models::progress::ProgressUpdate;use anyhow::anyhow;use async_trait::async_trait;+use omniget_core::models::progress::ProgressUpdate;use tokio::sync::mpsc;use crate::core::direct_downloader;diff --git a/src-tauri/src/platforms/gallerydl/mod.rs b/src-tauri/src/platforms/gallerydl/mod.rsindex ffa31761..0cc3eaa5 100644--- a/src-tauri/src/platforms/gallerydl/mod.rs+++ b/src-tauri/src/platforms/gallerydl/mod.rs@@ -7,7 +7,9 @@ use async_trait::async_trait;use tokio::io::{AsyncBufReadExt, BufReader};use tokio::sync::mpsc;-use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};+use omniget_core::models::media::{+ DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality,+};use omniget_core::models::progress::ProgressUpdate;use omniget_core::platforms::traits::PlatformDownloader;@@ -42,7 +44,9 @@ const GALLERY_HOSTS: &[&str] = &[pub fn is_gallery_url(url: &str) -> bool {let host = match url::Url::parse(url) {- Ok(u) => u.host_str().map(|h| h.trim_start_matches("www.").to_lowercase()),+ Ok(u) => u+ .host_str()+ .map(|h| h.trim_start_matches("www.").to_lowercase()),Err(_) => None,};let Some(host) = host else {@@ -134,7 +138,9 @@ impl PlatformDownloader for GalleryDlDownloader {let bin = omniget_core::core::dependencies::ensure_gallerydl().await.ok_or_else(|| {- anyhow!("gallery-dl is not available. Install gallery-dl to download from this site.")+ anyhow!(+ "gallery-dl is not available. Install gallery-dl to download from this site."+ )})?;std::fs::create_dir_all(&opts.output_dir)?;@@ -154,13 +160,17 @@ impl PlatformDownloader for GalleryDlDownloader {.arg(archive_dir.join("gallery-dl.txt"));}let cookie_file = data_dir.join("chrome-extension-cookies.txt");- if std::fs::metadata(&cookie_file).map(|m| m.len() > 0).unwrap_or(false) {+ if std::fs::metadata(&cookie_file)+ .map(|m| m.len() > 0)+ .unwrap_or(false)+ {cmd.arg("--cookies").arg(&cookie_file);}}cmd.arg("--").arg(&url);+ cmd.kill_on_drop(true);let mut child = cmd.spawn().map_err(|e| anyhow!("Failed to start gallery-dl: {}", e))?;@@ -296,7 +306,9 @@ mod tests {#[test]fn matches_curated_gallery_hosts() {- assert!(is_gallery_url("https://www.deviantart.com/someartist/gallery"));+ assert!(is_gallery_url(+ "https://www.deviantart.com/someartist/gallery"+ ));assert!(is_gallery_url("https://www.pixiv.net/en/users/12345"));assert!(is_gallery_url("https://danbooru.donmai.us/posts?tags=foo"));assert!(is_gallery_url("https://imgur.com/a/abcd"));diff --git a/src-tauri/src/platforms/instagram/mod.rs b/src-tauri/src/platforms/instagram/mod.rsindex dff3d17c..ae2d3eff 100644--- a/src-tauri/src/platforms/instagram/mod.rs+++ b/src-tauri/src/platforms/instagram/mod.rs@@ -1,6 +1,6 @@-use omniget_core::models::progress::ProgressUpdate;use anyhow::anyhow;use async_trait::async_trait;+use omniget_core::models::progress::ProgressUpdate;use rand::RngExt;use regex::Regex;use tokio::sync::mpsc;diff --git a/src-tauri/src/platforms/reddit/mod.rs b/src-tauri/src/platforms/reddit/mod.rsindex c8c54f56..245cf2b9 100644--- a/src-tauri/src/platforms/reddit/mod.rs+++ b/src-tauri/src/platforms/reddit/mod.rs@@ -1,6 +1,6 @@-use omniget_core::models::progress::ProgressUpdate;use anyhow::anyhow;use async_trait::async_trait;+use omniget_core::models::progress::ProgressUpdate;use tokio::sync::mpsc;use crate::core::direct_downloader;diff --git a/src-tauri/src/platforms/twitch/mod.rs b/src-tauri/src/platforms/twitch/mod.rsindex 3e889d71..fda6cfcf 100644--- a/src-tauri/src/platforms/twitch/mod.rs+++ b/src-tauri/src/platforms/twitch/mod.rs@@ -1,6 +1,6 @@-use omniget_core::models::progress::ProgressUpdate;use anyhow::anyhow;use async_trait::async_trait;+use omniget_core::models::progress::ProgressUpdate;use tokio::sync::mpsc;use crate::core::direct_downloader;diff --git a/src-tauri/src/platforms/twitter/mod.rs b/src-tauri/src/platforms/twitter/mod.rsindex 8cf508e7..5395da43 100644--- a/src-tauri/src/platforms/twitter/mod.rs+++ b/src-tauri/src/platforms/twitter/mod.rs@@ -1,4 +1,5 @@use omniget_core::models::progress::ProgressUpdate;+use regex::Regex;use std::sync::Arc;use anyhow::anyhow;@@ -64,14 +65,74 @@ impl TwitterDownloader {}}+ fn managed_cookie_string() -> Option<String> {+ for domain in ["x.com", "twitter.com"] {+ let slug = omniget_core::core::log_hook::current_cookie_slug();+ let path = crate::cookies::account_path_for_consumer(domain, slug.as_deref())+ .or_else(|| crate::cookies::account_path_for_consumer(domain, None));+ let Some(path) = path else {+ continue;+ };+ let Ok(content) = std::fs::read_to_string(path) else {+ continue;+ };+ if let Some(header) = Self::cookie_header_from_netscape(&content) {+ return Some(header);+ }+ }+ None+ }++ fn cookie_header_from_netscape(content: &str) -> Option<String> {+ let pairs: Vec<String> = content+ .lines()+ .filter_map(|line| {+ let trimmed = line.trim();+ if trimmed.is_empty() || trimmed.starts_with("# Netscape") {+ return None;+ }+ let normalized = trimmed.strip_prefix("#HttpOnly_").unwrap_or(trimmed);+ if normalized.starts_with('#') {+ return None;+ }+ let parts: Vec<&str> = normalized.split('\t').collect();+ if parts.len() < 7 {+ return None;+ }+ let name = parts[5].trim();+ let value = parts[6].trim();+ if name.is_empty() {+ return None;+ }+ Some(format!("{}={}", name, value))+ })+ .collect();+ if pairs.is_empty() {+ None+ } else {+ Some(pairs.join("; "))+ }+ }++ fn auth_cookie_string() -> Option<String> {+ Self::managed_cookie_string().or_else(Self::manual_cookie_string)+ }++ fn cookie_value(cookie_header: &str, name: &str) -> Option<String> {+ cookie_header.split(';').find_map(|part| {+ let (k, v) = part.trim().split_once('=')?;+ (k.trim() == name).then(|| v.trim().to_string())+ })+ }+fn request_cookie_header(guest_token: &str) -> String {let guest_cookie = format!("guest_id={}",urlencoding::encode(&format!("v1:{}", guest_token)));- if let Some(manual) = Self::manual_cookie_string() {- format!("{}; {}", guest_cookie, manual)+ if let Some(auth) = Self::auth_cookie_string() {+ format!("{}; {}", guest_cookie, auth)} else {guest_cookie}@@ -171,6 +232,7 @@ impl TwitterDownloader {.get("media_url").and_then(|v| v.as_str()).is_some()+ || media_item.get("url").and_then(|v| v.as_str()).is_some(){return Some(TwitterMediaType::Photo);}@@ -271,8 +333,10 @@ impl TwitterDownloader {);let cookie_val = Self::request_cookie_header(guest_token);+ let ct0 = Self::cookie_value(&cookie_val, "ct0");+ let has_auth_token = Self::cookie_value(&cookie_val, "auth_token").is_some();- let response = self+ let mut request = self.client.get(&url).header("Authorization", BEARER)@@ -281,9 +345,15 @@ impl TwitterDownloader {.header("x-twitter-active-user", "yes").header("Accept-Language", "en").header("Content-Type", "application/json")- .header("Cookie", &cookie_val)- .send()- .await?;+ .header("Cookie", &cookie_val);+ if has_auth_token {+ request = request.header("x-twitter-auth-type", "OAuth2Session");+ }+ if let Some(ct0) = ct0 {+ request = request.header("x-csrf-token", ct0);+ }++ let response = request.send().await?;let status = response.status();tracing::debug!("[twitter] graphql tweet_id={} status={}", tweet_id, status);@@ -374,7 +444,7 @@ impl TwitterDownloader {);let mut request = self.client.get(&url);- if let Some(cookie) = Self::manual_cookie_string() {+ if let Some(cookie) = Self::auth_cookie_string() {request = request.header("Cookie", cookie);}@@ -491,7 +561,9 @@ impl TwitterDownloader {let media = json.get("mediaDetails").and_then(Self::clone_media_array)+ .or_else(|| json.get("photos").and_then(Self::clone_media_array)).or_else(|| Self::find_first_array_for_key(json, "mediaDetails"))+ .or_else(|| Self::find_first_array_for_key(json, "photos")).ok_or_else(|| anyhow!("No media found in tweet"))?;tracing::debug!(@@ -535,19 +607,30 @@ impl TwitterDownloader {let base_url = media_item.get("media_url_https").or_else(|| media_item.get("media_url"))+ .or_else(|| media_item.get("url")).and_then(|v| v.as_str())?;+ Self::best_photo_url_from_str(base_url)+ }- let extension = url::Url::parse(base_url)+ fn best_photo_url_from_str(base_url: &str) -> Option<(String, String)> {+ let cleaned = Self::decode_html_url(base_url);+ let extension = url::Url::parse(&cleaned).ok().and_then(|u| {u.path_segments().and_then(|segments| segments.last().map(|s| s.to_string()))})- .and_then(|filename| filename.rsplit('.').next().map(|ext| ext.to_string()))+ .and_then(|filename| {+ filename+ .rsplit('.')+ .next()+ .and_then(|ext| ext.split('?').next())+ .map(|ext| ext.to_string())+ }).filter(|ext| !ext.is_empty()).unwrap_or_else(|| "jpg".to_string());- let url = if let Ok(mut parsed) = url::Url::parse(base_url) {+ let url = if let Ok(mut parsed) = url::Url::parse(&cleaned) {let existing: Vec<(String, String)> = parsed.query_pairs().filter(|(key, _)| key != "name")@@ -562,15 +645,43 @@ impl TwitterDownloader {qp.append_pair("name", "orig");}parsed.to_string()- } else if base_url.contains('?') {- format!("{}&name=orig", base_url)+ } else if cleaned.contains('?') {+ format!("{}&name=orig", cleaned)} else {- format!("{}?name=orig", base_url)+ format!("{}?name=orig", cleaned)};Some((url, extension))}+ fn decode_html_url(raw: &str) -> String {+ raw.replace("\\u0026", "&")+ .replace("&", "&")+ .replace("&", "&")+ }++ fn extract_html_photo_items(html: &str) -> Vec<TwitterMediaItem> {+ let re = match Regex::new(r#"https://pbs\.twimg\.com/media/[^\s"'<>\\]+"#) {+ Ok(re) => re,+ Err(_) => return Vec::new(),+ };+ let mut seen = std::collections::HashSet::new();+ let mut items = Vec::new();+ for m in re.find_iter(html) {+ let raw = m.as_str().trim_end_matches([',', ';', ')', ']']);+ if let Some((url, extension)) = Self::best_photo_url_from_str(raw) {+ if seen.insert(url.clone()) {+ items.push(TwitterMediaItem {+ media_type: TwitterMediaType::Photo,+ url,+ extension,+ });+ }+ }+ }+ items+ }+fn parse_media_items(media: &[serde_json::Value]) -> anyhow::Result<TwitterMedia> {let items: Vec<TwitterMediaItem> = media.iter()@@ -737,7 +848,7 @@ impl PlatformDownloader for TwitterDownloader {if quality.format == "ytdlp" {let ytdlp_path = crate::core::ytdlp::ensure_ytdlp().await?;let mut extra_flags = Vec::new();- if let Some(cookie) = Self::manual_cookie_string() {+ if let Some(cookie) = Self::auth_cookie_string() {extra_flags.push("--add-headers".to_string());extra_flags.push(format!("Cookie:{}", cookie));}@@ -843,7 +954,7 @@ impl TwitterDownloader {"--add-headers".to_string(),"Referer:https://x.com/".to_string(),];- if let Some(cookie) = Self::manual_cookie_string() {+ if let Some(cookie) = Self::auth_cookie_string() {extra_flags.push("--add-headers".to_string());extra_flags.push(format!("Cookie:{}", cookie));}@@ -870,8 +981,47 @@ impl TwitterDownloader {tweet_id,graphql_err);- let syndication = self.request_syndication(&tweet_id).await?;- Self::extract_syndication_media(&syndication)?+ match self.request_syndication(&tweet_id).await {+ Ok(syndication) => match Self::extract_syndication_media(&syndication) {+ Ok(items) => items,+ Err(syndication_extract_err) => {+ tracing::warn!(+ "[twitter] syndication media extraction failed for tweet_id={}: {}",+ tweet_id,+ syndication_extract_err+ );+ match self.request_html_media(url).await {+ Ok(items) => items,+ Err(html_err) => {+ return Err(anyhow!(+ "Post not available; graphql='{}'; syndication_extract='{}'; html='{}'",+ graphql_err,+ syndication_extract_err,+ html_err+ ));+ }+ }+ }+ },+ Err(syndication_err) => {+ tracing::warn!(+ "[twitter] syndication lookup failed for tweet_id={}: {}",+ tweet_id,+ syndication_err+ );+ match self.request_html_media(url).await {+ Ok(items) => items,+ Err(html_err) => {+ return Err(anyhow!(+ "Post not available; graphql='{}'; syndication='{}'; html='{}'",+ graphql_err,+ syndication_err,+ html_err+ ));+ }+ }+ }+ }}};@@ -883,6 +1033,37 @@ impl TwitterDownloader {))}+ async fn request_html_media(&self, url: &str) -> anyhow::Result<Vec<serde_json::Value>> {+ let mut request = self+ .client+ .get(url)+ .header("User-Agent", USER_AGENT)+ .header("Accept-Language", "en")+ .header("Referer", "https://x.com/");+ if let Some(cookie) = Self::auth_cookie_string() {+ request = request.header("Cookie", cookie);+ }+ let response = request.send().await?;+ if !response.status().is_success() {+ return Err(anyhow!("HTML request returned HTTP {}", response.status()));+ }+ let html = response.text().await?;+ let items = Self::extract_html_photo_items(&html);+ if items.is_empty() {+ return Err(anyhow!("No photo URLs found in HTML"));+ }+ tracing::debug!("[twitter] html extracted {} photo entries", items.len());+ Ok(items+ .into_iter()+ .map(|item| {+ serde_json::json!({+ "type": "photo",+ "media_url_https": item.url,+ })+ })+ .collect())+ }+async fn try_graphql(&self, tweet_id: &str) -> anyhow::Result<Vec<serde_json::Value>> {let token = self.get_guest_token(false).await?;@@ -897,6 +1078,3 @@ impl TwitterDownloader {}}}--#[cfg(test)]-mod tests;diff --git a/src-tauri/src/platforms/twitter/tests.rs b/src-tauri/src/platforms/twitter/tests.rsdeleted file mode 100644index 8b137891..00000000--- a/src-tauri/src/platforms/twitter/tests.rs+++ /dev/null@@ -1 +0,0 @@-diff --git a/src-tauri/src/platforms/youtube/mod.rs b/src-tauri/src/platforms/youtube/mod.rsindex 3ebb7b36..96f6ec18 100644--- a/src-tauri/src/platforms/youtube/mod.rs+++ b/src-tauri/src/platforms/youtube/mod.rs@@ -59,9 +59,19 @@ impl YouTubeDownloader {if parsed.path().starts_with("/playlist") {return true;}- if parsed.query_pairs().any(|(k, _)| k == "list") {- return true;++ let mut has_list = false;+ let mut has_video = false;+ for (key, value) in parsed.query_pairs() {+ if key == "list" && !value.is_empty() {+ has_list = true;+ }+ if key == "v" && !value.is_empty() {+ has_video = true;+ }}++ return has_list && !has_video;}false}@@ -211,6 +221,32 @@ impl YouTubeDownloader {}}+#[cfg(test)]+mod tests {+ use super::YouTubeDownloader;++ #[test]+ fn watch_url_with_playlist_param_is_single_video() {+ assert!(!YouTubeDownloader::is_playlist_url(+ "https://www.youtube.com/watch?v=abc123&list=PLxyz&index=2",+ ));+ }++ #[test]+ fn playlist_url_is_playlist() {+ assert!(YouTubeDownloader::is_playlist_url(+ "https://www.youtube.com/playlist?list=PLxyz",+ ));+ }++ #[test]+ fn list_only_watch_url_is_playlist() {+ assert!(YouTubeDownloader::is_playlist_url(+ "https://www.youtube.com/watch?list=PLxyz",+ ));+ }+}+#[async_trait]impl PlatformDownloader for YouTubeDownloader {fn name(&self) -> &str {@@ -356,6 +392,8 @@ impl YouTubeDownloader {let total = info.available_qualities.len();let mut total_bytes = 0u64;let mut last_path = playlist_dir.clone();+ let mut success_count = 0usize;+ let mut last_error: Option<String> = None;for (i, entry) in info.available_qualities.iter().enumerate() {if opts.cancel_token.is_cancelled() {@@ -373,7 +411,13 @@ impl YouTubeDownloader {let overall = (video_idx as f64 / video_total as f64) * 100.0+ (max_pct / video_total as f64);let _ = progress_tx- .send(ProgressUpdate::rich(overall, None, None, pu.speed_bps, None))+ .send(ProgressUpdate::rich(+ overall,+ None,+ None,+ pu.speed_bps,+ None,+ )).await;}});@@ -398,10 +442,12 @@ impl YouTubeDownloader {.await{Ok(result) => {+ success_count += 1;total_bytes += result.file_size_bytes;last_path = result.file_path;}Err(e) => {+ last_error = Some(e.to_string());tracing::warn!("Playlist video {} falhou: {}", i + 1, e);}}@@ -411,6 +457,13 @@ impl YouTubeDownloader {let _ = progress.send(ProgressUpdate::percent(100.0)).await;+ if success_count == 0 {+ anyhow::bail!(+ "Playlist download failed: {}",+ last_error.unwrap_or_else(|| "no entries were downloaded".to_string())+ );+ }+Ok(DownloadResult {file_path: last_path,file_size_bytes: total_bytes,diff --git a/src/components/download/DownloadLog.svelte b/src/components/download/DownloadLog.svelteindex 06f09b7a..1b9aa267 100644--- a/src/components/download/DownloadLog.svelte+++ b/src/components/download/DownloadLog.svelte@@ -13,6 +13,7 @@let preEl: HTMLPreElement | null = $state(null);let atBottom = $state(true);let unlisten: UnlistenFn | null = null;+ let refreshTimer: ReturnType<typeof setInterval> | null = null;async function refresh() {try {@@ -35,9 +36,16 @@refresh();}});- } else if (unlisten) {- unlisten();- unlisten = null;+ refreshTimer = setInterval(refresh, 1000);+ } else {+ if (unlisten) {+ unlisten();+ unlisten = null;+ }+ if (refreshTimer) {+ clearInterval(refreshTimer);+ refreshTimer = null;+ }}}@@ -70,6 +78,10 @@unlisten();unlisten = null;}+ if (refreshTimer) {+ clearInterval(refreshTimer);+ refreshTimer = null;+ }};});</script>diff --git a/src/components/settings/SettingsCookies.svelte b/src/components/settings/SettingsCookies.svelteindex 19be093e..fb5ff2e6 100644--- a/src/components/settings/SettingsCookies.svelte+++ b/src/components/settings/SettingsCookies.svelte@@ -54,11 +54,20 @@}let testing = $state<Record<string, boolean>>({});+ let selectedCookies = $state<Record<string, boolean>>({});++ function cookieTestUrl(domain: string, platformKind: string | undefined): string {+ if (platformKind === "bilibili") return "https://www.bilibili.com/video/BV1xx411c7mu";+ if (platformKind === "youtube" || platformKind === "youtube_music") {+ return "https://www.youtube.com/watch?v=dQw4w9WgXcQ";+ }+ if (platformKind === "twitch") return "https://www.twitch.tv/videos/1";+ return `https://${domain}`;+ }async function handleTest(domain: string, slug: string) {const bucket = registry.buckets[domain];- const acc = bucket?.accounts.find((a) => a.slug === slug);- const url = acc?.source_url || `https://${domain}`;+ const url = cookieTestUrl(domain, bucket?.platform_kind);const key = healthKey(domain, slug);testing = { ...testing, [key]: true };try {@@ -103,6 +112,7 @@let confirmClearOpen = $state(false);let confirmDomain = $state("");let confirmSlug = $state("");+ let confirmBulkClearOpen = $state(false);let addAccountOpen = $state(false);let addAccountDomain = $state("");@@ -117,6 +127,18 @@return bTime - aTime;}),);+ let selectedCookieItems = $derived.by(() => {+ const items: Array<{ domain: string; slug: string; alias: string }> = [];+ for (const [domain, bucket] of Object.entries(registry.buckets)) {+ for (const account of bucket.accounts) {+ if (selectedCookies[healthKey(domain, account.slug)]) {+ items.push({ domain, slug: account.slug, alias: account.alias });+ }+ }+ }+ return items;+ });+ let selectedCount = $derived(selectedCookieItems.length);async function reload() {loading = true;@@ -124,6 +146,14 @@const res = await invoke<ListResponse>("cookies_list");registry = res.registry;cookiesDir = res.cookies_dir;+ const validSelected: Record<string, boolean> = {};+ for (const [domain, bucket] of Object.entries(res.registry.buckets)) {+ for (const account of bucket.accounts) {+ const key = healthKey(domain, account.slug);+ if (selectedCookies[key]) validSelected[key] = true;+ }+ }+ selectedCookies = validSelected;try {const h = await invoke<HealthResponse>("cookies_health");const map: Record<string, HealthItem> = {};@@ -235,6 +265,36 @@confirmClearOpen = true;}+ function toggleCookieSelection(domain: string, slug: string, checked: boolean) {+ const key = healthKey(domain, slug);+ if (checked) {+ selectedCookies = { ...selectedCookies, [key]: true };+ return;+ }+ const next = { ...selectedCookies };+ delete next[key];+ selectedCookies = next;+ }++ function selectAllCookies() {+ const next: Record<string, boolean> = {};+ for (const bucket of bucketList) {+ for (const account of bucket.accounts) {+ next[healthKey(bucket.domain, account.slug)] = true;+ }+ }+ selectedCookies = next;+ }++ function clearCookieSelection() {+ selectedCookies = {};+ }++ function askBulkClear() {+ if (selectedCount === 0) return;+ confirmBulkClearOpen = true;+ }+function openAddAccount(domain: string) {addAccountDomain = domain;if (domain === "bilibili.com") {@@ -385,6 +445,28 @@}}+ async function confirmBulkClear() {+ const items = selectedCookieItems.map(({ domain, slug }) => ({ domain, slug }));+ if (items.length === 0) {+ confirmBulkClearOpen = false;+ return;+ }+ try {+ const res = await invoke<{ ok: boolean; cleared: number }>("cookies_clear_batch", {+ request: { items },+ });+ confirmBulkClearOpen = false;+ clearCookieSelection();+ await reload();+ showToast(+ "success",+ `${$t("settings.cookies.cleared_toast") as string} (${res.cleared})`,+ );+ } catch (e) {+ showToast("error", String(e));+ }+ }+async function openCookiesDir() {if (!cookiesDir) return;try {@@ -449,6 +531,25 @@</label></header>+ {#if bucketList.length > 0}+ <div class="bulk-bar">+ <div class="bulk-info">+ <span>{selectedCount} selected</span>+ </div>+ <div class="bulk-actions">+ <button type="button" class="ghost-btn subtle" onclick={selectAllCookies}>+ Select all+ </button>+ <button type="button" class="ghost-btn subtle" onclick={clearCookieSelection} disabled={selectedCount === 0}>+ {$t("common.clear")}+ </button>+ <button type="button" class="danger-btn" onclick={askBulkClear} disabled={selectedCount === 0}>+ {$t("settings.cookies.action_clear")}+ </button>+ </div>+ </div>+ {/if}+{#if loading}<div class="loading">{#each Array(3) as _, i (i)}@@ -479,6 +580,8 @@onClear={askClear}onAddAccount={openAddAccount}onTest={handleTest}+ selected={selectedCookies}+ onToggleSelection={toggleCookieSelection}/>{#if bucket.domain === "bilibili.com"}{#if bucket.accounts.some((a) => !a.slug.startsWith("_") && a.cookie_count > 0)}@@ -577,6 +680,26 @@</div>{/if}+{#if confirmBulkClearOpen}+ <div class="overlay" onclick={(e) => { if (e.target === e.currentTarget) confirmBulkClearOpen = false; }} role="presentation">+ <div class="confirm" role="dialog" aria-label={$t("settings.cookies.confirm_clear_title") as string}>+ <h3>{$t("settings.cookies.confirm_clear_title")}</h3>+ <p>+ Cookies for {selectedCount} account{selectedCount === 1 ? "" : "s"} go to the trash+ (recoverable for 24h). Continue?+ </p>+ <div class="confirm-actions">+ <button type="button" class="ghost-btn" onclick={() => confirmBulkClearOpen = false}>+ {$t("settings.cookies.confirm_clear_cancel")}+ </button>+ <button type="button" class="danger-btn" onclick={confirmBulkClear}>+ {$t("settings.cookies.confirm_clear_action")}+ </button>+ </div>+ </div>+ </div>+{/if}+<style>.section { display: flex; flex-direction: column; gap: 16px; }.section-head { display: flex; flex-direction: column; gap: 8px; }@@ -615,6 +738,26 @@margin-top: 3px;flex-shrink: 0;}+ .bulk-bar {+ display: flex;+ justify-content: space-between;+ align-items: center;+ gap: 12px;+ padding: 10px 12px;+ background: color-mix(in oklab, var(--button) 55%, transparent);+ border: 1px solid color-mix(in oklab, var(--content-border) 35%, transparent);+ border-radius: var(--border-radius);+ }+ .bulk-info {+ color: var(--secondary);+ font-size: 12px;+ }+ .bulk-actions {+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+ justify-content: flex-end;+ }.managed-toggle-text {display: flex;flex-direction: column;diff --git a/src/lib/components/cookies/CookieBucketCard.svelte b/src/lib/components/cookies/CookieBucketCard.svelteindex 7ad256c2..5d690595 100644--- a/src/lib/components/cookies/CookieBucketCard.svelte+++ b/src/lib/components/cookies/CookieBucketCard.svelte@@ -31,6 +31,8 @@onClear: (domain: string, slug: string) => void;onAddAccount?: (domain: string) => void;onTest?: (domain: string, slug: string) => void;+ selected?: Record<string, boolean>;+ onToggleSelection?: (domain: string, slug: string, checked: boolean) => void;};let {@@ -43,6 +45,8 @@onClear,onAddAccount,onTest,+ selected = {},+ onToggleSelection,}: Props = $props();let primaryAccount = $derived(bucket.accounts.find((a) => a.slug === "_default") ?? bucket.accounts[0]);@@ -52,6 +56,7 @@let inputRef = $state<HTMLInputElement | null>(null);let primaryHealth = $derived(primaryAccount ? health[primaryAccount.slug] : undefined);+ let sourceUrl = $derived.by(() => displaySourceUrl(primaryAccount?.source_url ?? null, bucket.domain));let status = $derived.by(() => {if (!primaryAccount) return "empty";@@ -139,14 +144,41 @@}}+ function siteHostForDomain(domain: string): string {+ const host = domain.trim().replace(/^\./, "").toLowerCase();+ if (host.endsWith("bilibili.com")) return "www.bilibili.com";+ const parts = host.split(".").filter(Boolean);+ if (parts.length >= 2) return parts.slice(-2).join(".");+ return host;+ }++ function displaySourceUrl(rawUrl: string | null, domain: string): string | null {+ const host = siteHostForDomain(domain);+ if (!host) return rawUrl;+ const siteUrl = `https://${host}/`;+ if (!rawUrl) return null;+ try {+ const parsed = new URL(rawUrl);+ const sourceHost = siteHostForDomain(parsed.hostname);+ if (sourceHost === host) return siteUrl;+ } catch {+ return siteUrl;+ }+ return siteUrl;+ }+async function openSourceUrl() {- if (!primaryAccount?.source_url) return;+ if (!sourceUrl) return;try {- await openShell(primaryAccount.source_url);+ await openShell(sourceUrl);} catch (e) {console.warn("[cookies] failed to open source url", e);}}++ function keyFor(slug: string): string {+ return `${bucket.domain}__${slug}`;+ }</script><article class="bucket-card" data-status={status}>@@ -189,11 +221,11 @@{/if}</p>- {#if primaryAccount?.source_url}+ {#if sourceUrl}<p class="source-line"><span class="source-label">{$t("settings.cookies.captured_from")}</span>- <button type="button" class="source-link" onclick={openSourceUrl} title={primaryAccount.source_url}>- {primaryAccount.source_url}+ <button type="button" class="source-link" onclick={openSourceUrl} title={sourceUrl}>+ {sourceUrl}</button></p>{/if}@@ -218,6 +250,15 @@{#if primaryAccount}<div class="actions">+ {#if onToggleSelection}+ <label class="select-account">+ <input+ type="checkbox"+ checked={!!selected[keyFor(primaryAccount.slug)]}+ onchange={(e) => onToggleSelection?.(bucket.domain, primaryAccount.slug, e.currentTarget.checked)}+ />+ </label>+ {/if}<button type="button" class="ghost-btn" onclick={() => onView(bucket.domain, primaryAccount.slug)}>{$t("settings.cookies.action_view")}</button>@@ -248,7 +289,16 @@{#if extraAccounts.length > 0}<ul class="extra-accounts">{#each extraAccounts as account (account.slug)}- <li class="extra-account">+ <li class="extra-account" class:selectable={!!onToggleSelection}>+ {#if onToggleSelection}+ <label class="select-extra">+ <input+ type="checkbox"+ checked={!!selected[keyFor(account.slug)]}+ onchange={(e) => onToggleSelection?.(bucket.domain, account.slug, e.currentTarget.checked)}+ />+ </label>+ {/if}<span class="extra-alias">{account.alias}</span><span class="extra-count">{$t("settings.cookies.count_cookies", { count: String(account.cookie_count) })}</span><div class="extra-actions">@@ -409,6 +459,20 @@gap: 6px;margin-top: 8px;flex-wrap: wrap;+ align-items: center;+ }+ .select-account,+ .select-extra {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ }+ .select-account input,+ .select-extra input {+ width: 15px;+ height: 15px;+ accent-color: var(--accent);+ cursor: pointer;}.ghost-btn {padding: 5px 12px;@@ -457,6 +521,9 @@padding: 4px 0;font-size: 12px;}+ .extra-account.selectable {+ grid-template-columns: auto 1fr auto auto;+ }.extra-alias {color: var(--secondary);overflow: hidden;diff --git a/src/lib/stores/download-listener.ts b/src/lib/stores/download-listener.tsindex d7ceb773..d09aeb6b 100644--- a/src/lib/stores/download-listener.ts+++ b/src/lib/stores/download-listener.ts@@ -140,7 +140,9 @@ type UdemyCompletePayload = {const seenCourseIds = new Set<number>();const seenUdemyCourseIds = new Set<number>();const loggedQueueTerminal = new Set<number>();+const queueToastEligibleIds = new Set<number>();const seenGenericIds = new Set<number>();+let queueStateInitialized = false;let throttleTimer: ReturnType<typeof setTimeout> | null = null;let pendingPayload: QueueItemInfo[] | null = null;@@ -260,16 +262,39 @@ export async function initDownloadListener(): Promise<() => void> {"queue-state-update",(event) => {const payload = event.payload;+ if (!queueStateInitialized) {+ for (const item of payload) {+ if (item.status.type === "Complete" || item.status.type === "Error") {+ loggedQueueTerminal.add(item.id);+ } else {+ queueToastEligibleIds.add(item.id);+ }+ }+ queueStateInitialized = true;+ throttledSyncQueueState(payload);+ return;+ }+for (const item of payload) {+ if (item.status.type !== "Complete" && item.status.type !== "Error") {+ queueToastEligibleIds.add(item.id);+ continue;+ }if (loggedQueueTerminal.has(item.id)) continue;+ if (!queueToastEligibleIds.has(item.id)) {+ loggedQueueTerminal.add(item.id);+ continue;+ }if (item.status.type === "Error") {loggedQueueTerminal.add(item.id);+ queueToastEligibleIds.delete(item.id);const errMsg = typeof item.status.data === "string"? item.status.data: (item.status.data as { message?: string } | undefined)?.message;addLog("error", "download", `Download error: ${item.title}`, errMsg ?? undefined);} else if (item.status.type === "Complete") {loggedQueueTerminal.add(item.id);+ queueToastEligibleIds.delete(item.id);addLog("info", "download", `Download complete: ${item.title}`, item.file_path ?? undefined);const tr = get(t);showToast("success", tr("toast.generic_download_complete", { name: item.title }));@@ -290,6 +315,7 @@ export async function initDownloadListener(): Promise<() => void> {seenGenericIds.add(d.id);addLog("info", "download", `Download started: ${d.title}`, `Platform: ${d.platform}`);}+ queueToastEligibleIds.add(d.id);upsertGenericProgress(d.id,d.title,diff --git a/src/routes/+page.svelte b/src/routes/+page.svelteindex 751f8347..2c4ae1a9 100644--- a/src/routes/+page.svelte+++ b/src/routes/+page.svelte@@ -1051,7 +1051,7 @@{@const playlistBlocked = omniState.info.content_type === "playlist" && playlistEntries.length > 0 && selectedPlaylistItems.size === 0}{@const torrentBlocked = torrentEntries.length > 0 && selectedTorrentFiles.size === 0}{#if omniState.info.platform === "bilibili"}- <BilibiliPreviewExtras {url} accountSlug={selectedCookieSlug && !selectedCookieSlug.startsWith("_") ? selectedCookieSlug : null} />+ <BilibiliPreviewExtras {url} accountSlug={selectedCookieSlug} />{/if}<button class="download-primary-btn" disabled={playlistBlocked || torrentBlocked} onclick={handleAction}>{$t('omnibox.download')}