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
B47 + B48 + B41: add CI, sanitise plugin_id, fall back on SABR (#204)
antonio5db7ab1150f0
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlnew file mode 100644index 00000000..0bb5ec4b--- /dev/null+++ b/.github/workflows/ci.yml@@ -0,0 +1,127 @@+name: CI++on:+ push:+ branches: [main]+ pull_request:++concurrency:+ group: ci-${{ github.ref }}+ cancel-in-progress: true++jobs:+ rust:+ if: ${{ github.event_name != 'pull_request' || github.event.pull_request.user.login != 'weblate' }}+ strategy:+ fail-fast: false+ matrix:+ platform: [ubuntu-latest, windows-latest, macos-latest]+ runs-on: ${{ matrix.platform }}+ steps:+ - uses: actions/checkout@v4++ - name: Install Linux system dependencies+ if: matrix.platform == 'ubuntu-latest'+ run: |+ sudo apt-get update+ sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev++ - uses: dtolnay/rust-toolchain@stable+ with:+ components: rustfmt, clippy++ - uses: Swatinem/rust-cache@v2+ with:+ workspaces: './src-tauri'++ - name: Format+ if: matrix.platform == 'ubuntu-latest'+ working-directory: src-tauri+ run: cargo fmt --all -- --check++ # Informativo por enquanto: o workspace tem warnings pre-existentes, entao+ # `-D warnings` reprovaria toda PR no primeiro dia. Fica visivel no log; ver+ # docs/backlog.md B47 para o baseline que torna isso um portao de verdade.+ - name: Clippy+ working-directory: src-tauri+ run: cargo clippy --workspace --all-targets++ - name: Test+ working-directory: src-tauri+ run: cargo test --workspace++ rust-debian:+ if: ${{ github.event_name != 'pull_request' || github.event.pull_request.user.login != 'weblate' }}+ runs-on: ubuntu-latest+ container: debian:bookworm+ steps:+ - name: Install base tools+ run: |+ apt-get update+ apt-get install -y --no-install-recommends \+ ca-certificates curl wget git build-essential pkg-config \+ libssl-dev file unzip xz-utils++ - uses: actions/checkout@v4++ - name: Install Debian system dependencies+ run: |+ apt-get install -y --no-install-recommends \+ libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev \+ patchelf xdg-utils++ - uses: dtolnay/rust-toolchain@stable++ - uses: Swatinem/rust-cache@v2+ with:+ workspaces: './src-tauri'+ key: debian++ - name: Cargo check (Debian compat)+ working-directory: src-tauri+ run: cargo check --workspace --all-targets++ frontend:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4++ - uses: actions/setup-node@v4+ with:+ node-version: lts/*++ - uses: pnpm/action-setup@v4++ - name: Install dependencies+ run: pnpm install --frozen-lockfile++ # Este e o portao que faltava: `pnpm check` sai com 1 em erro de tipo, que+ # foi exatamente o que passou despercebido na PR #197.+ - name: svelte-check+ run: pnpm check++ - name: Unit tests (vitest)+ run: pnpm test++ # `--strict` reprova quando algum locale esta fora de sincronia com en.json.+ - name: Locales in sync with en.json+ run: pnpm check:i18n++ - name: Generated i18n keys are committed+ run: |+ pnpm generate:i18n-keys+ git diff --exit-code -- src/lib/i18n/keys.ts++ metainfo:+ if: ${{ github.event_name != 'pull_request' || github.event.pull_request.user.login != 'weblate' }}+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4++ - name: Install appstreamcli+ run: |+ sudo apt-get update+ sudo apt-get install -y appstream++ - name: Validate flatpak metainfo+ run: appstreamcli validate flatpak/wtf.tonho.omniget.metainfo.xmldiff --git a/.gitignore b/.gitignoreindex 219e1cf7..c21833da 100644--- a/.gitignore+++ b/.gitignore@@ -25,10 +25,12 @@ src-tauri/gen/schemas.DS_StoreThumbs.dbDesktop.ini-/docs+# /docs e /.github contem arquivos do projeto (docs/backlog.md,+# docs/plugin-development.md, .github/workflows/). Ignora-los inteiros fazia+# qualquer arquivo novo falhar em silencio no `git add` — os que existem hoje+# so entraram com `git add -f`. Ignorar apenas o que e de fato local.settings.local.json/.claude-/.githubclaude.mddiff --git a/docs/backlog.md b/docs/backlog.mdindex 81b75e4f..6be19924 100644--- a/docs/backlog.md+++ b/docs/backlog.md@@ -5,10 +5,15 @@ Itens abertos por ordem de retorno. Numeração contínua; concluídos não são**Legenda.** Custo P/M/G · Impacto 1–5 · Status: `aberto` · `bloqueado` · `em análise`**Concluído em v0.7.7:** B21–B31 (11 itens).+**Concluído e aguardando release:** B47, B48, B41.----## Onda proposta — v0.7.8+## Onda v0.7.8 — concluída, aguardando release++B47, B48 e B41 entregues na branch `feat/ci-and-hardening`. Portões: clippy no baseline (34/42/8/1), 460 testes (era 456), `pnpm check` 0 erros / 107 warnings.++### Escopo originalDuas correções baratas com impacto real, mais a rede de proteção que impede a próxima PR de entrar quebrada. Ordem de entrada: B47 → B48 → B41.@@ -16,7 +21,7 @@ Duas correções baratas com impacto real, mais a rede de proteção que impede### B47 — Ter CI-**Status:** aberto · **Custo:** P · **Impacto:** 5 · **Pré-requisito de tudo**+**Status:** concluído · **Custo:** P · **Impacto:** 5 · **Pré-requisito de tudo****Problema.** Não existe CI neste repositório. Nenhum `pnpm check`, nenhum `cargo test`, nenhum `cargo clippy` roda em PR. Só `release.yml` está versionado.@@ -38,7 +43,7 @@ Duas correções baratas com impacto real, mais a rede de proteção que impede### B48 — Sanitizar `plugin_id` antes do `remove_dir_all`-**Status:** aberto · **Custo:** P · **Impacto:** 5 · **Segurança — prevenção**+**Status:** concluído · **Custo:** P · **Impacto:** 5 · **Segurança — prevenção****Problema.** `plugin_loader.rs:193` faz `join(plugin_id)` cru e apaga o resultado com `remove_dir_all`. Um id contendo `..` escapa do diretório de plugins e deleta caminho arbitrário.@@ -56,7 +61,7 @@ Ainda assim **não é release de segurança isolada**: explorar exige compromete### B41 — Cascata de client do YouTube (SABR)-**Status:** aberto · **Custo:** P · **Impacto:** 5 · **Melhor razão custo/impacto da lista**+**Status:** concluído · **Custo:** P · **Impacto:** 5 · **Melhor razão custo/impacto da lista****Problema.** O extractor `web` passou a devolver formatos SABR-only que quebram o caminho normal de download. O usuário vê falha sem causa legível.diff --git a/package.json b/package.jsonindex 6b9d4356..b21beb7c 100644--- a/package.json+++ b/package.json@@ -13,7 +13,7 @@"tauri": "tauri","version:set": "node scripts/bump-version.js","generate:i18n-keys": "node scripts/generate-i18n-keys.js",- "sync:locales": "node scripts/sync-locales.mjs",+ "check:i18n": "node scripts/generate-i18n-keys.js --strict","plugins:deploy": "node scripts/deploy-plugins-local.mjs","extension:sync": "node browser-extension/sync.mjs","test": "vitest run",diff --git a/src-tauri/omniget-cli/src/commands/batch.rs b/src-tauri/omniget-cli/src/commands/batch.rsindex 1a23a7eb..c60a3234 100644--- a/src-tauri/omniget-cli/src/commands/batch.rs+++ b/src-tauri/omniget-cli/src/commands/batch.rs@@ -4,7 +4,12 @@ use tokio::sync::Semaphore;use crate::output;-pub async fn execute(file: String, max_concurrent: usize, output_dir: Option<String>, proxy: Option<String>) -> Result<()> {+pub async fn execute(+ file: String,+ max_concurrent: usize,+ output_dir: Option<String>,+ proxy: Option<String>,+) -> Result<()> {let content = tokio::fs::read_to_string(&file).await.with_context(|| format!("Failed to read {}", file))?;@@ -22,7 +27,10 @@ pub async fn execute(file: String, max_concurrent: usize, output_dir: Option<Strlet total = urls.len();if !output::is_json_mode() {- println!("Batch downloading {} URLs (max concurrent: {})", total, max_concurrent);+ println!(+ "Batch downloading {} URLs (max concurrent: {})",+ total, max_concurrent+ );}let semaphore = Arc::new(Semaphore::new(max_concurrent));@@ -58,7 +66,10 @@ pub async fn execute(file: String, max_concurrent: usize, output_dir: Option<Str}if output::is_json_mode() {- println!(r#"{{"total":{},"success":{},"failed":{}}}"#, total, success, failed);+ println!(+ r#"{{"total":{},"success":{},"failed":{}}}"#,+ total, success, failed+ );} else {println!("Done: {} ok, {} failed", success, failed);}diff --git a/src-tauri/omniget-cli/src/commands/common.rs b/src-tauri/omniget-cli/src/commands/common.rsindex 3f38823b..835fd2f4 100644--- a/src-tauri/omniget-cli/src/commands/common.rs+++ b/src-tauri/omniget-cli/src/commands/common.rs@@ -10,8 +10,8 @@ use omniget_core::models::settings::ProxySettings;use omniget_core::platforms::{BilibiliDownloader, BlueskyDownloader, DirectFileDownloader, DouyinDownloader,GenericYtdlpDownloader, InstagramDownloader, P2pDownloader, PinterestDownloader,- PlatformDownloader, RedditDownloader,- TikTokDownloader, TwitchClipsDownloader, TwitterDownloader, VimeoDownloader, YouTubeDownloader,+ PlatformDownloader, RedditDownloader, TikTokDownloader, TwitchClipsDownloader,+ TwitterDownloader, VimeoDownloader, YouTubeDownloader,};use tokio_util::sync::CancellationToken;diff --git a/src-tauri/omniget-cli/src/commands/import_cookies.rs b/src-tauri/omniget-cli/src/commands/import_cookies.rsindex d6d2eafb..8e59d98e 100644--- a/src-tauri/omniget-cli/src/commands/import_cookies.rs+++ b/src-tauri/omniget-cli/src/commands/import_cookies.rs@@ -12,9 +12,7 @@ pub async fn execute(file: String, name: Option<String>, dry_run: bool) -> Resulif output::is_json_mode() {let items: Vec<serde_json::Value> = preview.iter()- .map(|(domain, count)| {- serde_json::json!({ "domain": domain, "cookies": count })- })+ .map(|(domain, count)| serde_json::json!({ "domain": domain, "cookies": count })).collect();output::print_json(&serde_json::json!({ "domains": items }));} else {@@ -37,7 +35,9 @@ pub async fn execute(file: String, name: Option<String>, dry_run: bool) -> Resulprintln!(r#"{{"success":true,"total":{},"destination":"{}"}}"#,total,- dest.as_deref().map(|p| p.display().to_string()).unwrap_or_default()+ dest.as_deref()+ .map(|p| p.display().to_string())+ .unwrap_or_default());} else {if let Some(d) = &dest {diff --git a/src-tauri/omniget-cli/src/cookies.rs b/src-tauri/omniget-cli/src/cookies.rsindex 2a6a96f5..7f94b4d7 100644--- a/src-tauri/omniget-cli/src/cookies.rs+++ b/src-tauri/omniget-cli/src/cookies.rs@@ -2,8 +2,8 @@ use anyhow::{Context, Result};use std::collections::HashMap;use std::path::PathBuf;-use omniget_core::core::paths::app_data_dir;use omniget_core::core::cookie_parser::parse_cookie_input;+use omniget_core::core::paths::app_data_dir;const COOKIES_DIR: &str = "cookies";const DEFAULT_COOKIE_FILE: &str = "cookies.txt";diff --git a/src-tauri/omniget-cli/src/main.rs b/src-tauri/omniget-cli/src/main.rsindex 14dd4fc4..c24a3793 100644--- a/src-tauri/omniget-cli/src/main.rs+++ b/src-tauri/omniget-cli/src/main.rs@@ -40,9 +40,7 @@ enum Commands {format: Option<String>,},/// Preview media info without downloading- Info {- url: String,- },+ Info { url: String },/// Batch download from a file (one URL per line)Batch {file: String,@@ -89,7 +87,8 @@ async fn main() -> anyhow::Result<()> {subs,format,} => {- commands::download::execute(url, quality, output, audio_only, subs, format, cli.proxy).await?;+ commands::download::execute(url, quality, output, audio_only, subs, format, cli.proxy)+ .await?;}Commands::Info { url } => {commands::info::execute(url, cli.proxy).await?;@@ -101,7 +100,11 @@ async fn main() -> anyhow::Result<()> {} => {commands::batch::execute(file, max_concurrent, output, cli.proxy).await?;}- Commands::ImportCookies { file, name, dry_run } => {+ Commands::ImportCookies {+ file,+ name,+ dry_run,+ } => {commands::import_cookies::execute(file, name, dry_run).await?;}}diff --git a/src-tauri/omniget-cli/src/reporter.rs b/src-tauri/omniget-cli/src/reporter.rsindex 9fc68adc..154901f3 100644--- a/src-tauri/omniget-cli/src/reporter.rs+++ b/src-tauri/omniget-cli/src/reporter.rs@@ -17,13 +17,20 @@ pub struct CliReporter {impl CliReporter {pub fn new(json_mode: bool) -> Self {let pb = ProgressBar::new(100);- pb.set_style(ProgressStyle::default_bar().template(SPINNER_STYLE).unwrap());+ pb.set_style(+ ProgressStyle::default_bar()+ .template(SPINNER_STYLE)+ .unwrap(),+ );Self { pb, json_mode }}pub fn message(&self, msg: &str) {if self.json_mode {- println!(r#"{{"type":"message","content":"{}"}}"#, msg.replace('"', "\\\""));+ println!(+ r#"{{"type":"message","content":"{}"}}"#,+ msg.replace('"', "\\\"")+ );} else {self.pb.set_message(msg.to_string());}@@ -42,7 +49,8 @@ impl CliReporter {println!("{}", json);} else {if update.percent >= 0.0 {- self.pb.set_position(update.percent.clamp(0.0, 100.0).round() as u64);+ self.pb+ .set_position(update.percent.clamp(0.0, 100.0).round() as u64);self.pb.set_style(ProgressStyle::default_bar().template(PROGRESS_STYLE)diff --git a/src-tauri/omniget-core/src/core/dependencies.rs b/src-tauri/omniget-core/src/core/dependencies.rsindex 8df3237b..30e30f2d 100644--- a/src-tauri/omniget-core/src/core/dependencies.rs+++ b/src-tauri/omniget-core/src/core/dependencies.rs@@ -925,9 +925,19 @@ mod integrity_tests {// Regressao: a versao anterior usava `?` dentro do laco, entao a// primeira linha vazia ou de um token so abortava a funcao inteira e o// asset seguinte nunca era encontrado -> instalacao sem verificacao.- let sums = format!("\n\ncomentario\n{} yt-dlp.exe\n\n{} yt-dlp_macos\n", VAZIO, "1".repeat(64));- assert_eq!(parse_sha256sums(&sums, "yt-dlp.exe").as_deref(), Some(VAZIO));- assert_eq!(parse_sha256sums(&sums, "yt-dlp_macos").as_deref(), Some("1".repeat(64).as_str()));+ let sums = format!(+ "\n\ncomentario\n{} yt-dlp.exe\n\n{} yt-dlp_macos\n",+ VAZIO,+ "1".repeat(64)+ );+ assert_eq!(+ parse_sha256sums(&sums, "yt-dlp.exe").as_deref(),+ Some(VAZIO)+ );+ assert_eq!(+ parse_sha256sums(&sums, "yt-dlp_macos").as_deref(),+ Some("1".repeat(64).as_str())+ );assert_eq!(parse_sha256sums(&sums, "ausente"), None);}@@ -936,12 +946,18 @@ mod integrity_tests {let bin = format!("{} *ffmpeg.zip\n", VAZIO);assert_eq!(parse_sha256sums(&bin, "ffmpeg.zip").as_deref(), Some(VAZIO));assert_eq!(parse_sha256sums("abc yt-dlp.exe\n", "yt-dlp.exe"), None);- assert_eq!(parse_sha256sums(&format!("{} yt-dlp.exe\n", "z".repeat(64)), "yt-dlp.exe"), None);+ assert_eq!(+ parse_sha256sums(&format!("{} yt-dlp.exe\n", "z".repeat(64)), "yt-dlp.exe"),+ None+ );}#[test]fn digest_da_api_do_github() {- assert_eq!(parse_github_digest(&format!("sha256:{}", VAZIO)).as_deref(), Some(VAZIO));+ assert_eq!(+ parse_github_digest(&format!("sha256:{}", VAZIO)).as_deref(),+ Some(VAZIO)+ );assert_eq!(parse_github_digest(VAZIO), None);assert_eq!(parse_github_digest("sha512:abc"), None);}diff --git a/src-tauri/omniget-core/src/core/hls_downloader.rs b/src-tauri/omniget-core/src/core/hls_downloader.rsindex 0a135e7a..41cadc58 100644--- a/src-tauri/omniget-core/src/core/hls_downloader.rs+++ b/src-tauri/omniget-core/src/core/hls_downloader.rs@@ -442,10 +442,7 @@ struct EncryptionInfo {/// Attach `Referer` (and a matching `Origin`) headers to a request./// An empty referer means "send no Referer/Origin at all" — some CDNs/// reject requests with a wrong Referer but accept ones without any.-fn apply_referer_headers(- req: reqwest::RequestBuilder,- referer: &str,-) -> reqwest::RequestBuilder {+fn apply_referer_headers(req: reqwest::RequestBuilder, referer: &str) -> reqwest::RequestBuilder {if referer.is_empty() {return req;}diff --git a/src-tauri/omniget-core/src/core/http_fetcher.rs b/src-tauri/omniget-core/src/core/http_fetcher.rsindex 05f82712..9b7d1ad0 100644--- a/src-tauri/omniget-core/src/core/http_fetcher.rs+++ b/src-tauri/omniget-core/src/core/http_fetcher.rs@@ -466,13 +466,7 @@ impl HttpFetcher {(s > 0.0 && total > dl).then(|| ((total - dl) as f64 / s) as u64)});let _ = progress_tx- .send(ProgressUpdate::rich(- pct,- Some(dl),- Some(total),- speed,- eta,- ))+ .send(ProgressUpdate::rich(pct, Some(dl), Some(total), speed, eta)).await;last_emit = std::time::Instant::now();}diff --git a/src-tauri/omniget-core/src/core/ytdlp.rs b/src-tauri/omniget-core/src/core/ytdlp.rsindex 8b1b8648..be8813dd 100644--- a/src-tauri/omniget-core/src/core/ytdlp.rs+++ b/src-tauri/omniget-core/src/core/ytdlp.rs@@ -64,6 +64,28 @@ static SPONSORBLOCK_CATEGORIES_FN: OnceLock<SponsorBlockCategoriesFn> = OnceLock/// yt-dlp removeu esse suporte na 2026.06.09 e recomenda `-N` no lugar.pub(crate) const ARIA2C_ALLOWED_PROTOCOLS: &str = "http,ftp";+/// Ordem de fallback de `player_client` quando o YouTube devolve formato+/// SABR-only.+///+/// O extractor `web` passou a entregar formatos que o caminho normal de+/// download nao consegue puxar. Estes quatro clients ainda servem URL+/// progressiva; a ordem vai do mais confiavel ao mais restrito.+pub(crate) const SABR_CLIENT_CASCADE: [&str; 4] = ["android", "ios", "tv", "web_safari"];++/// `Some(arg)` quando o stderr indica formato SABR-only e ainda resta client na+/// cascata; `None` quando nao e SABR ou a cascata se esgotou.+///+/// Separado do laco de retry de proposito: e o unico jeito de testar a decisao+/// com stderr real capturado como fixture, sem subir um download.+pub(crate) fn sabr_fallback_client(stderr_lower: &str, attempt: usize) -> Option<String> {+ if !stderr_lower.contains("sabr") {+ return None;+ }+ SABR_CLIENT_CASCADE+ .get(attempt)+ .map(|client| format!("youtube:player_client={client}"))+}+/// Piso de versão do yt-dlp. 2026.06.09 é a release que corrigiu/// CVE-2026-50019 (vazamento de cookie no downloader curl), CVE-2026-50023/// (escrita de `.desktop`/`.url`/`.webloc`) e CVE-2026-50574 (execução@@ -989,7 +1011,6 @@ fn ytdlp_release_base(channel: YtdlpChannel) -> &'static str {use crate::core::dependencies::integrity;-async fn download_ytdlp_binary() -> anyhow::Result<PathBuf> {let target =managed_ytdlp_path().ok_or_else(|| anyhow!("Could not determine data directory"))?;@@ -1390,23 +1411,22 @@ pub async fn get_video_info(attempt + 1);- let result =- tokio::time::timeout(- std::time::Duration::from_secs(VIDEO_INFO_PROCESS_TIMEOUT_SECS),- child.wait_with_output(),+ let result = tokio::time::timeout(+ std::time::Duration::from_secs(VIDEO_INFO_PROCESS_TIMEOUT_SECS),+ child.wait_with_output(),+ )+ .await+ .map_err(|_| {+ tracing::debug!("[perf] get_video_info took {:?}", _timer_start.elapsed());+ anyhow!(+ "Timeout fetching video info ({}s)",+ VIDEO_INFO_PROCESS_TIMEOUT_SECS)- .await- .map_err(|_| {- tracing::debug!("[perf] get_video_info took {:?}", _timer_start.elapsed());- anyhow!(- "Timeout fetching video info ({}s)",- VIDEO_INFO_PROCESS_TIMEOUT_SECS- )- })?- .map_err(|e| {- tracing::debug!("[perf] get_video_info took {:?}", _timer_start.elapsed());- anyhow!("Failed to run yt-dlp: {}", e)- })?;+ })?+ .map_err(|e| {+ tracing::debug!("[perf] get_video_info took {:?}", _timer_start.elapsed());+ anyhow!("Failed to run yt-dlp: {}", e)+ })?;tracing::debug!("[perf] get_video_info: yt-dlp process exited at {:?} (attempt {})",@@ -2787,6 +2807,19 @@ pub async fn download_video(tracing::warn!("[yt-dlp] nsig error, switching to {}", client);}+ if is_youtube_url(url) {+ if let Some(client) = sabr_fallback_client(&stderr_lower, attempt) {+ base_args.retain(|a| a != "--extractor-args" && !a.contains("player_client"));+ extra_args.retain(|a| a != "--extractor-args" && !a.contains("player_client"));+ extra_args.push("--extractor-args".to_string());+ extra_args.push(client.clone());+ tracing::warn!(+ "[yt-dlp] SABR-only formats detected, switching player_client to {}",+ client+ );+ }+ }+if (stderr_lower.contains("http error 403") || stderr_lower.contains("forbidden"))&& !extra_args.contains(&"--force-ipv4".to_string()){@@ -2927,10 +2960,16 @@ async fn convert_vtt_sidecars_to_srt(video_path: &Path) {.await;match result {Ok(out) if out.status.success() => {- tracing::info!("[yt-dlp] converted subtitle sidecar {} to srt (vtt kept)", name);+ tracing::info!(+ "[yt-dlp] converted subtitle sidecar {} to srt (vtt kept)",+ name+ );}_ => {- tracing::warn!("[yt-dlp] failed to convert subtitle sidecar {} to srt", name);+ tracing::warn!(+ "[yt-dlp] failed to convert subtitle sidecar {} to srt",+ name+ );let _ = std::fs::remove_file(&srt_path);}}@@ -3545,10 +3584,12 @@ mod tests {// Bilibili cheese season entries are full info dicts with webpage_url// but no top-level "url" (issue #157).let dump = r#"{"id":"12345","title":"Lesson 1","webpage_url":"https://www.bilibili.com/cheese/play/ep12345","extractor_key":"BiliBiliCheese"}"#;- let (_, entries) =- parse_playlist_dump(dump, "https://www.bilibili.com/cheese/play/ss999");+ let (_, entries) = parse_playlist_dump(dump, "https://www.bilibili.com/cheese/play/ss999");assert_eq!(entries.len(), 1);- assert_eq!(entries[0].url, "https://www.bilibili.com/cheese/play/ep12345");+ assert_eq!(+ entries[0].url,+ "https://www.bilibili.com/cheese/play/ep12345"+ );}#[test]@@ -3556,25 +3597,27 @@ mod tests {let dump = r#"{"id":"dQw4w9WgXcQ","title":"YT Video","ie_key":"Youtube"}"#;let (_, entries) = parse_playlist_dump(dump, "https://example.com/playlist");assert_eq!(entries.len(), 1);- assert_eq!(entries[0].url, "https://www.youtube.com/watch?v=dQw4w9WgXcQ");+ assert_eq!(+ entries[0].url,+ "https://www.youtube.com/watch?v=dQw4w9WgXcQ"+ );}#[test]fn playlist_dump_fabricates_youtube_url_for_youtube_source() {let dump = r#"{"id":"dQw4w9WgXcQ","title":"YT Video"}"#;- let (_, entries) = parse_playlist_dump(- dump,- "https://www.youtube.com/playlist?list=PL123",- );+ let (_, entries) = parse_playlist_dump(dump, "https://www.youtube.com/playlist?list=PL123");assert_eq!(entries.len(), 1);- assert_eq!(entries[0].url, "https://www.youtube.com/watch?v=dQw4w9WgXcQ");+ assert_eq!(+ entries[0].url,+ "https://www.youtube.com/watch?v=dQw4w9WgXcQ"+ );}#[test]fn playlist_dump_skips_non_youtube_entry_without_url() {let dump = r#"{"id":"12345","title":"Lesson 1","extractor_key":"BiliBiliCheese"}"#;- let (_, entries) =- parse_playlist_dump(dump, "https://www.bilibili.com/cheese/play/ss999");+ let (_, entries) = parse_playlist_dump(dump, "https://www.bilibili.com/cheese/play/ss999");assert!(entries.is_empty());}@@ -3983,7 +4026,10 @@ e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 yt-dlp.exe\n\let downloader = &args[1];assert!(downloader.starts_with("http,ftp:"), "{downloader}");for proto in ["m3u8", "m3u8_native", "m3u8_frag_urls", "dash_frag_urls"] {- assert!(!downloader.contains(proto), "protocolo {proto} nao pode ir ao aria2c");+ assert!(+ !downloader.contains(proto),+ "protocolo {proto} nao pode ir ao aria2c"+ );}assert_eq!(downloader, "http,ftp:/opt/bin/aria2c");// A chave de --downloader-args e o NOME do downloader, nao o protocolo.@@ -3993,7 +4039,11 @@ e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 yt-dlp.exe\n\#[test]fn aria2c_downloader_args_rejeita_proxy_com_espaco() {let limpo = aria2c_downloader_args("/bin/aria2c", 2, Some("http://127.0.0.1:8080"));- assert!(limpo[3].ends_with("--all-proxy=http://127.0.0.1:8080"), "{}", limpo[3]);+ assert!(+ limpo[3].ends_with("--all-proxy=http://127.0.0.1:8080"),+ "{}",+ limpo[3]+ );let sujo = aria2c_downloader_args("/bin/aria2c", 2, Some("http://h:1 --seed-ratio=0"));assert!(!sujo[3].contains("--all-proxy"), "{}", sujo[3]);assert!(!sujo[3].contains("--seed-ratio"));@@ -4002,7 +4052,11 @@ e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 yt-dlp.exe\n\#[test]fn aria2c_nunca_zera_conexoes() {let args = aria2c_downloader_args("/bin/aria2c", 0, None);- assert!(args[3].contains("-x 1") && args[3].contains("-j 1"), "{}", args[3]);+ assert!(+ args[3].contains("-x 1") && args[3].contains("-j 1"),+ "{}",+ args[3]+ );}// --- Piso de versao do yt-dlp ---@@ -4010,8 +4064,14 @@ e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 yt-dlp.exe\n\#[test]fn parse_ytdlp_version_le_os_formatos_reais() {assert_eq!(parse_ytdlp_version("2026.06.09"), Some((2026, 6, 9)));- assert_eq!(parse_ytdlp_version("2025.12.31.232815"), Some((2025, 12, 31)));- assert_eq!(parse_ytdlp_version("2026.06.10.232815-nightly"), Some((2026, 6, 10)));+ assert_eq!(+ parse_ytdlp_version("2025.12.31.232815"),+ Some((2025, 12, 31))+ );+ assert_eq!(+ parse_ytdlp_version("2026.06.10.232815-nightly"),+ Some((2026, 6, 10))+ );for lixo in ["", "unknown", "1.2", "2026.13.01", "2026.06.99"] {assert_eq!(parse_ytdlp_version(lixo), None, "aceitou {lixo:?}");}@@ -4025,4 +4085,67 @@ e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 yt-dlp.exe\n\// Versao ilegivel nao pode ser reportada como desatualizada.assert_eq!(ytdlp_version_is_supported("sei la"), None);}++ // --- B41: cascata de client acionada por SABR ---++ /// stderr real do yt-dlp quando o cliente `web` devolve formato SABR-only.+ const SABR_STDERR: &str = "WARNING: [youtube] abc123: Some web client https formats have been \+skipped as they are missing a url. YouTube is forcing SABR streaming for this client. \+See https://github.com/yt-dlp/yt-dlp/issues/12482 for more details\n\+ERROR: [youtube] abc123: Requested format is not available";++ #[test]+ fn sabr_no_stderr_dispara_a_cascata_na_ordem() {+ let lower = SABR_STDERR.to_lowercase();+ assert_eq!(+ sabr_fallback_client(&lower, 0).as_deref(),+ Some("youtube:player_client=android")+ );+ assert_eq!(+ sabr_fallback_client(&lower, 1).as_deref(),+ Some("youtube:player_client=ios")+ );+ assert_eq!(+ sabr_fallback_client(&lower, 2).as_deref(),+ Some("youtube:player_client=tv")+ );+ assert_eq!(+ sabr_fallback_client(&lower, 3).as_deref(),+ Some("youtube:player_client=web_safari")+ );+ }++ #[test]+ fn cascata_esgotada_devolve_none_em_vez_de_repetir() {+ let lower = SABR_STDERR.to_lowercase();+ assert_eq!(sabr_fallback_client(&lower, 4), None);+ assert_eq!(sabr_fallback_client(&lower, 99), None);+ }++ #[test]+ fn erro_que_nao_e_sabr_nao_troca_de_client() {+ // Regressao: trocar de client em qualquer falha mascararia a causa real+ // e gastaria as tentativas de retry a toa.+ for stderr in [+ "error: [youtube] abc: video unavailable",+ "error: http error 429: too many requests",+ "error: [youtube] abc: nsig extraction failed",+ "error: unable to download webpage: timed out",+ "",+ ] {+ assert_eq!(+ sabr_fallback_client(stderr, 0),+ None,+ "trocou de client sem SABR: {stderr:?}"+ );+ }+ }++ #[test]+ fn a_cascata_nao_contem_o_client_que_causa_o_problema() {+ // `web` e `default` sao justamente os que devolvem SABR-only.+ assert!(!SABR_CLIENT_CASCADE.contains(&"web"));+ assert!(!SABR_CLIENT_CASCADE.contains(&"default"));+ assert_eq!(SABR_CLIENT_CASCADE.len(), 4);+ }}diff --git a/src-tauri/omniget-core/src/platforms/bluesky.rs b/src-tauri/omniget-core/src/platforms/bluesky.rsindex e54b4d74..d41077d6 100644--- a/src-tauri/omniget-core/src/platforms/bluesky.rs+++ b/src-tauri/omniget-core/src/platforms/bluesky.rs@@ -1,6 +1,6 @@+use crate::models::progress::ProgressUpdate;use anyhow::anyhow;use async_trait::async_trait;-use crate::models::progress::ProgressUpdate;use tokio::sync::mpsc;use crate::core::direct_downloader;diff --git a/src-tauri/omniget-core/src/platforms/direct_file.rs b/src-tauri/omniget-core/src/platforms/direct_file.rsindex 3ba4b612..ec274203 100644--- a/src-tauri/omniget-core/src/platforms/direct_file.rs+++ b/src-tauri/omniget-core/src/platforms/direct_file.rs@@ -6,9 +6,7 @@ use tokio::sync::mpsc;use crate::core::direct_downloader;use crate::core::http_client;-use crate::models::media::{- DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality,-};+use crate::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};pub struct DirectFileDownloader;@@ -117,11 +115,12 @@ impl PlatformDownloader for DirectFileDownloader {builder = builder.user_agent(ua);}- let jar = crate::core::cookie_parser::load_extension_cookies_for_url(file_url).or_else(|| {- opts.referer- .as_deref()- .and_then(crate::core::cookie_parser::load_extension_cookies_for_url)- });+ let jar =+ crate::core::cookie_parser::load_extension_cookies_for_url(file_url).or_else(|| {+ opts.referer+ .as_deref()+ .and_then(crate::core::cookie_parser::load_extension_cookies_for_url)+ });if let Some(jar) = jar {builder = builder.cookie_provider(jar);}diff --git a/src-tauri/omniget-core/src/platforms/instagram.rs b/src-tauri/omniget-core/src/platforms/instagram.rsindex 7c9b8509..cc4efd41 100644--- a/src-tauri/omniget-core/src/platforms/instagram.rs+++ b/src-tauri/omniget-core/src/platforms/instagram.rs@@ -1,6 +1,6 @@+use crate::models::progress::ProgressUpdate;use anyhow::anyhow;use async_trait::async_trait;-use crate::models::progress::ProgressUpdate;use rand::RngExt;use regex::Regex;use tokio::sync::mpsc;diff --git a/src-tauri/omniget-core/src/platforms/p2p.rs b/src-tauri/omniget-core/src/platforms/p2p.rsindex 2599db84..7da6fab4 100644--- a/src-tauri/omniget-core/src/platforms/p2p.rs+++ b/src-tauri/omniget-core/src/platforms/p2p.rs@@ -1,5 +1,3 @@--use crate::models::progress::ProgressUpdate;use std::path::PathBuf;use std::sync::Arc;diff --git a/src-tauri/omniget-core/src/platforms/reddit.rs b/src-tauri/omniget-core/src/platforms/reddit.rsindex 2dc4518c..241ca54a 100644--- a/src-tauri/omniget-core/src/platforms/reddit.rs+++ b/src-tauri/omniget-core/src/platforms/reddit.rs@@ -1,6 +1,6 @@+use crate::models::progress::ProgressUpdate;use anyhow::anyhow;use async_trait::async_trait;-use crate::models::progress::ProgressUpdate;use tokio::sync::mpsc;use crate::core::direct_downloader;diff --git a/src-tauri/omniget-core/src/platforms/twitch.rs b/src-tauri/omniget-core/src/platforms/twitch.rsindex 9ab7bedd..ee4fff37 100644--- a/src-tauri/omniget-core/src/platforms/twitch.rs+++ b/src-tauri/omniget-core/src/platforms/twitch.rs@@ -1,6 +1,6 @@+use crate::models::progress::ProgressUpdate;use anyhow::anyhow;use async_trait::async_trait;-use crate::models::progress::ProgressUpdate;use tokio::sync::mpsc;use crate::core::direct_downloader;diff --git a/src-tauri/omniget-core/src/platforms/vimeo.rs b/src-tauri/omniget-core/src/platforms/vimeo.rsindex 2ee6fc43..1499d325 100644--- a/src-tauri/omniget-core/src/platforms/vimeo.rs+++ b/src-tauri/omniget-core/src/platforms/vimeo.rs@@ -126,9 +126,9 @@ impl PlatformDownloader for VimeoDownloader {}async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {- let ytdlp_path = ytdlp::ensure_ytdlp().await.map_err(|e| {- anyhow!("Vimeo requires yt-dlp. Failed to get yt-dlp: {}", e)- })?;+ let ytdlp_path = ytdlp::ensure_ytdlp()+ .await+ .map_err(|e| anyhow!("Vimeo requires yt-dlp. Failed to get yt-dlp: {}", e))?;let json = ytdlp::get_video_info(&ytdlp_path, url, &[]).await?;Self::parse_video_info(&json)diff --git a/src-tauri/src/commands/auth_webview.rs b/src-tauri/src/commands/auth_webview.rsindex 858c92f8..280842c4 100644--- a/src-tauri/src/commands/auth_webview.rs+++ b/src-tauri/src/commands/auth_webview.rs@@ -109,8 +109,8 @@ pub async fn open_auth_webview(// Same host, or a subdomain of the login host. The old// bidirectional substring check treated unrelated hosts// (e.g. hotmart.com vs sso.hotmart.com) as a match.- let same_host = nav_host == login_host- || nav_host.ends_with(&format!(".{login_host}"));+ let same_host =+ nav_host == login_host || nav_host.ends_with(&format!(".{login_host}"));if same_host {if nav_path != login_path&& !nav_path.contains("login")diff --git a/src-tauri/src/commands/league/mod.rs b/src-tauri/src/commands/league/mod.rsindex 9834b402..eceafdff 100644--- a/src-tauri/src/commands/league/mod.rs+++ b/src-tauri/src/commands/league/mod.rs@@ -76,8 +76,8 @@ async fn discover_client() -> Option<LcuClient> {let port = extract_arg(line, "app-port").and_then(|p| p.parse::<u16>().ok());let token = extract_arg(line, "remoting-auth-token");if let (Some(port), Some(token)) = (port, token) {- let region = extract_arg(line, "region")- .or_else(|| extract_arg(line, "rso_platform_id"));+ let region =+ extract_arg(line, "region").or_else(|| extract_arg(line, "rso_platform_id"));return Some(LcuClient {port,token,@@ -213,7 +213,12 @@ static IMMUTABLE_CACHE: Lazy<std::collections::VecDeque<String>,std::collections::HashMap<String, Value>,)>,-> = Lazy::new(|| Mutex::new((std::collections::VecDeque::new(), std::collections::HashMap::new())));+> = Lazy::new(|| {+ Mutex::new((+ std::collections::VecDeque::new(),+ std::collections::HashMap::new(),+ ))+});fn cache_kind(path: &str) -> Option<CacheKind> {if path.starts_with("/lol-game-data/assets/") || path == "/lol-perks/v1/perks" {@@ -476,7 +481,13 @@ pub async fn league_stop_matchmaking() -> Result<(), String> {pub async fn league_leave_lobby() -> Result<(), String> {ensure_enabled()?;let client = get_client().await?;- lcu_send(&client, reqwest::Method::DELETE, "/lol-lobby/v2/lobby", None).await?;+ lcu_send(+ &client,+ reqwest::Method::DELETE,+ "/lol-lobby/v2/lobby",+ None,+ )+ .await?;Ok(())}@@ -525,11 +536,7 @@ pub async fn league_live_game() -> Result<Value, String> {.json::<Value>().await.map_err(|e| format!("invalid live client response: {}", e))?;- let players = http- .get(format!("{}/playerlist", base))- .send()- .await- .ok();+ let players = http.get(format!("{}/playerlist", base)).send().await.ok();let players = match players {Some(r) => r.json::<Value>().await.unwrap_or(Value::Null),None => Value::Null,@@ -587,9 +594,7 @@ pub async fn league_game_players() -> Result<Value, String> {let my_puuid = lcu_get_raw(&client, "/lol-summoner/v1/current-summoner").await.ok()- .and_then(|s| {- s.get("puuid").and_then(Value::as_str).map(String::from)- })+ .and_then(|s| s.get("puuid").and_then(Value::as_str).map(String::from)).unwrap_or_default();let game_data = session.get("gameData").cloned().unwrap_or(Value::Null);let team_one: Vec<Value> = game_data@@ -602,9 +607,9 @@ pub async fn league_game_players() -> Result<Value, String> {.and_then(Value::as_array).cloned().unwrap_or_default();- let one_has_me = team_one.iter().any(|m| {- m.get("puuid").and_then(Value::as_str) == Some(my_puuid.as_str())- });+ let one_has_me = team_one+ .iter()+ .any(|m| m.get("puuid").and_then(Value::as_str) == Some(my_puuid.as_str()));for (team, mine) in [(team_one, one_has_me), (team_two, !one_has_me)] {for member in &team {players.push(player_identity(member, mine));@@ -641,9 +646,8 @@ pub async fn league_game_players() -> Result<Value, String> {if let Some(arr) = found.as_array() {for (slot, (idx, g, _)) in to_lookup.iter().enumerate() {let hit = arr.get(slot).or_else(|| {- arr.iter().find(|s| {- s.get("gameName").and_then(Value::as_str) == Some(g.as_str())- })+ arr.iter()+ .find(|s| s.get("gameName").and_then(Value::as_str) == Some(g.as_str()))});if let Some(s) = hit {if let Some(puuid) = s.get("puuid").and_then(Value::as_str) {@@ -657,7 +661,11 @@ pub async fn league_game_players() -> Result<Value, String> {let mut name_tasks = Vec::new();for (i, p) in resolved.iter().enumerate() {- let puuid = p.get("puuid").and_then(Value::as_str).unwrap_or("").to_string();+ let puuid = p+ .get("puuid")+ .and_then(Value::as_str)+ .unwrap_or("")+ .to_string();let has_name = p.get("gameName").and_then(Value::as_str)@@ -727,9 +735,9 @@ fn compute_history_stats(games: &[Value], puuid: &str) -> Value {.and_then(|i| i.get("participantId").and_then(Value::as_i64))});match pid {- Some(pid) => arr.iter().find(|p| {- p.get("participantId").and_then(Value::as_i64) == Some(pid)- }),+ Some(pid) => arr+ .iter()+ .find(|p| p.get("participantId").and_then(Value::as_i64) == Some(pid)),None => arr.first(),}}@@ -750,7 +758,10 @@ fn compute_history_stats(games: &[Value], puuid: &str) -> Value {.get("totalDamageDealtToChampions").and_then(Value::as_f64).unwrap_or(0.0);- total_gold += stats.get("goldEarned").and_then(Value::as_f64).unwrap_or(0.0);+ total_gold += stats+ .get("goldEarned")+ .and_then(Value::as_f64)+ .unwrap_or(0.0);// Slot 1 is the D key, slot 2 the F key; Flash is spell id 4.match (participant.get("spell1Id").and_then(Value::as_i64),@@ -885,9 +896,12 @@ pub async fn league_player_report(// The summoner record states privacy explicitly; an empty history only// means the request came back thin, which is not the same thing.- let summoner = lcu_get_raw(&client, &format!("/lol-summoner/v2/summoners/puuid/{}", puuid))- .await- .unwrap_or(Value::Null);+ let summoner = lcu_get_raw(+ &client,+ &format!("/lol-summoner/v2/summoners/puuid/{}", puuid),+ )+ .await+ .unwrap_or(Value::Null);let is_private = summoner.get("privacy").and_then(Value::as_str)@@ -1010,7 +1024,11 @@ fn ranked_entry_parts(entry: &Value) -> (Option<f64>, u32, u32) {.and_then(Value::as_i64).unwrap_or(0).max(0) as u32;- let wins = entry.get("wins").and_then(Value::as_i64).unwrap_or(0).max(0) as u32;+ let wins = entry+ .get("wins")+ .and_then(Value::as_i64)+ .unwrap_or(0)+ .max(0) as u32;let losses = entry.get("losses").and_then(Value::as_i64)@@ -1076,7 +1094,11 @@ pub async fn league_match_analysis() -> Result<Value, String> {.collect()}).unwrap_or_default();- (index, json!({ "ranked": ranked, "history": history }), game_ids)+ (+ index,+ json!({ "ranked": ranked, "history": history }),+ game_ids,+ )}));}@@ -1094,7 +1116,10 @@ pub async fn league_match_analysis() -> Result<Value, String> {let mut detail: Vec<Value> = Vec::new();for (index, player) in players.iter().enumerate() {- let is_ally = player.get("isAlly").and_then(Value::as_bool).unwrap_or(false);+ let is_ally = player+ .get("isAlly")+ .and_then(Value::as_bool)+ .unwrap_or(false);let data = &fetched[index];let solo = data.get("ranked")@@ -1141,8 +1166,7 @@ pub async fn league_match_analysis() -> Result<Value, String> {enemy_strengths.push(strength);}- let season_shrunk =- stats::shrunk_winrate(season_wins, season_losses, stats::PRIOR_GAMES);+ let season_shrunk = stats::shrunk_winrate(season_wins, season_losses, stats::PRIOR_GAMES);let (wilson_low, wilson_high) =stats::wilson_interval(season_wins, season_losses, stats::Z_90);@@ -1531,9 +1555,7 @@ async fn deep_timeline_stats(client: &LcuClient, puuid: &str, games: &[Value]) -solo_kills += 1;}}- if event.get("victimId").and_then(Value::as_i64) == Some(pid)- && ts <= 900_000- {+ if event.get("victimId").and_then(Value::as_i64) == Some(pid) && ts <= 900_000 {early_deaths += 1;}}@@ -1672,8 +1694,7 @@ pub async fn league_duos(sample: Option<u32>) -> Result<Value, String> {}));}- let mut tally: std::collections::HashMap<String, (u32, u32)> =- std::collections::HashMap::new();+ let mut tally: std::collections::HashMap<String, (u32, u32)> = std::collections::HashMap::new();let mut names: std::collections::HashMap<String, Value> = std::collections::HashMap::new();let mut analysed = 0u32;@@ -1838,10 +1859,8 @@ pub async fn league_jungle_report(puuid: String, sample: Option<u32>) -> Result<let mut analysed = 0u32;let mut invades = 0u32;let mut level3_ganks = 0u32;- let mut first_camps: std::collections::HashMap<String, u32> =- std::collections::HashMap::new();- let mut objectives: std::collections::HashMap<String, u32> =- std::collections::HashMap::new();+ let mut first_camps: std::collections::HashMap<String, u32> = std::collections::HashMap::new();+ let mut objectives: std::collections::HashMap<String, u32> = std::collections::HashMap::new();for task in tasks {let (detail, timeline) = match task.await {@@ -1953,10 +1972,7 @@ pub async fn league_jungle_report(puuid: String, sample: Option<u32>) -> Result<let x = pos.get("x").and_then(Value::as_f64).unwrap_or(-1.0);let y = pos.get("y").and_then(Value::as_f64).unwrap_or(-1.0);if x >= 0.0 && y >= 0.0 {- weights.add(- analysis::classify_zone(x, y),- analysis::KILL_WEIGHT,- );+ weights.add(analysis::classify_zone(x, y), analysis::KILL_WEIGHT);}}}@@ -1974,7 +1990,10 @@ pub async fn league_jungle_report(puuid: String, sample: Option<u32>) -> Result<}if let Some(pf3) = frames.get(3).and_then(frame_participant) {- let cs = (pf3.get("minionsKilled").and_then(Value::as_i64).unwrap_or(0)+ let cs = (pf3+ .get("minionsKilled")+ .and_then(Value::as_i64)+ .unwrap_or(0)+ pf3.get("jungleMinionsKilled").and_then(Value::as_i64)@@ -2146,7 +2165,11 @@ pub async fn league_rune_recommendations(let perks: Vec<i64> = p.get("perks").and_then(Value::as_array)- .map(|a| a.iter().filter_map(|x| x.get("id").and_then(Value::as_i64)).collect())+ .map(|a| {+ a.iter()+ .filter_map(|x| x.get("id").and_then(Value::as_i64))+ .collect()+ }).unwrap_or_default();json!({"recommendationId": p.get("recommendationId"),@@ -2181,7 +2204,9 @@ pub async fn league_champion_tiers(let region = region.unwrap_or_else(|| "br".to_string());let bracket = tier.unwrap_or_else(|| "emerald_plus".to_string());if !region.chars().all(|c| c.is_ascii_alphanumeric())- || !bracket.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')+ || !bracket+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || c == '_'){return Err("invalid region or tier".to_string());}@@ -2258,10 +2283,7 @@ pub async fn league_champion_tiers(/// champion across those games contributes their finished items. The response/// always reports how many games backed it so a thin sample is obvious.#[tauri::command]-pub async fn league_champion_build(- champion_id: i64,- sample: Option<u32>,-) -> Result<Value, String> {+pub async fn league_champion_build(champion_id: i64, sample: Option<u32>) -> Result<Value, String> {ensure_enabled()?;if champion_id <= 0 {return Err("invalid champion".to_string());@@ -2482,7 +2504,10 @@ async fn load_haste_table(http: &reqwest::Client) -> std::collections::HashMap<iif let Some(arr) = items_data.as_array() {for item in arr {let id = item.get("id").and_then(Value::as_i64).unwrap_or(0);- let desc = item.get("description").and_then(Value::as_str).unwrap_or("");+ let desc = item+ .get("description")+ .and_then(Value::as_str)+ .unwrap_or("");let haste = item_ability_haste(desc);if id > 0 && haste > 0 {table.insert(id, haste);@@ -2521,8 +2546,7 @@ pub async fn league_ability_cooldowns() -> Result<Value, String> {let summary = lcu_get_raw(&client, "/lol-game-data/assets/v1/champion-summary.json").await.unwrap_or(Value::Null);- let mut id_by_alias: std::collections::HashMap<String, i64> =- std::collections::HashMap::new();+ let mut id_by_alias: std::collections::HashMap<String, i64> = std::collections::HashMap::new();if let Some(arr) = summary.as_array() {for champ in arr {if let (Some(id), Some(alias)) = (@@ -2567,12 +2591,18 @@ pub async fn league_ability_cooldowns() -> Result<Value, String> {}let mut rows: Vec<Value> = Vec::new();- let mut spell_cache: std::collections::HashMap<i64, Value> =- std::collections::HashMap::new();+ let mut spell_cache: std::collections::HashMap<i64, Value> = std::collections::HashMap::new();for p in &list {- let raw_name = p.get("rawChampionName").and_then(Value::as_str).unwrap_or("");- let alias = raw_name.rsplit('_').next().unwrap_or("").to_ascii_lowercase();+ let raw_name = p+ .get("rawChampionName")+ .and_then(Value::as_str)+ .unwrap_or("");+ let alias = raw_name+ .rsplit('_')+ .next()+ .unwrap_or("")+ .to_ascii_lowercase();let champion_id = id_by_alias.get(&alias).copied().unwrap_or(0);let level = p.get("level").and_then(Value::as_i64).unwrap_or(1);@@ -2652,7 +2682,10 @@ pub async fn league_ability_cooldowns() -> Result<Value, String> {.and_then(|s| s.get(slot)).and_then(|s| s.get("displayName")).and_then(Value::as_str)?;- let (cd, icon) = spell_by_name.get(name).cloned().unwrap_or((0.0, String::new()));+ let (cd, icon) = spell_by_name+ .get(name)+ .cloned()+ .unwrap_or((0.0, String::new()));Some(json!({"name": name,"baseCooldown": cd,@@ -2723,7 +2756,10 @@ pub async fn league_dodge() -> Result<(), String> {pub async fn league_auto_accept_set(enabled: bool) -> Result<(), String> {ensure_enabled()?;AUTO_ACCEPT.store(enabled, Ordering::Relaxed);- tracing::info!("[league] auto-accept {}", if enabled { "on" } else { "off" });+ tracing::info!(+ "[league] auto-accept {}",+ if enabled { "on" } else { "off" }+ );Ok(())}diff --git a/src-tauri/src/commands/league/stats.rs b/src-tauri/src/commands/league/stats.rsindex 9f023cad..ddd9eeff 100644--- a/src-tauri/src/commands/league/stats.rs+++ b/src-tauri/src/commands/league/stats.rs@@ -185,7 +185,11 @@ pub fn player_strength(let base = rank.unwrap_or(UNRANKED_RATING);// Rank is the strong signal; without it we fall back to a wide prior.- let base_sigma = if rank.is_some() { RANK_SIGMA } else { UNKNOWN_SIGMA };+ let base_sigma = if rank.is_some() {+ RANK_SIGMA+ } else {+ UNKNOWN_SIGMA+ };let season_p = shrunk_winrate(season_wins, season_losses, PRIOR_GAMES);let season_delta = winrate_rating_delta(season_p);@@ -234,10 +238,13 @@ pub struct WinProbability {/// Bradley-Terry model with additive strengths. The interval comes from/// propagating each player's variance through the mean and then through the/// logistic — it is wide on purpose when players are unknown.-pub fn team_win_probability(allies: &[PlayerStrength], enemies: &[PlayerStrength]) -> WinProbability {+pub fn team_win_probability(+ allies: &[PlayerStrength],+ enemies: &[PlayerStrength],+) -> WinProbability {let total_players = allies.len() + enemies.len();- let known_players = allies.iter().filter(|p| p.known).count()- + enemies.iter().filter(|p| p.known).count();+ let known_players =+ allies.iter().filter(|p| p.known).count() + enemies.iter().filter(|p| p.known).count();if allies.is_empty() || enemies.is_empty() {return WinProbability {@@ -381,12 +388,7 @@ pub fn contribution_ratio(value: f64, team_total: f64, team_size: usize) -> f64////// Above 1 the player converts less damage into more kills (finishing or/// stealing); below 1 they deal damage others convert. Neutral when unknown.-pub fn kill_damage_efficiency(- kills: u32,- team_kills: u32,- damage: f64,- team_damage: f64,-) -> f64 {+pub fn kill_damage_efficiency(kills: u32, team_kills: u32, damage: f64, team_damage: f64) -> f64 {if team_kills == 0 || team_damage <= 0.0 || damage <= 0.0 {return 1.0;}@@ -432,7 +434,11 @@ pub struct ImpactInput {/// Every component is a bounded ramp, so no single stat can dominate and the/// result stays comparable across roles and game lengths.pub fn impact_score(input: &ImpactInput) -> f64 {- let team_size = if input.team_size == 0 { 5 } else { input.team_size };+ let team_size = if input.team_size == 0 {+ 5+ } else {+ input.team_size+ };// KDA on a square-root curve: the gap from 2 to 5 matters more than 8 to 11.let kda_value = kda(input.kills, input.deaths, input.assists);@@ -598,7 +604,11 @@ mod tests {assert!(close(iron4, RATING_FLOOR, 1e-9));// Silver IV should land near the ladder median used for unranked.let silver4 = rank_rating("SILVER", "IV", 0).unwrap();- assert!((silver4 - UNRANKED_RATING).abs() < 150.0, "silver4={}", silver4);+ assert!(+ (silver4 - UNRANKED_RATING).abs() < 150.0,+ "silver4={}",+ silver4+ );let gold4 = rank_rating("GOLD", "IV", 0).unwrap();let gold1 = rank_rating("GOLD", "I", 75).unwrap();let emerald4 = rank_rating("EMERALD", "IV", 0).unwrap();@@ -626,7 +636,12 @@ mod tests {let ra = winrate_rating_delta(pa);let rb = winrate_rating_delta(pb);let via_elo = elo_expectancy(ra, rb);- assert!(close(via_log5, via_elo, 1e-9), "{} vs {}", via_log5, via_elo);+ assert!(+ close(via_log5, via_elo, 1e-9),+ "{} vs {}",+ via_log5,+ via_elo+ );assert!(close(log5(0.5, 0.5), 0.5, 1e-12));}diff --git a/src-tauri/src/commands/league/ws.rs b/src-tauri/src/commands/league/ws.rsindex 123b6f54..c4f273dd 100644--- a/src-tauri/src/commands/league/ws.rs+++ b/src-tauri/src/commands/league/ws.rs@@ -1,4 +1,4 @@-use super::{get_client, league_settings, lcu_get_raw, lcu_post_raw, lcu_send, LcuClient};+use super::{get_client, lcu_get_raw, lcu_post_raw, lcu_send, league_settings, LcuClient};use base64::Engine;use futures::{SinkExt, StreamExt};use once_cell::sync::OnceCell;@@ -75,8 +75,7 @@ async fn run_session(client: &LcuClient) -> Result<(), String> {let mut request = url.into_client_request().map_err(|e| format!("bad websocket url: {}", e))?;- let auth = base64::engine::general_purpose::STANDARD- .encode(format!("riot:{}", client.token));+ let auth = base64::engine::general_purpose::STANDARD.encode(format!("riot:{}", client.token));request.headers_mut().insert("Authorization",format!("Basic {}", auth)@@ -280,7 +279,11 @@ async fn handle_trades(let path = format!("/lol-champ-select/v1/session/trades/{}/{}",id,- if strategy == "accept" { "accept" } else { "decline" }+ if strategy == "accept" {+ "accept"+ } else {+ "decline"+ });match lcu_post_raw(client, &path).await {Ok(_) => {@@ -362,7 +365,10 @@ async fn honor_from_ballot(client: &LcuClient, ballot: &Value) {None => return,};let puuid = choice.get("puuid").and_then(Value::as_str).unwrap_or("");- let summoner_id = choice.get("summonerId").and_then(Value::as_i64).unwrap_or(0);+ let summoner_id = choice+ .get("summonerId")+ .and_then(Value::as_i64)+ .unwrap_or(0);let modern = lcu_send(client,diff --git a/src-tauri/src/commands/p2p.rs b/src-tauri/src/commands/p2p.rsindex 8180681b..4e3ebc52 100644--- a/src-tauri/src/commands/p2p.rs+++ b/src-tauri/src/commands/p2p.rs@@ -2,8 +2,8 @@ use serde::Serialize;use tauri::Emitter;use tokio_util::sync::CancellationToken;-use omniget_core::platforms::p2p;use crate::{AppState, P2pSendHandle};+use omniget_core::platforms::p2p;#[derive(Clone, Serialize)]pub struct P2pSendStarted {diff --git a/src-tauri/src/commands/plugins.rs b/src-tauri/src/commands/plugins.rsindex 97a4aea6..659c613f 100644--- a/src-tauri/src/commands/plugins.rs+++ b/src-tauri/src/commands/plugins.rs@@ -11,7 +11,10 @@ fn emit_plugins_changed(app: &tauri::AppHandle) {let _ = app.emit("plugins-changed", ());}-fn build_plugin_host(app: &tauri::AppHandle, plugins_dir: std::path::PathBuf) -> Arc<dyn PluginHost> {+fn build_plugin_host(+ app: &tauri::AppHandle,+ plugins_dir: std::path::PathBuf,+) -> Arc<dyn PluginHost> {Arc::new(PluginHostImpl::new(app.clone(), plugins_dir))}@@ -139,7 +142,10 @@ pub fn get_plugin_frontend_path(plugin_id: String,) -> Result<String, String> {let manager = state.blocking_read();- let frontend_dir = manager.plugins_dir().join(&plugin_id).join("frontend");+ let frontend_dir = manager+ .plugin_dir(&plugin_id)+ .map_err(|e| e.to_string())?+ .join("frontend");if !frontend_dir.exists() {return Err(format!("Plugin '{}' has no frontend", plugin_id));}@@ -197,7 +203,10 @@ pub fn get_plugin_i18n(locale: String,) -> Result<serde_json::Value, String> {let manager = state.blocking_read();- let i18n_dir = manager.plugins_dir().join(&plugin_id).join("i18n");+ let i18n_dir = manager+ .plugin_dir(&plugin_id)+ .map_err(|e| e.to_string())?+ .join("i18n");let locale_file = i18n_dir.join(format!("{}.json", locale));if !locale_file.exists() {let fallback = i18n_dir.join("en.json");@@ -401,7 +410,7 @@ pub async fn install_plugin_zip_from_repo(let plugin_dir = {let manager = state.read().await;- manager.plugins_dir().join(&plugin_id)+ manager.plugin_dir(&plugin_id).map_err(|e| e.to_string())?};std::fs::create_dir_all(&plugin_dir).map_err(|e| e.to_string())?;@@ -517,7 +526,11 @@ pub async fn ensure_default_plugins(state: Arc<tokio::sync::RwLock<PluginManagerif skip {continue;}- tracing::info!("installing default plugin '{}' from {}", entry.id, entry.repo);+ tracing::info!(+ "installing default plugin '{}' from {}",+ entry.id,+ entry.repo+ );match install_plugin_zip_from_repo(&state, entry.id.clone(), entry.repo.clone()).await {Ok(v) => tracing::info!("default plugin '{}' installed ({})", entry.id, v),Err(e) => tracing::warn!("failed to install default plugin '{}': {}", entry.id, e),diff --git a/src-tauri/src/core/queue.rs b/src-tauri/src/core/queue.rsindex bb1e063f..312b417e 100644--- a/src-tauri/src/core/queue.rs+++ b/src-tauri/src/core/queue.rs@@ -1,2087 +1,2088 @@-use std::collections::HashMap;-use std::path::PathBuf;-use std::sync::atomic::{AtomicU64, Ordering};-use std::sync::{Arc, OnceLock};--static EMIT_COUNT: AtomicU64 = AtomicU64::new(0);--pub fn now_ms() -> u64 {- std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map(|d| d.as_millis() as 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;-use tokio_util::sync::CancellationToken;--fn shared_http_client() -> &'static reqwest::Client {- static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();- CLIENT.get_or_init(|| {- crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .build()- .unwrap_or_default()- })-}--use crate::core::ffmpeg::{self, MetadataEmbed};-use crate::models::media::MediaInfo;-use crate::platforms::traits::PlatformDownloader;-use crate::storage::config;--struct CachedInfo {- info: MediaInfo,- cached_at: std::time::Instant,-}--static INFO_CACHE: OnceLock<tokio::sync::Mutex<HashMap<String, CachedInfo>>> = OnceLock::new();--fn info_cache() -> &'static tokio::sync::Mutex<HashMap<String, CachedInfo>> {- INFO_CACHE.get_or_init(|| tokio::sync::Mutex::new(HashMap::new()))-}--const INFO_CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(600);--static IN_FLIGHT_FETCHES: OnceLock<- tokio::sync::Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,-> = OnceLock::new();--fn in_flight_map() -> &'static tokio::sync::Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>> {- IN_FLIGHT_FETCHES.get_or_init(|| tokio::sync::Mutex::new(HashMap::new()))-}--#[derive(Debug, Clone, Serialize)]-pub struct MediaPreviewEvent {- pub url: String,- pub title: String,- pub author: String,- pub thumbnail_url: Option<String>,- pub duration_seconds: Option<f64>,-}--#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, serde::Deserialize)]-#[serde(rename_all = "snake_case")]-pub enum QueueKind {- Video,- Audio,- Image,- Pdf,- Book,- Webpage,- TelegramMedia,- CourseLesson,- Generic,-}--pub fn kind_from_platform(platform: &str) -> QueueKind {- let p = platform.to_ascii_lowercase();- match p.as_str() {- "youtube" | "vimeo" | "twitch" | "bilibili" | "tiktok" | "twitter" | "x" | "instagram"- | "reddit" | "bluesky" | "facebook" | "generic_ytdlp" => QueueKind::Video,- "soundcloud" | "spotify" => QueueKind::Audio,- "pinterest" => QueueKind::Image,- "magnet" | "p2p" | "torrent" => QueueKind::Generic,- "telegram" | "telegram_media" => QueueKind::TelegramMedia,- "courses" | "course_lesson" => QueueKind::CourseLesson,- "annas_archive" | "book" | "libgen" | "gutendex" => QueueKind::Book,- "pdf" => QueueKind::Pdf,- "webpage" | "embed" => QueueKind::Webpage,- _ => QueueKind::Generic,- }-}--#[derive(Debug, Clone, Serialize, PartialEq)]-#[serde(tag = "type", content = "data")]-pub enum QueueStatus {- Queued,- Active,- Paused,- Seeding,- Complete { success: bool },- Error { message: String, retryable: bool },-}--pub fn is_retryable_error_message(message: &str) -> bool {- let lower = message.to_lowercase();- if lower.contains("cancel") {- return false;- }- let (category, _) = omniget_core::core::errors::classify_download_error(message);- matches!(category, "unknown" | "rate_limited")-}--#[derive(Clone, Serialize)]-pub struct QueueItemInfo {- pub id: u64,- pub url: String,- pub platform: String,- pub title: String,- pub status: QueueStatus,- pub percent: f64,- pub speed_bytes_per_sec: f64,- pub downloaded_bytes: u64,- pub total_bytes: Option<u64>,- pub file_path: Option<String>,- pub file_size_bytes: Option<u64>,- pub file_count: Option<u32>,- pub thumbnail_url: Option<String>,- #[serde(skip_serializing_if = "Option::is_none")]- pub kind: Option<QueueKind>,- #[serde(default)]- pub external: bool,- #[serde(skip_serializing_if = "Option::is_none")]- pub eta_seconds: Option<u64>,- #[serde(skip_serializing_if = "Option::is_none")]- pub quality: Option<String>,- #[serde(skip_serializing_if = "Option::is_none")]- pub download_mode: Option<String>,-}--pub struct QueueItem {- pub id: u64,- pub url: String,- pub platform: String,- pub title: String,- pub status: QueueStatus,- pub cancel_token: CancellationToken,- pub output_dir: String,- pub download_mode: Option<String>,- pub quality: Option<String>,- pub format_id: Option<String>,- pub referer: Option<String>,- pub extra_headers: Option<std::collections::HashMap<String, String>>,- pub page_url: Option<String>,- pub user_agent: Option<String>,- pub percent: f64,- pub speed_bytes_per_sec: f64,- pub downloaded_bytes: u64,- pub total_bytes: Option<u64>,- pub file_path: Option<String>,- pub file_size_bytes: Option<u64>,- pub file_count: Option<u32>,- pub media_info: Option<MediaInfo>,- pub downloader: Arc<dyn PlatformDownloader>,- pub ytdlp_path: Option<PathBuf>,- pub from_hotkey: bool,- pub torrent_id: Option<usize>,- pub kind: Option<QueueKind>,- pub external: bool,- pub thumbnail_url_override: Option<String>,- pub retry_count: u32,- pub max_retries: u32,- pub resume_state: Option<serde_json::Value>,- pub concurrent_segments: Option<usize>,- pub segment_size_bytes: Option<u64>,- pub eta_seconds: Option<u64>,- pub cookie_slug: Option<String>,- pub custom_ytdlp_args: Option<Vec<String>>,- pub torrent_files: Option<Vec<usize>>,- pub scheduled_at_ms: Option<u64>,- pub stop_at_ms: Option<u64>,-}--impl QueueItem {- pub fn to_info(&self) -> QueueItemInfo {- QueueItemInfo {- id: self.id,- url: self.url.clone(),- platform: self.platform.clone(),- title: self.title.clone(),- status: self.status.clone(),- percent: self.percent,- speed_bytes_per_sec: self.speed_bytes_per_sec,- downloaded_bytes: self.downloaded_bytes,- total_bytes: self.total_bytes,- file_path: self.file_path.clone(),- file_size_bytes: self.file_size_bytes,- file_count: self.file_count,- thumbnail_url: self.thumbnail_url_override.clone().or_else(|| {- self.media_info- .as_ref()- .and_then(|m| m.thumbnail_url.clone())- }),- kind: self.kind,- external: self.external,- eta_seconds: self.eta_seconds,- quality: self.quality.clone(),- download_mode: self.download_mode.clone(),- }- }-}--pub struct DownloadQueue {- pub items: Vec<QueueItem>,- pub max_concurrent: u32,- pub stagger_delay_ms: u64,- pub default_max_retries: u32,-}--impl DownloadQueue {- pub fn new(max_concurrent: u32) -> Self {- Self {- items: Vec::new(),- max_concurrent,- stagger_delay_ms: 150,- default_max_retries: 3,- }- }-- #[allow(clippy::too_many_arguments)]- pub fn enqueue(- &mut self,- id: u64,- url: String,- platform: String,- title: String,- output_dir: String,- download_mode: Option<String>,- quality: Option<String>,- format_id: Option<String>,- referer: Option<String>,- extra_headers: Option<std::collections::HashMap<String, String>>,- page_url: Option<String>,- user_agent: Option<String>,- media_info: Option<MediaInfo>,- total_bytes: Option<u64>,- file_count: Option<u32>,- downloader: Arc<dyn PlatformDownloader>,- ytdlp_path: Option<PathBuf>,- from_hotkey: bool,- cookie_slug: Option<String>,- custom_ytdlp_args: Option<Vec<String>>,- torrent_files: Option<Vec<usize>>,- scheduled_at_ms: Option<u64>,- stop_at_ms: Option<u64>,- ) {- let computed_kind = Some(kind_from_platform(&platform));- let item = QueueItem {- id,- url,- platform,- title,- status: QueueStatus::Queued,- cancel_token: CancellationToken::new(),- output_dir,- download_mode,- quality,- format_id,- referer,- extra_headers,- page_url,- user_agent,- percent: 0.0,- speed_bytes_per_sec: 0.0,- downloaded_bytes: 0,- total_bytes,- file_path: None,- file_size_bytes: None,- file_count,- media_info,- downloader,- ytdlp_path,- from_hotkey,- torrent_id: None,- kind: computed_kind,- external: false,- thumbnail_url_override: None,- retry_count: 0,- max_retries: self.default_max_retries,- resume_state: None,- concurrent_segments: None,- segment_size_bytes: None,- eta_seconds: None,- cookie_slug,- custom_ytdlp_args,- torrent_files,- scheduled_at_ms,- stop_at_ms,- };- crate::core::recovery::persist(crate::core::recovery::RecoveryItem {- id: item.id,- url: item.url.clone(),- title: item.title.clone(),- platform: item.platform.clone(),- output_dir: item.output_dir.clone(),- download_mode: item.download_mode.clone(),- quality: item.quality.clone(),- format_id: item.format_id.clone(),- referer: item.referer.clone(),- });- self.items.push(item);- }-- pub fn hydrate_from_history(&mut self) {- let entries = crate::core::queue_history::list();- if entries.is_empty() {- return;- }- let placeholder: Arc<dyn PlatformDownloader> =- Arc::new(crate::platforms::noop::NoopDownloader::new());- for entry in entries.iter().rev() {- if self.items.iter().any(|i| i.id == entry.id) {- continue;- }- let status = if entry.success {- QueueStatus::Complete { success: true }- } else {- let msg = entry.error.clone().unwrap_or_default();- let retryable = is_retryable_error_message(&msg);- QueueStatus::Error {- message: msg,- retryable,- }- };- let percent = if entry.success { 100.0 } else { 0.0 };- let item = QueueItem {- id: entry.id,- url: entry.url.clone(),- platform: entry.platform.clone(),- title: entry.title.clone(),- status,- cancel_token: CancellationToken::new(),- output_dir: entry- .file_path- .as_ref()- .and_then(|p| {- std::path::Path::new(p)- .parent()- .map(|x| x.to_string_lossy().to_string())- })- .unwrap_or_default(),- download_mode: None,- quality: None,- format_id: None,- referer: None,- extra_headers: None,- page_url: None,- user_agent: None,- percent,- speed_bytes_per_sec: 0.0,- downloaded_bytes: entry.file_size_bytes.unwrap_or(0),- total_bytes: entry.total_bytes,- file_path: entry.file_path.clone(),- file_size_bytes: entry.file_size_bytes,- file_count: None,- media_info: None,- downloader: placeholder.clone(),- ytdlp_path: None,- from_hotkey: false,- torrent_id: None,- kind: entry.kind,- external: false,- thumbnail_url_override: entry.thumbnail_url.clone(),- retry_count: 0,- max_retries: 0,- resume_state: None,- concurrent_segments: None,- segment_size_bytes: None,- eta_seconds: None,- cookie_slug: None,- custom_ytdlp_args: None,- torrent_files: None,- scheduled_at_ms: None,- stop_at_ms: None,- };- self.items.push(item);- }- }-- pub fn active_count(&self) -> u32 {- self.items- .iter()- .filter(|i| i.status == QueueStatus::Active)- .count() as u32- }-- pub fn next_queued_ids(&self) -> Vec<u64> {- let slots = self.max_concurrent.saturating_sub(self.active_count()) as usize;- let now = now_ms();- self.items- .iter()- .filter(|i| i.status == QueueStatus::Queued)- .filter(|i| i.scheduled_at_ms.map(|t| now >= t).unwrap_or(true))- .take(slots)- .map(|i| i.id)- .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 && i.status == QueueStatus::Queued)- {- item.status = QueueStatus::Active;- item.cancel_token = CancellationToken::new();- }- }-- pub fn mark_complete(- &mut self,- id: u64,- success: bool,- error: Option<String>,- file_path: Option<String>,- file_size_bytes: Option<u64>,- ) {- if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {- let error_for_history = error.clone();- if success {- item.status = QueueStatus::Complete { success: true };- item.percent = 100.0;- } else {- let msg = error.unwrap_or_default();- let retryable = is_retryable_error_message(&msg);- item.status = QueueStatus::Error {- message: msg,- retryable,- };- }- item.file_path = file_path;- item.file_size_bytes = file_size_bytes;- item.speed_bytes_per_sec = 0.0;- item.eta_seconds = None;- crate::core::recovery::remove(id);-- if !item.external {- let entry = crate::core::queue_history::HistoryEntry {- id: item.id,- url: item.url.clone(),- platform: item.platform.clone(),- title: item.title.clone(),- file_path: item.file_path.clone(),- file_size_bytes: item.file_size_bytes,- total_bytes: item.total_bytes,- success,- error: if success { None } else { error_for_history },- completed_at: crate::core::queue_history::now_unix_seconds(),- thumbnail_url: item.thumbnail_url_override.clone().or_else(|| {- item.media_info- .as_ref()- .and_then(|m| m.thumbnail_url.clone())- }),- kind: item.kind,- };- crate::core::queue_history::record(entry);- }- }- }-- pub fn mark_seeding(- &mut self,- id: u64,- file_path: Option<String>,- file_size_bytes: Option<u64>,- torrent_id: Option<usize>,- ) {- if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {- item.status = QueueStatus::Seeding;- item.percent = 100.0;- item.file_path = file_path;- item.file_size_bytes = file_size_bytes;- item.speed_bytes_per_sec = 0.0;- item.torrent_id = torrent_id;- crate::core::recovery::remove(id);- }- }-- pub fn update_progress(- &mut self,- id: u64,- percent: f64,- speed: f64,- downloaded: u64,- total: Option<u64>,- torrent_id: Option<usize>,- eta_seconds: Option<u64>,- ) {- if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {- if item.status != QueueStatus::Active {- if torrent_id.is_some() && item.torrent_id.is_none() {- item.torrent_id = torrent_id;- }- return;- }- item.percent = percent;- item.speed_bytes_per_sec = speed;- item.downloaded_bytes = downloaded;- if let Some(t) = total {- item.total_bytes = Some(t);- }- if torrent_id.is_some() && item.torrent_id.is_none() {- item.torrent_id = torrent_id;- }- item.eta_seconds = eta_seconds;- }- }-- 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"- && !omniget_core::core::ytdlp::pause_download_process(id)- {- return false;- }- item.status = QueueStatus::Paused;- item.speed_bytes_per_sec = 0.0;- item.eta_seconds = None;- return true;- }- }- false- }-- 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"- && !omniget_core::core::ytdlp::resume_download_process(id)- {- return false;- }- item.status = QueueStatus::Active;- return true;- }- }- false- }-- pub fn pause_all(&mut self) -> Vec<(u64, Option<usize>)> {- let mut paused = Vec::new();- for item in self.items.iter_mut() {- if item.status == QueueStatus::Active {- 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;- item.eta_seconds = None;- paused.push((item.id, item.torrent_id));- }- }- paused- }-- pub fn resume_all(&mut self) -> Vec<(u64, Option<usize>)> {- let mut resumed = Vec::new();- for item in self.items.iter_mut() {- if item.status == QueueStatus::Paused {- let tid = item.torrent_id;- if item.platform != "magnet"- && !omniget_core::core::ytdlp::resume_download_process(item.id)- {- continue;- }- item.status = QueueStatus::Active;- resumed.push((item.id, tid));- }- }- resumed- }-- pub fn reorder(&mut self, ids_in_order: Vec<u64>) -> bool {- let mut slots: Vec<Option<QueueItem>> = self.items.drain(..).map(Some).collect();-- let queued_slot_indices: Vec<usize> = slots- .iter()- .enumerate()- .filter_map(|(idx, slot)| {- slot.as_ref()- .filter(|i| i.status == QueueStatus::Queued)- .map(|_| idx)- })- .collect();-- if queued_slot_indices.is_empty() {- self.items = slots.into_iter().flatten().collect();- return false;- }-- let queued_id_to_slot: std::collections::HashMap<u64, usize> = queued_slot_indices- .iter()- .map(|idx| (slots[*idx].as_ref().unwrap().id, *idx))- .collect();-- let mut new_queued_order: Vec<QueueItem> = Vec::with_capacity(queued_slot_indices.len());- let mut seen: std::collections::HashSet<u64> = std::collections::HashSet::new();-- for id in &ids_in_order {- if seen.contains(id) {- continue;- }- if let Some(slot_idx) = queued_id_to_slot.get(id) {- if let Some(item) = slots[*slot_idx].take() {- new_queued_order.push(item);- seen.insert(*id);- }- }- }- for idx in &queued_slot_indices {- if let Some(item) = slots[*idx].take() {- new_queued_order.push(item);- }- }-- let mut iter = new_queued_order.into_iter();- let mut rebuilt: Vec<QueueItem> = Vec::with_capacity(slots.len());- for (idx, slot) in slots.into_iter().enumerate() {- if queued_slot_indices.contains(&idx) {- if let Some(item) = iter.next() {- rebuilt.push(item);- }- } else if let Some(item) = slot {- rebuilt.push(item);- }- }- rebuilt.extend(iter);- self.items = rebuilt;- true- }-- /// Cancel an item. Returns the torrent_id if the item needs torrent cleanup (caller should delete from session).- pub fn cancel(&mut self, id: u64) -> (bool, Option<usize>) {- let result = self.cancel_inner(id);- if result.0 {- crate::core::recovery::remove(id);- }- result- }-- fn cancel_inner(&mut self, id: u64) -> (bool, Option<usize>) {- if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {- match &item.status {- QueueStatus::Active => {- item.cancel_token.cancel();- item.status = QueueStatus::Error {- message: "Cancelled".to_string(),- retryable: false,- };- item.speed_bytes_per_sec = 0.0;- return (true, None);- }- QueueStatus::Seeding => {- let tid = item.torrent_id;- item.status = QueueStatus::Error {- message: "Cancelled".to_string(),- retryable: false,- };- item.speed_bytes_per_sec = 0.0;- return (true, tid);- }- QueueStatus::Paused => {- // For magnet downloads, the cancel_token was not cancelled during pause,- // so we must cancel it now to stop the background download loop.- // Also return the torrent_id for session cleanup.- item.cancel_token.cancel();- let tid = if item.platform == "magnet" {- item.torrent_id- } else {- None- };- item.status = QueueStatus::Error {- message: "Cancelled".to_string(),- retryable: false,- };- item.speed_bytes_per_sec = 0.0;- return (true, tid);- }- QueueStatus::Queued => {- item.status = QueueStatus::Error {- message: "Cancelled".to_string(),- retryable: false,- };- return (true, None);- }- _ => {}- }- }- (false, None)- }-- pub fn retry(&mut self, id: u64) -> bool {- if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {- if matches!(item.status, QueueStatus::Error { .. }) {- item.status = QueueStatus::Queued;- item.cancel_token = CancellationToken::new();- item.percent = 0.0;- item.speed_bytes_per_sec = 0.0;- item.downloaded_bytes = 0;- item.file_path = None;- item.file_size_bytes = None;- item.retry_count = 0;- return true;- }- }- false- }-- /// Remove an item. Returns the torrent_id if the item needs torrent cleanup (caller should delete from session).- pub fn remove(&mut self, id: u64) -> Option<Option<usize>> {- let result = self.remove_inner(id);- if result.is_some() {- crate::core::recovery::remove(id);- crate::core::queue_history::remove(id);- }- result- }-- fn remove_inner(&mut self, id: u64) -> Option<Option<usize>> {- if let Some(pos) = self.items.iter().position(|i| i.id == id) {- let item = &self.items[pos];- if item.status == QueueStatus::Active {- item.cancel_token.cancel();- }- // For paused magnet items, the cancel_token was not cancelled during pause- if item.status == QueueStatus::Paused && item.platform == "magnet" {- item.cancel_token.cancel();- }- let torrent_id = if item.status == QueueStatus::Seeding- || (item.status == QueueStatus::Paused && item.platform == "magnet")- {- item.torrent_id- } else {- None- };- self.items.remove(pos);- return Some(torrent_id);- }- None- }-- pub fn clear_finished(&mut self) {- let to_remove: Vec<u64> = self- .items- .iter()- .filter(|i| matches!(i.status, QueueStatus::Complete { .. }))- .map(|i| i.id)- .collect();- for id in &to_remove {- crate::core::recovery::remove(*id);- crate::core::queue_history::remove(*id);- }- self.items- .retain(|i| !matches!(i.status, QueueStatus::Complete { .. }));- }-- pub fn get_state(&self) -> Vec<QueueItemInfo> {- self.items.iter().map(|i| i.to_info()).collect()- }-- pub fn has_url(&self, url: &str) -> bool {- self.items.iter().any(|i| {- i.url == url- && matches!(- i.status,- QueueStatus::Queued- | QueueStatus::Active- | QueueStatus::Paused- | QueueStatus::Seeding- )- })- }-}--pub struct ProgressThrottle {- last_emit: std::time::Instant,- min_interval: std::time::Duration,-}--impl ProgressThrottle {- pub fn new(min_interval_ms: u64) -> Self {- Self {- last_emit: std::time::Instant::now() - std::time::Duration::from_secs(10),- min_interval: std::time::Duration::from_millis(min_interval_ms),- }- }-- pub fn should_emit(&mut self) -> bool {- let now = std::time::Instant::now();- if now.duration_since(self.last_emit) >= self.min_interval {- self.last_emit = now;- true- } else {- false- }- }-}--#[derive(Clone, Serialize)]-pub struct QueueItemProgress {- pub id: u64,- pub title: String,- pub platform: String,- pub percent: f64,- pub speed_bytes_per_sec: f64,- pub downloaded_bytes: u64,- pub total_bytes: Option<u64>,- pub phase: String,- #[serde(skip_serializing_if = "Option::is_none")]- pub eta_seconds: Option<u64>,-}--pub fn emit_queue_state_from_state(app: &tauri::AppHandle, state: Vec<QueueItemInfo>) {- let n = EMIT_COUNT.fetch_add(1, Ordering::Relaxed);- if n.is_multiple_of(10) {- tracing::debug!("[perf] emit_queue_state called {} times", n);- }- let _ = app.emit("queue-state-update", &state);- let total = crate::tray::compute_total_active(app);- crate::tray::update_active_count(app, total);- crate::core::awake::sync(total > 0);-- let active_items: Vec<_> = state- .iter()- .filter(|i| i.status == QueueStatus::Active)- .collect();- let avg_percent = if !active_items.is_empty() {- let sum: f64 = active_items.iter().map(|i| i.percent).sum();- sum / active_items.len() as f64 / 100.0- } else {- 0.0- };- let total_speed: f64 = active_items.iter().map(|i| i.speed_bytes_per_sec).sum();- crate::tray::update_speed_tooltip(app, total, total_speed);- crate::tray::update_taskbar_badge(app, total, avg_percent);-- if let Some(window) = app.get_webview_window("main") {- let title = if total > 0 {- format!("({}) omniget", total)- } else {- "omniget".into()- };- let _ = window.set_title(&title);- }-}--pub fn emit_queue_state(app: &tauri::AppHandle, queue: &DownloadQueue) {- let state = queue.get_state();- emit_queue_state_from_state(app, state);-}--/// RAII guard that ensures an Active queue item never leaks a slot.-///-/// If the download future panics or is dropped before reaching `mark_complete`-/// / `mark_seeding`, the Drop impl spawns a task that transitions the item to-/// Error("Download interrupted") and calls `try_start_next`, unblocking the-/// queue.-///-/// When the download reaches a terminal state through the normal paths, the-/// guard sees the item is no longer Active and does nothing (idempotent).-struct ActiveJobSlot {- app: tauri::AppHandle,- queue: Arc<tokio::sync::Mutex<DownloadQueue>>,- item_id: u64,- armed: bool,-}--impl ActiveJobSlot {- fn new(- app: tauri::AppHandle,- queue: Arc<tokio::sync::Mutex<DownloadQueue>>,- item_id: u64,- ) -> Self {- Self {- app,- queue,- item_id,- armed: true,- }- }-- fn disarm(mut self) {- self.armed = false;- }-}--impl Drop for ActiveJobSlot {- fn drop(&mut self) {- if !self.armed {- return;- }- let app = self.app.clone();- let queue = self.queue.clone();- let item_id = self.item_id;- tokio::spawn(async move {- let state = {- let mut q = queue.lock().await;- let still_active = q- .items- .iter()- .find(|i| i.id == item_id)- .map(|i| i.status == QueueStatus::Active)- .unwrap_or(false);- if !still_active {- return;- }- tracing::warn!(- "[queue] ActiveJobSlot guard firing for {} — download ended without clean release",- item_id- );- q.mark_complete(- item_id,- false,- Some("Download interrupted".to_string()),- None,- None,- );- q.get_state()- };- emit_queue_state_from_state(&app, state);- try_start_next(app, queue).await;- });- }-}--pub fn spawn_download(- app: tauri::AppHandle,- queue: Arc<tokio::sync::Mutex<DownloadQueue>>,- item_id: u64,-) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> {- Box::pin(async move {- let _timer_start = std::time::Instant::now();- let slot = ActiveJobSlot::new(app.clone(), queue.clone(), item_id);- spawn_download_inner(app, queue, item_id).await;- slot.disarm();- tracing::debug!(- "[perf] spawn_download {} took {:?}",- item_id,- _timer_start.elapsed()- );- })-}--async fn spawn_download_inner(- app: tauri::AppHandle,- queue: Arc<tokio::sync::Mutex<DownloadQueue>>,- item_id: u64,-) {- tracing::info!("[queue] download {} started", item_id);-- let _ = app.emit(- "queue-item-progress",- &QueueItemProgress {- id: item_id,- title: "".to_string(),- platform: "".to_string(),- percent: 0.0,- speed_bytes_per_sec: 0.0,- downloaded_bytes: 0,- total_bytes: None,- phase: "preparing".to_string(),- eta_seconds: None,- },- );-- let host_key = {- let q = queue.lock().await;- q.items- .iter()- .find(|i| i.id == item_id)- .map(|i| crate::core::host_limiter::host_key_for_url(&i.url))- };- let _host_lease = match host_key {- Some(key) => Some(crate::core::host_limiter::acquire(&key).await),- None => None,- };-- let (- url,- output_dir,- download_mode,- quality,- format_id,- referer,- extra_headers,- page_url,- user_agent,- cancel_token,- media_info,- platform_name,- downloader,- ytdlp_path,- from_hotkey,- cookie_slug,- custom_ytdlp_args,- torrent_files,- ) = {- let q = queue.lock().await;- let item = match q.items.iter().find(|i| i.id == item_id) {- Some(i) => i,- None => return,- };- (- item.url.clone(),- item.output_dir.clone(),- item.download_mode.clone(),- item.quality.clone(),- item.format_id.clone(),- item.referer.clone(),- item.extra_headers.clone(),- item.page_url.clone(),- item.user_agent.clone(),- item.cancel_token.clone(),- item.media_info.clone(),- item.platform.clone(),- item.downloader.clone(),- item.ytdlp_path.clone(),- item.from_hotkey,- item.cookie_slug.clone(),- item.custom_ytdlp_args.clone(),- item.torrent_files.clone(),- )- };-- {- let settings = crate::storage::config::load_settings(&app);- let proxy = settings.proxy.clone();- crate::core::http_client::init_proxy(proxy.clone());- let proxy_status = if !proxy.enabled {- "disabled; system/env proxy honored if set".to_string()- } else if proxy.host.trim().is_empty() {- "enabled but host is empty; falling back to system/env proxy".to_string()- } else {- format!("enabled; {}://{}:{}", proxy.proxy_type, proxy.host, proxy.port)- };- append_download_log(- &app,- item_id,- format!("[network] proxy setting: {}", proxy_status),- );- }-- let info_start = std::time::Instant::now();- let info = match media_info {- Some(i) if !i.available_qualities.is_empty() => {- tracing::info!(- "[queue] info for {} from cache/pre-fetched in {:?}",- item_id,- info_start.elapsed()- );- append_download_log(- &app,- item_id,- format!(- "[omniget] using cached video info: platform={} title=\"{}\"",- platform_name, i.title- ),- );- i- }- _ => {- tracing::debug!(- "[perf] spawn_download_inner {}: media_info is None, fetching info",- item_id- );- append_download_log(- &app,- item_id,- format!(- "[omniget] fetching video info: platform={} url={}",- platform_name, url- ),- );- if let Some(slug) = cookie_slug.as_deref() {- append_download_log(- &app,- item_id,- format!("[cookies] selected managed cookie account: {}", slug),- );- }- let _ = app.emit(- "queue-item-progress",- &QueueItemProgress {- id: item_id,- title: url.clone(),- platform: platform_name.clone(),- percent: 0.0,- speed_bytes_per_sec: 0.0,- downloaded_bytes: 0,- total_bytes: None,- phase: "fetching_info".to_string(),- eta_seconds: None,- },- );-- let info_future = fetch_and_cache_info(- &url,- &*downloader,- &platform_name,- ytdlp_path.as_deref(),- );- let scoped_info_future = omniget_core::core::log_hook::CURRENT_COOKIE_SLUG.scope(- cookie_slug.clone(),- omniget_core::core::log_hook::CURRENT_DOWNLOAD_ID.scope(item_id, info_future),- );- let info_timeout_secs = if platform_name == "youtube"- || url.to_ascii_lowercase().contains("youtube.com")- || url.to_ascii_lowercase().contains("youtu.be")- {- omniget_core::core::ytdlp::YOUTUBE_VIDEO_INFO_TOTAL_TIMEOUT_SECS- } else if platform_name == "douyin" {- 30- } else {- omniget_core::core::ytdlp::DEFAULT_VIDEO_INFO_TOTAL_TIMEOUT_SECS- };- let info_result = tokio::time::timeout(- std::time::Duration::from_secs(info_timeout_secs),- scoped_info_future,- )- .await;-- match info_result {- Ok(Ok(i)) => {- append_download_log(- &app,- item_id,- format!(- "[omniget] video info fetched in {:.1}s: title=\"{}\"",- info_start.elapsed().as_secs_f64(),- i.title- ),- );- i- }- Ok(Err(e)) => {- append_download_log(- &app,- item_id,- format!(- "[omniget] failed fetching video info after {:.1}s: {}",- info_start.elapsed().as_secs_f64(),- e- ),- );- let state = {- let mut q = queue.lock().await;- q.mark_complete(item_id, false, Some(e.to_string()), None, None);- q.get_state()- };- emit_queue_state_from_state(&app, state);- try_start_next(app, queue).await;- return;- }- Err(_) => {- tracing::warn!(- "[queue] info fetch timed out for {} after {}s",- item_id,- info_timeout_secs- );- append_download_log(- &app,- item_id,- format!(- "[omniget] video info timed out after {}s",- info_timeout_secs- ),- );- let state = {- let mut q = queue.lock().await;- q.mark_complete(- item_id,- false,- Some("Timed out fetching video info".to_string()),- None,- None,- );- q.get_state()- };- emit_queue_state_from_state(&app, state);- try_start_next(app, queue).await;- return;- }- }- }- };- tracing::info!(- "[queue] info fetch for {} took {:?}",- item_id,- info_start.elapsed()- );-- let mut info = info;- if is_generic_title(&info.title) {- let pokemon = omniget_core::core::pokemon_names::random_pokemon_name();- info.title = format!("video_{}", pokemon);- }-- let state = {- let mut q = queue.lock().await;- if let Some(item) = q.items.iter_mut().find(|i| i.id == item_id) {- item.title = info.title.clone();- item.total_bytes = info.file_size_bytes;- let fc = if info.media_type == crate::models::media::MediaType::Carousel- || info.media_type == crate::models::media::MediaType::Playlist- {- info.available_qualities.len() as u32- } else {- 1- };- item.file_count = Some(fc);- item.media_info = Some(info.clone());- }- q.get_state()- };- emit_queue_state_from_state(&app, state);-- let _ = app.emit(- "queue-item-progress",- &QueueItemProgress {- id: item_id,- title: info.title.clone(),- platform: platform_name.clone(),- percent: 0.5,- speed_bytes_per_sec: 0.0,- downloaded_bytes: 0,- total_bytes: info.file_size_bytes,- phase: "starting".to_string(),- eta_seconds: None,- },- );-- let settings = config::load_settings(&app);- let tmpl = settings.download.filename_template.clone();- let mut final_output_dir = std::path::PathBuf::from(&output_dir);- if settings.download.organize_by_platform {- final_output_dir = final_output_dir.join(&platform_name);- }- let torrent_id_slot = Arc::new(tokio::sync::Mutex::new(None));- let audio_format = if download_mode.as_deref() == Some("audio") {- Some(settings.download.music_audio_format.clone())- } else {- None- };- let custom_ytdlp_args = {- let mut args = custom_ytdlp_args.clone();- if settings.download.skip_existing {- let flags = args.get_or_insert_with(Vec::new);- if !flags.iter().any(|f| f == "--no-overwrites") {- flags.push("--no-overwrites".to_string());- }- }- args- };- let opts = crate::models::media::DownloadOptions {- quality: quality.or_else(|| Some(settings.download.video_quality.clone())),- output_dir: final_output_dir,- filename_template: Some(tmpl),- download_subtitles: settings.download.download_subtitles,- include_auto_subtitles: settings.download.include_auto_subtitles,- download_mode,- audio_format,- format_id,- referer,- extra_headers,- page_url,- user_agent,- cancel_token: cancel_token.clone(),- concurrent_fragments: settings.advanced.concurrent_fragments,- ytdlp_path,- torrent_listen_port: Some(settings.advanced.torrent_listen_port),- torrent_id_slot: Some(torrent_id_slot.clone()),- custom_ytdlp_args: custom_ytdlp_args.clone(),- torrent_files: torrent_files.clone(),- torrent_auto_trackers: settings.advanced.torrent_auto_trackers,- torrent_upnp: settings.advanced.torrent_upnp,- };-- 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);-- let app_progress = app.clone();- let queue_progress = queue.clone();- let torrent_id_slot_progress = torrent_id_slot.clone();- let progress_forwarder = tokio::spawn(async move {- const STALL_AFTER: std::time::Duration = std::time::Duration::from_secs(6);-- let mut last_bytes: u64 = 0;- let mut last_time = std::time::Instant::now();- let mut throttle = ProgressThrottle::new(250);- let mut current_speed: f64 = 0.0;- let mut last_percent: f64 = 0.0;- let mut last_advance = std::time::Instant::now();- let mut stalled = false;-- loop {- let update = tokio::select! {- msg = rx.recv() => match msg {- Some(u) => u,- None => break,- },- _ = tokio::time::sleep(std::time::Duration::from_secs(2)) => {- if !stalled && last_advance.elapsed() >= STALL_AFTER {- stalled = true;- current_speed = 0.0;- {- let mut q = queue_progress.lock().await;- let tid = { *torrent_id_slot_progress.lock().await };- q.update_progress(- item_id, last_percent, 0.0, last_bytes, total_bytes, tid, None,- );- }- let _ = app_progress.emit(- "queue-item-progress",- &QueueItemProgress {- id: item_id,- title: item_title.clone(),- platform: item_platform.clone(),- percent: last_percent,- speed_bytes_per_sec: 0.0,- downloaded_bytes: last_bytes,- total_bytes,- phase: "stalled".to_string(),- eta_seconds: None,- },- );- }- continue;- }- };-- let percent = update.percent;- if !throttle.should_emit() && percent < 100.0 && !update.has_real_metrics() {- continue;- }-- let now = std::time::Instant::now();- let resolved_total = update.total_bytes.or(total_bytes);- 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;- } else if downloaded_bytes > last_bytes {- let dt = now.duration_since(last_time).as_secs_f64();- if dt > 0.1 {- let instant_speed = (downloaded_bytes - last_bytes) as f64 / dt;- current_speed = if current_speed > 0.0 {- current_speed * 0.7 + instant_speed * 0.3- } else {- instant_speed- };- }- }-- if downloaded_bytes > last_bytes || clamped > last_percent || update.speed_bps.is_some()- {- last_advance = now;- stalled = false;- }- last_bytes = downloaded_bytes;- last_time = now;- last_percent = clamped;-- 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",- p if p > 0.0 => "downloading",- _ => "starting",- };-- let eta_seconds = update- .eta_seconds- .or_else(|| omniget_core::core::ytdlp::get_eta(item_id))- .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)- })- } else {- None- }- });-- {- let mut q = queue_progress.lock().await;- let tid = { *torrent_id_slot_progress.lock().await };- q.update_progress(- item_id,- clamped,- current_speed,- downloaded_bytes,- resolved_total,- tid,- eta_seconds,- );- }-- let _ = app_progress.emit(- "queue-item-progress",- &QueueItemProgress {- id: item_id,- title: item_title.clone(),- platform: item_platform.clone(),- percent: clamped,- speed_bytes_per_sec: current_speed,- downloaded_bytes,- total_bytes: resolved_total,- phase: phase.to_string(),- eta_seconds,- },- );- }- omniget_core::core::ytdlp::clear_eta(item_id);- });-- if let Some(ua) = opts.user_agent.clone() {- omniget_core::core::ytdlp::register_ext_user_agent(url.clone(), ua);- }- if let Some(hdrs) = opts.extra_headers.clone() {- omniget_core::core::ytdlp::register_ext_headers(url.clone(), hdrs);- }-- 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,- _ = cancel_token.cancelled() => {- Err(anyhow::anyhow!("Download cancelado"))- }- }- };- let result = omniget_core::core::log_hook::CURRENT_COOKIE_SLUG- .scope(- cookie_slug.clone(),- omniget_core::core::log_hook::CURRENT_DOWNLOAD_ID.scope(item_id, dl_future),- )- .await;- omniget_core::core::ytdlp::clear_ext_user_agent(&url);- omniget_core::core::ytdlp::clear_ext_headers(&url);- tracing::info!(- "[queue] download {} completed in {:?}",- item_id,- dl_start.elapsed()- );-- let _ = progress_forwarder.await;-- let was_paused = {- let q = queue.lock().await;- q.items- .iter()- .find(|i| i.id == item_id)- .map(|i| i.status == QueueStatus::Paused)- .unwrap_or(false)- };-- if was_paused {- let state = {- let q = queue.lock().await;- q.get_state()- };- emit_queue_state_from_state(&app, state);- try_start_next(app, queue).await;- return;- }-- 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- ),- );- let is_seeding = platform_name == "magnet" && dl.torrent_id.is_some();- if !is_seeding {- if let Err(msg) = validate_download_output(&dl.file_path).await {- tracing::error!(- "[queue] download {} reported success but output is missing or empty: {:?}",- item_id,- dl.file_path- );- append_download_log(- &app,- item_id,- format!(- "[omniget] download reported success but output missing or empty: {}",- dl.file_path.to_string_lossy()- ),- );- let state = {- let mut q = queue.lock().await;- q.mark_complete(item_id, false, Some(msg), None, None);- q.get_state()- };- emit_queue_state_from_state(&app, state);- try_start_next(app, queue).await;- return;- }- }-- if settings.download.embed_metadata- && platform_name != "magnet"- && ffmpeg::is_ffmpeg_available().await- {- let metadata = MetadataEmbed {- title: Some(info.title.clone()),- artist: Some(info.author.clone()),- thumbnail_url: info.thumbnail_url.clone(),- ..Default::default()- };- if let Err(e) = ffmpeg::embed_metadata(- &dl.file_path,- &metadata,- settings.download.embed_thumbnail,- shared_http_client(),- )- .await- {- tracing::warn!("Metadata embed failed for '{}': {}", info.title, e);- }- }-- if from_hotkey && settings.download.copy_to_clipboard_on_hotkey {- #[cfg(not(target_os = "android"))]- {- match crate::core::clipboard::copy_file_to_clipboard(&dl.file_path).await {- Ok(()) => {- let _ = app.emit(- "file-copied-to-clipboard",- serde_json::json!({- "path": dl.file_path.to_string_lossy(),- }),- );- }- Err(e) => {- tracing::warn!("[clipboard] failed to copy file: {}", e);- }- }- }- }-- let state = {- let mut q = queue.lock().await;- if platform_name == "magnet" && dl.torrent_id.is_some() {- q.mark_seeding(- item_id,- Some(dl.file_path.to_string_lossy().to_string()),- Some(dl.file_size_bytes),- dl.torrent_id,- );- } else {- q.mark_complete(- item_id,- true,- None,- Some(dl.file_path.to_string_lossy().to_string()),- Some(dl.file_size_bytes),- );- }- q.get_state()- };- emit_queue_state_from_state(&app, state);- }- 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)- } else {- raw_err.clone()- };- tracing::error!(- "Download error '{}' [{}]: {}",- platform_name,- category,- raw_err- );-- let retry_decision = {- let mut q = queue.lock().await;- if let Some(item) = q.items.iter_mut().find(|i| i.id == item_id) {- if item.downloaded_bytes > 5 * 1024 * 1024 {- item.retry_count = 0;- }- let retryable = is_retryable_category(category);- let attempt = item.retry_count;- let max = item.max_retries;- if retryable && attempt < max {- item.retry_count = attempt + 1;- Some((attempt + 1, max))- } else {- None- }- } else {- None- }- };-- if let Some((next_attempt, max)) = retry_decision {- let delay_secs = (1u64 << (next_attempt - 1).min(5)).min(30);- tracing::warn!(- "[queue] retry {}/{} for {} in {}s (category={})",- next_attempt,- max,- item_id,- delay_secs,- category- );- let state = {- let mut q = queue.lock().await;- if let Some(item) = q.items.iter_mut().find(|i| i.id == item_id) {- item.status = QueueStatus::Queued;- item.cancel_token = CancellationToken::new();- item.percent = 0.0;- item.speed_bytes_per_sec = 0.0;- item.downloaded_bytes = 0;- }- q.get_state()- };- emit_queue_state_from_state(&app, state);- let app_for_retry = app.clone();- let queue_for_retry = queue.clone();- tokio::spawn(async move {- tokio::time::sleep(std::time::Duration::from_secs(delay_secs)).await;- try_start_next(app_for_retry, queue_for_retry).await;- });- return;- }-- let state = {- let mut q = queue.lock().await;- q.mark_complete(item_id, false, Some(user_msg), None, None);- q.get_state()- };- emit_queue_state_from_state(&app, state);- }- }-- try_start_next(app, queue).await;-}--fn is_retryable_category(category: &str) -> bool {- matches!(category, "unknown" | "rate_limited")-}--const OUTPUT_MISSING_ERROR: &str =- "Download reported success but the file is missing or empty. Check disk space and antivirus exclusions, then retry.";--async fn validate_download_output(path: &std::path::Path) -> Result<(), String> {- if path.as_os_str().is_empty() {- return Err(OUTPUT_MISSING_ERROR.to_string());- }- let meta = match tokio::fs::metadata(path).await {- Ok(m) => m,- Err(_) => return Err(OUTPUT_MISSING_ERROR.to_string()),- };- if meta.is_dir() {- let mut entries = match tokio::fs::read_dir(path).await {- Ok(e) => e,- Err(_) => return Err(OUTPUT_MISSING_ERROR.to_string()),- };- match entries.next_entry().await {- Ok(Some(_)) => Ok(()),- _ => Err(OUTPUT_MISSING_ERROR.to_string()),- }- } else if meta.len() > 0 {- Ok(())- } else {- Err(OUTPUT_MISSING_ERROR.to_string())- }-}--async fn fetch_and_cache_info(- url: &str,- downloader: &dyn PlatformDownloader,- platform: &str,- ytdlp_path: Option<&std::path::Path>,-) -> anyhow::Result<MediaInfo> {- {- let cache = info_cache().lock().await;- if let Some(entry) = cache.get(url) {- if entry.cached_at.elapsed() < INFO_CACHE_TTL {- tracing::debug!("[perf] fetch_and_cache_info: cache hit for {}", platform);- return Ok(entry.info.clone());- }- }- }-- let url_lock = {- let mut map = in_flight_map().lock().await;- map.entry(url.to_string())- .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))- .clone()- };- let _guard = url_lock.lock().await;-- {- let cache = info_cache().lock().await;- if let Some(entry) = cache.get(url) {- if entry.cached_at.elapsed() < INFO_CACHE_TTL {- tracing::debug!(- "[perf] fetch_and_cache_info: dedup cache hit for {}",- platform- );- return Ok(entry.info.clone());- }- }- }-- tracing::debug!("[perf] fetch_and_cache_info: fetching for {}", platform);- let info = if let Some(ytdlp) = ytdlp_path {- match platform {- "youtube" => {- omniget_core::platforms::YouTubeDownloader::fetch_with_ytdlp(url, ytdlp).await?- }- "generic" => {- if crate::platforms::generic_ytdlp::is_direct_media_url(url).is_some() {- downloader.get_media_info(url).await?- } else {- let json = crate::core::ytdlp::get_video_info(ytdlp, url, &[]).await?;- crate::platforms::generic_ytdlp::GenericYtdlpDownloader::parse_video_info(&json)?- }- }- _ => downloader.get_media_info(url).await?,- }- } else {- downloader.get_media_info(url).await?- };-- let mut cache = info_cache().lock().await;- cache.insert(- url.to_string(),- CachedInfo {- info: info.clone(),- cached_at: std::time::Instant::now(),- },- );- if cache.len() > 50 {- cache.retain(|_, v| v.cached_at.elapsed() < INFO_CACHE_TTL);- }- Ok(info)-}--pub async fn try_get_cached_info(url: &str) -> Option<MediaInfo> {- let cache = info_cache().lock().await;- cache- .get(url)- .filter(|entry| entry.cached_at.elapsed() < INFO_CACHE_TTL)- .map(|entry| entry.info.clone())-}--pub async fn prefetch_info(- url: &str,- downloader: &dyn PlatformDownloader,- platform: &str,- ytdlp_path: Option<&std::path::Path>,-) {- prefetch_info_with_emit(url, downloader, platform, ytdlp_path, None).await;-}--pub async fn prefetch_info_with_emit(- url: &str,- downloader: &dyn PlatformDownloader,- platform: &str,- ytdlp_path: Option<&std::path::Path>,- app: Option<tauri::AppHandle>,-) {- let _timer_start = std::time::Instant::now();- tracing::debug!("[perf] prefetch_info: started");- let result = tokio::time::timeout(- std::time::Duration::from_secs(15),- fetch_and_cache_info(url, downloader, platform, ytdlp_path),- )- .await;- match result {- Ok(Ok(info)) => {- tracing::debug!(- "[perf] prefetch_info: completed in {:?} — {}",- _timer_start.elapsed(),- info.title- );- if let Some(app) = app {- let preview = MediaPreviewEvent {- url: url.to_string(),- title: info.title.clone(),- author: info.author.clone(),- thumbnail_url: info.thumbnail_url.clone(),- duration_seconds: info.duration_seconds,- };- let _ = app.emit("media-info-preview", preview);- }- }- Ok(Err(e)) => tracing::warn!(- "[perf] prefetch_info: failed in {:?} — {}",- _timer_start.elapsed(),- e- ),- Err(_) => tracing::warn!(- "[perf] prefetch_info: timed out after {:?}",- _timer_start.elapsed()- ),- }-}--pub async fn try_start_next(app: tauri::AppHandle, queue: Arc<tokio::sync::Mutex<DownloadQueue>>) {- let _timer_start = std::time::Instant::now();- let (next_ids, stagger, state_to_emit) = {- let mut q = queue.lock().await;- let ids = q.next_queued_ids();- for nid in &ids {- q.mark_active(*nid);- }- let state = if !ids.is_empty() {- Some(q.get_state())- } else {- None- };- (ids, q.stagger_delay_ms, state)- };-- if let Some(state) = state_to_emit {- emit_queue_state_from_state(&app, state);- }-- let batch_size = next_ids.len();- for (i, nid) in next_ids.into_iter().enumerate() {- let _ = app.emit(- "queue-item-progress",- &QueueItemProgress {- id: nid,- title: String::new(),- platform: String::new(),- percent: 0.0,- speed_bytes_per_sec: 0.0,- downloaded_bytes: 0,- total_bytes: None,- phase: "queued_starting".to_string(),- eta_seconds: None,- },- );-- if i > 0 {- let item_platform = {- let q = queue.lock().await;- q.items- .iter()- .find(|item| item.id == nid)- .map(|item| item.platform.clone())- };- let delay_ms = if item_platform.as_deref() == Some("youtube") {- 2000- } else if batch_size > 3 {- stagger.max(1000)- } else {- stagger- };- if delay_ms > 0 {- tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;- }- }- let app_c = app.clone();- let queue_c = queue.clone();- tokio::spawn(async move {- spawn_download(app_c, queue_c, nid).await;- });- }- tracing::debug!("[perf] try_start_next took {:?}", _timer_start.elapsed());-}--// Periodic tick so a future-scheduled download still starts when its time-// arrives even if the queue is otherwise idle, and so a download with a-// stop time is cancelled when that time passes.-pub fn start_scheduler(app: tauri::AppHandle) {- tauri::async_runtime::spawn(async move {- tokio::time::sleep(std::time::Duration::from_secs(15)).await;- loop {- let state = app.state::<crate::AppState>();- let queue = state.download_queue.clone();- let (has_due, stopped_any) = {- let q = queue.lock().await;- let now = now_ms();- let mut stopped = false;- for item in &q.items {- if item.status == QueueStatus::Active {- if let Some(stop) = item.stop_at_ms {- if now >= stop {- item.cancel_token.cancel();- stopped = true;- }- }- }- }- let due = q.items.iter().any(|i| {- i.status == QueueStatus::Queued- && i.scheduled_at_ms.map(|t| now >= t).unwrap_or(false)- });- (due, stopped)- };- if has_due || stopped_any {- try_start_next(app.clone(), queue.clone()).await;- }- tokio::time::sleep(std::time::Duration::from_secs(15)).await;- }- });-}--fn is_generic_title(title: &str) -> bool {- let t = title.to_lowercase();- let t = t.trim();- t.is_empty()- || t == "video"- || t == "media"- || t == "untitled"- || t == "unknown"- || t.starts_with("video [video]")- || t.starts_with("media [media]")-}--#[cfg(test)]-mod kind_tests {- use super::{kind_from_platform, QueueKind};-- #[test]- fn youtube_and_video_platforms_map_to_video() {- assert_eq!(kind_from_platform("youtube"), QueueKind::Video);- assert_eq!(kind_from_platform("vimeo"), QueueKind::Video);- assert_eq!(kind_from_platform("twitch"), QueueKind::Video);- assert_eq!(kind_from_platform("bilibili"), QueueKind::Video);- assert_eq!(kind_from_platform("tiktok"), QueueKind::Video);- assert_eq!(kind_from_platform("instagram"), QueueKind::Video);- assert_eq!(kind_from_platform("reddit"), QueueKind::Video);- assert_eq!(kind_from_platform("bluesky"), QueueKind::Video);- assert_eq!(kind_from_platform("generic_ytdlp"), QueueKind::Video);- }-- #[test]- fn audio_platforms() {- assert_eq!(kind_from_platform("soundcloud"), QueueKind::Audio);- assert_eq!(kind_from_platform("spotify"), QueueKind::Audio);- }-- #[test]- fn pinterest_is_image() {- assert_eq!(kind_from_platform("pinterest"), QueueKind::Image);- }-- #[test]- fn pdf_kind() {- assert_eq!(kind_from_platform("pdf"), QueueKind::Pdf);- }-- #[test]- fn book_platforms() {- assert_eq!(kind_from_platform("annas_archive"), QueueKind::Book);- assert_eq!(kind_from_platform("libgen"), QueueKind::Book);- assert_eq!(kind_from_platform("gutendex"), QueueKind::Book);- assert_eq!(kind_from_platform("book"), QueueKind::Book);- }-- #[test]- fn webpage_kind() {- assert_eq!(kind_from_platform("webpage"), QueueKind::Webpage);- assert_eq!(kind_from_platform("embed"), QueueKind::Webpage);- }-- #[test]- fn telegram_kind() {- assert_eq!(kind_from_platform("telegram"), QueueKind::TelegramMedia);- assert_eq!(- kind_from_platform("telegram_media"),- QueueKind::TelegramMedia- );- }-- #[test]- fn course_lesson_kind() {- assert_eq!(kind_from_platform("courses"), QueueKind::CourseLesson);- assert_eq!(kind_from_platform("course_lesson"), QueueKind::CourseLesson);- }-- #[test]- fn generic_for_torrents_and_p2p() {- assert_eq!(kind_from_platform("magnet"), QueueKind::Generic);- assert_eq!(kind_from_platform("p2p"), QueueKind::Generic);- assert_eq!(kind_from_platform("torrent"), QueueKind::Generic);- }-- #[test]- fn unknown_platform_falls_back_to_generic() {- assert_eq!(kind_from_platform(""), QueueKind::Generic);- assert_eq!(kind_from_platform("totally-unknown"), QueueKind::Generic);- assert_eq!(kind_from_platform("xyz123"), QueueKind::Generic);- }-- #[test]- fn case_insensitive() {- assert_eq!(kind_from_platform("YouTube"), QueueKind::Video);- assert_eq!(kind_from_platform("TELEGRAM"), QueueKind::TelegramMedia);- }-}+use std::collections::HashMap;+use std::path::PathBuf;+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::{Arc, OnceLock};++static EMIT_COUNT: AtomicU64 = AtomicU64::new(0);++pub fn now_ms() -> u64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_millis() as 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;+use tokio_util::sync::CancellationToken;++fn shared_http_client() -> &'static reqwest::Client {+ static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();+ CLIENT.get_or_init(|| {+ crate::core::http_client::apply_global_proxy(reqwest::Client::builder())+ .build()+ .unwrap_or_default()+ })+}++use crate::core::ffmpeg::{self, MetadataEmbed};+use crate::models::media::MediaInfo;+use crate::platforms::traits::PlatformDownloader;+use crate::storage::config;++struct CachedInfo {+ info: MediaInfo,+ cached_at: std::time::Instant,+}++static INFO_CACHE: OnceLock<tokio::sync::Mutex<HashMap<String, CachedInfo>>> = OnceLock::new();++fn info_cache() -> &'static tokio::sync::Mutex<HashMap<String, CachedInfo>> {+ INFO_CACHE.get_or_init(|| tokio::sync::Mutex::new(HashMap::new()))+}++const INFO_CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(600);++static IN_FLIGHT_FETCHES: OnceLock<+ tokio::sync::Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,+> = OnceLock::new();++fn in_flight_map() -> &'static tokio::sync::Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>> {+ IN_FLIGHT_FETCHES.get_or_init(|| tokio::sync::Mutex::new(HashMap::new()))+}++#[derive(Debug, Clone, Serialize)]+pub struct MediaPreviewEvent {+ pub url: String,+ pub title: String,+ pub author: String,+ pub thumbnail_url: Option<String>,+ pub duration_seconds: Option<f64>,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, serde::Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum QueueKind {+ Video,+ Audio,+ Image,+ Pdf,+ Book,+ Webpage,+ TelegramMedia,+ CourseLesson,+ Generic,+}++pub fn kind_from_platform(platform: &str) -> QueueKind {+ let p = platform.to_ascii_lowercase();+ match p.as_str() {+ "youtube" | "vimeo" | "twitch" | "bilibili" | "tiktok" | "twitter" | "x" | "instagram"+ | "reddit" | "bluesky" | "facebook" | "generic_ytdlp" => QueueKind::Video,+ "soundcloud" | "spotify" => QueueKind::Audio,+ "pinterest" => QueueKind::Image,+ "magnet" | "p2p" | "torrent" => QueueKind::Generic,+ "telegram" | "telegram_media" => QueueKind::TelegramMedia,+ "courses" | "course_lesson" => QueueKind::CourseLesson,+ "annas_archive" | "book" | "libgen" | "gutendex" => QueueKind::Book,+ "pdf" => QueueKind::Pdf,+ "webpage" | "embed" => QueueKind::Webpage,+ _ => QueueKind::Generic,+ }+}++#[derive(Debug, Clone, Serialize, PartialEq)]+#[serde(tag = "type", content = "data")]+pub enum QueueStatus {+ Queued,+ Active,+ Paused,+ Seeding,+ Complete { success: bool },+ Error { message: String, retryable: bool },+}++pub fn is_retryable_error_message(message: &str) -> bool {+ let lower = message.to_lowercase();+ if lower.contains("cancel") {+ return false;+ }+ let (category, _) = omniget_core::core::errors::classify_download_error(message);+ matches!(category, "unknown" | "rate_limited")+}++#[derive(Clone, Serialize)]+pub struct QueueItemInfo {+ pub id: u64,+ pub url: String,+ pub platform: String,+ pub title: String,+ pub status: QueueStatus,+ pub percent: f64,+ pub speed_bytes_per_sec: f64,+ pub downloaded_bytes: u64,+ pub total_bytes: Option<u64>,+ pub file_path: Option<String>,+ pub file_size_bytes: Option<u64>,+ pub file_count: Option<u32>,+ pub thumbnail_url: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub kind: Option<QueueKind>,+ #[serde(default)]+ pub external: bool,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub eta_seconds: Option<u64>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub quality: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub download_mode: Option<String>,+}++pub struct QueueItem {+ pub id: u64,+ pub url: String,+ pub platform: String,+ pub title: String,+ pub status: QueueStatus,+ pub cancel_token: CancellationToken,+ pub output_dir: String,+ pub download_mode: Option<String>,+ pub quality: Option<String>,+ pub format_id: Option<String>,+ pub referer: Option<String>,+ pub extra_headers: Option<std::collections::HashMap<String, String>>,+ pub page_url: Option<String>,+ pub user_agent: Option<String>,+ pub percent: f64,+ pub speed_bytes_per_sec: f64,+ pub downloaded_bytes: u64,+ pub total_bytes: Option<u64>,+ pub file_path: Option<String>,+ pub file_size_bytes: Option<u64>,+ pub file_count: Option<u32>,+ pub media_info: Option<MediaInfo>,+ pub downloader: Arc<dyn PlatformDownloader>,+ pub ytdlp_path: Option<PathBuf>,+ pub from_hotkey: bool,+ pub torrent_id: Option<usize>,+ pub kind: Option<QueueKind>,+ pub external: bool,+ pub thumbnail_url_override: Option<String>,+ pub retry_count: u32,+ pub max_retries: u32,+ pub resume_state: Option<serde_json::Value>,+ pub concurrent_segments: Option<usize>,+ pub segment_size_bytes: Option<u64>,+ pub eta_seconds: Option<u64>,+ pub cookie_slug: Option<String>,+ pub custom_ytdlp_args: Option<Vec<String>>,+ pub torrent_files: Option<Vec<usize>>,+ pub scheduled_at_ms: Option<u64>,+ pub stop_at_ms: Option<u64>,+}++impl QueueItem {+ pub fn to_info(&self) -> QueueItemInfo {+ QueueItemInfo {+ id: self.id,+ url: self.url.clone(),+ platform: self.platform.clone(),+ title: self.title.clone(),+ status: self.status.clone(),+ percent: self.percent,+ speed_bytes_per_sec: self.speed_bytes_per_sec,+ downloaded_bytes: self.downloaded_bytes,+ total_bytes: self.total_bytes,+ file_path: self.file_path.clone(),+ file_size_bytes: self.file_size_bytes,+ file_count: self.file_count,+ thumbnail_url: self.thumbnail_url_override.clone().or_else(|| {+ self.media_info+ .as_ref()+ .and_then(|m| m.thumbnail_url.clone())+ }),+ kind: self.kind,+ external: self.external,+ eta_seconds: self.eta_seconds,+ quality: self.quality.clone(),+ download_mode: self.download_mode.clone(),+ }+ }+}++pub struct DownloadQueue {+ pub items: Vec<QueueItem>,+ pub max_concurrent: u32,+ pub stagger_delay_ms: u64,+ pub default_max_retries: u32,+}++impl DownloadQueue {+ pub fn new(max_concurrent: u32) -> Self {+ Self {+ items: Vec::new(),+ max_concurrent,+ stagger_delay_ms: 150,+ default_max_retries: 3,+ }+ }++ #[allow(clippy::too_many_arguments)]+ pub fn enqueue(+ &mut self,+ id: u64,+ url: String,+ platform: String,+ title: String,+ output_dir: String,+ download_mode: Option<String>,+ quality: Option<String>,+ format_id: Option<String>,+ referer: Option<String>,+ extra_headers: Option<std::collections::HashMap<String, String>>,+ page_url: Option<String>,+ user_agent: Option<String>,+ media_info: Option<MediaInfo>,+ total_bytes: Option<u64>,+ file_count: Option<u32>,+ downloader: Arc<dyn PlatformDownloader>,+ ytdlp_path: Option<PathBuf>,+ from_hotkey: bool,+ cookie_slug: Option<String>,+ custom_ytdlp_args: Option<Vec<String>>,+ torrent_files: Option<Vec<usize>>,+ scheduled_at_ms: Option<u64>,+ stop_at_ms: Option<u64>,+ ) {+ let computed_kind = Some(kind_from_platform(&platform));+ let item = QueueItem {+ id,+ url,+ platform,+ title,+ status: QueueStatus::Queued,+ cancel_token: CancellationToken::new(),+ output_dir,+ download_mode,+ quality,+ format_id,+ referer,+ extra_headers,+ page_url,+ user_agent,+ percent: 0.0,+ speed_bytes_per_sec: 0.0,+ downloaded_bytes: 0,+ total_bytes,+ file_path: None,+ file_size_bytes: None,+ file_count,+ media_info,+ downloader,+ ytdlp_path,+ from_hotkey,+ torrent_id: None,+ kind: computed_kind,+ external: false,+ thumbnail_url_override: None,+ retry_count: 0,+ max_retries: self.default_max_retries,+ resume_state: None,+ concurrent_segments: None,+ segment_size_bytes: None,+ eta_seconds: None,+ cookie_slug,+ custom_ytdlp_args,+ torrent_files,+ scheduled_at_ms,+ stop_at_ms,+ };+ crate::core::recovery::persist(crate::core::recovery::RecoveryItem {+ id: item.id,+ url: item.url.clone(),+ title: item.title.clone(),+ platform: item.platform.clone(),+ output_dir: item.output_dir.clone(),+ download_mode: item.download_mode.clone(),+ quality: item.quality.clone(),+ format_id: item.format_id.clone(),+ referer: item.referer.clone(),+ });+ self.items.push(item);+ }++ pub fn hydrate_from_history(&mut self) {+ let entries = crate::core::queue_history::list();+ if entries.is_empty() {+ return;+ }+ let placeholder: Arc<dyn PlatformDownloader> =+ Arc::new(crate::platforms::noop::NoopDownloader::new());+ for entry in entries.iter().rev() {+ if self.items.iter().any(|i| i.id == entry.id) {+ continue;+ }+ let status = if entry.success {+ QueueStatus::Complete { success: true }+ } else {+ let msg = entry.error.clone().unwrap_or_default();+ let retryable = is_retryable_error_message(&msg);+ QueueStatus::Error {+ message: msg,+ retryable,+ }+ };+ let percent = if entry.success { 100.0 } else { 0.0 };+ let item = QueueItem {+ id: entry.id,+ url: entry.url.clone(),+ platform: entry.platform.clone(),+ title: entry.title.clone(),+ status,+ cancel_token: CancellationToken::new(),+ output_dir: entry+ .file_path+ .as_ref()+ .and_then(|p| {+ std::path::Path::new(p)+ .parent()+ .map(|x| x.to_string_lossy().to_string())+ })+ .unwrap_or_default(),+ download_mode: None,+ quality: None,+ format_id: None,+ referer: None,+ extra_headers: None,+ page_url: None,+ user_agent: None,+ percent,+ speed_bytes_per_sec: 0.0,+ downloaded_bytes: entry.file_size_bytes.unwrap_or(0),+ total_bytes: entry.total_bytes,+ file_path: entry.file_path.clone(),+ file_size_bytes: entry.file_size_bytes,+ file_count: None,+ media_info: None,+ downloader: placeholder.clone(),+ ytdlp_path: None,+ from_hotkey: false,+ torrent_id: None,+ kind: entry.kind,+ external: false,+ thumbnail_url_override: entry.thumbnail_url.clone(),+ retry_count: 0,+ max_retries: 0,+ resume_state: None,+ concurrent_segments: None,+ segment_size_bytes: None,+ eta_seconds: None,+ cookie_slug: None,+ custom_ytdlp_args: None,+ torrent_files: None,+ scheduled_at_ms: None,+ stop_at_ms: None,+ };+ self.items.push(item);+ }+ }++ pub fn active_count(&self) -> u32 {+ self.items+ .iter()+ .filter(|i| i.status == QueueStatus::Active)+ .count() as u32+ }++ pub fn next_queued_ids(&self) -> Vec<u64> {+ let slots = self.max_concurrent.saturating_sub(self.active_count()) as usize;+ let now = now_ms();+ self.items+ .iter()+ .filter(|i| i.status == QueueStatus::Queued)+ .filter(|i| i.scheduled_at_ms.map(|t| now >= t).unwrap_or(true))+ .take(slots)+ .map(|i| i.id)+ .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 && i.status == QueueStatus::Queued)+ {+ item.status = QueueStatus::Active;+ item.cancel_token = CancellationToken::new();+ }+ }++ pub fn mark_complete(+ &mut self,+ id: u64,+ success: bool,+ error: Option<String>,+ file_path: Option<String>,+ file_size_bytes: Option<u64>,+ ) {+ if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {+ let error_for_history = error.clone();+ if success {+ item.status = QueueStatus::Complete { success: true };+ item.percent = 100.0;+ } else {+ let msg = error.unwrap_or_default();+ let retryable = is_retryable_error_message(&msg);+ item.status = QueueStatus::Error {+ message: msg,+ retryable,+ };+ }+ item.file_path = file_path;+ item.file_size_bytes = file_size_bytes;+ item.speed_bytes_per_sec = 0.0;+ item.eta_seconds = None;+ crate::core::recovery::remove(id);++ if !item.external {+ let entry = crate::core::queue_history::HistoryEntry {+ id: item.id,+ url: item.url.clone(),+ platform: item.platform.clone(),+ title: item.title.clone(),+ file_path: item.file_path.clone(),+ file_size_bytes: item.file_size_bytes,+ total_bytes: item.total_bytes,+ success,+ error: if success { None } else { error_for_history },+ completed_at: crate::core::queue_history::now_unix_seconds(),+ thumbnail_url: item.thumbnail_url_override.clone().or_else(|| {+ item.media_info+ .as_ref()+ .and_then(|m| m.thumbnail_url.clone())+ }),+ kind: item.kind,+ };+ crate::core::queue_history::record(entry);+ }+ }+ }++ pub fn mark_seeding(+ &mut self,+ id: u64,+ file_path: Option<String>,+ file_size_bytes: Option<u64>,+ torrent_id: Option<usize>,+ ) {+ if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {+ item.status = QueueStatus::Seeding;+ item.percent = 100.0;+ item.file_path = file_path;+ item.file_size_bytes = file_size_bytes;+ item.speed_bytes_per_sec = 0.0;+ item.torrent_id = torrent_id;+ crate::core::recovery::remove(id);+ }+ }++ pub fn update_progress(+ &mut self,+ id: u64,+ percent: f64,+ speed: f64,+ downloaded: u64,+ total: Option<u64>,+ torrent_id: Option<usize>,+ eta_seconds: Option<u64>,+ ) {+ if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {+ if item.status != QueueStatus::Active {+ if torrent_id.is_some() && item.torrent_id.is_none() {+ item.torrent_id = torrent_id;+ }+ return;+ }+ item.percent = percent;+ item.speed_bytes_per_sec = speed;+ item.downloaded_bytes = downloaded;+ if let Some(t) = total {+ item.total_bytes = Some(t);+ }+ if torrent_id.is_some() && item.torrent_id.is_none() {+ item.torrent_id = torrent_id;+ }+ item.eta_seconds = eta_seconds;+ }+ }++ 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"+ && !omniget_core::core::ytdlp::pause_download_process(id)+ {+ return false;+ }+ item.status = QueueStatus::Paused;+ item.speed_bytes_per_sec = 0.0;+ item.eta_seconds = None;+ return true;+ }+ }+ false+ }++ 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"+ && !omniget_core::core::ytdlp::resume_download_process(id)+ {+ return false;+ }+ item.status = QueueStatus::Active;+ return true;+ }+ }+ false+ }++ pub fn pause_all(&mut self) -> Vec<(u64, Option<usize>)> {+ let mut paused = Vec::new();+ for item in self.items.iter_mut() {+ if item.status == QueueStatus::Active {+ 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;+ item.eta_seconds = None;+ paused.push((item.id, item.torrent_id));+ }+ }+ paused+ }++ pub fn resume_all(&mut self) -> Vec<(u64, Option<usize>)> {+ let mut resumed = Vec::new();+ for item in self.items.iter_mut() {+ if item.status == QueueStatus::Paused {+ let tid = item.torrent_id;+ if item.platform != "magnet"+ && !omniget_core::core::ytdlp::resume_download_process(item.id)+ {+ continue;+ }+ item.status = QueueStatus::Active;+ resumed.push((item.id, tid));+ }+ }+ resumed+ }++ pub fn reorder(&mut self, ids_in_order: Vec<u64>) -> bool {+ let mut slots: Vec<Option<QueueItem>> = self.items.drain(..).map(Some).collect();++ let queued_slot_indices: Vec<usize> = slots+ .iter()+ .enumerate()+ .filter_map(|(idx, slot)| {+ slot.as_ref()+ .filter(|i| i.status == QueueStatus::Queued)+ .map(|_| idx)+ })+ .collect();++ if queued_slot_indices.is_empty() {+ self.items = slots.into_iter().flatten().collect();+ return false;+ }++ let queued_id_to_slot: std::collections::HashMap<u64, usize> = queued_slot_indices+ .iter()+ .map(|idx| (slots[*idx].as_ref().unwrap().id, *idx))+ .collect();++ let mut new_queued_order: Vec<QueueItem> = Vec::with_capacity(queued_slot_indices.len());+ let mut seen: std::collections::HashSet<u64> = std::collections::HashSet::new();++ for id in &ids_in_order {+ if seen.contains(id) {+ continue;+ }+ if let Some(slot_idx) = queued_id_to_slot.get(id) {+ if let Some(item) = slots[*slot_idx].take() {+ new_queued_order.push(item);+ seen.insert(*id);+ }+ }+ }+ for idx in &queued_slot_indices {+ if let Some(item) = slots[*idx].take() {+ new_queued_order.push(item);+ }+ }++ let mut iter = new_queued_order.into_iter();+ let mut rebuilt: Vec<QueueItem> = Vec::with_capacity(slots.len());+ for (idx, slot) in slots.into_iter().enumerate() {+ if queued_slot_indices.contains(&idx) {+ if let Some(item) = iter.next() {+ rebuilt.push(item);+ }+ } else if let Some(item) = slot {+ rebuilt.push(item);+ }+ }+ rebuilt.extend(iter);+ self.items = rebuilt;+ true+ }++ /// Cancel an item. Returns the torrent_id if the item needs torrent cleanup (caller should delete from session).+ pub fn cancel(&mut self, id: u64) -> (bool, Option<usize>) {+ let result = self.cancel_inner(id);+ if result.0 {+ crate::core::recovery::remove(id);+ }+ result+ }++ fn cancel_inner(&mut self, id: u64) -> (bool, Option<usize>) {+ if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {+ match &item.status {+ QueueStatus::Active => {+ item.cancel_token.cancel();+ item.status = QueueStatus::Error {+ message: "Cancelled".to_string(),+ retryable: false,+ };+ item.speed_bytes_per_sec = 0.0;+ return (true, None);+ }+ QueueStatus::Seeding => {+ let tid = item.torrent_id;+ item.status = QueueStatus::Error {+ message: "Cancelled".to_string(),+ retryable: false,+ };+ item.speed_bytes_per_sec = 0.0;+ return (true, tid);+ }+ QueueStatus::Paused => {+ // For magnet downloads, the cancel_token was not cancelled during pause,+ // so we must cancel it now to stop the background download loop.+ // Also return the torrent_id for session cleanup.+ item.cancel_token.cancel();+ let tid = if item.platform == "magnet" {+ item.torrent_id+ } else {+ None+ };+ item.status = QueueStatus::Error {+ message: "Cancelled".to_string(),+ retryable: false,+ };+ item.speed_bytes_per_sec = 0.0;+ return (true, tid);+ }+ QueueStatus::Queued => {+ item.status = QueueStatus::Error {+ message: "Cancelled".to_string(),+ retryable: false,+ };+ return (true, None);+ }+ _ => {}+ }+ }+ (false, None)+ }++ pub fn retry(&mut self, id: u64) -> bool {+ if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {+ if matches!(item.status, QueueStatus::Error { .. }) {+ item.status = QueueStatus::Queued;+ item.cancel_token = CancellationToken::new();+ item.percent = 0.0;+ item.speed_bytes_per_sec = 0.0;+ item.downloaded_bytes = 0;+ item.file_path = None;+ item.file_size_bytes = None;+ item.retry_count = 0;+ return true;+ }+ }+ false+ }++ /// Remove an item. Returns the torrent_id if the item needs torrent cleanup (caller should delete from session).+ pub fn remove(&mut self, id: u64) -> Option<Option<usize>> {+ let result = self.remove_inner(id);+ if result.is_some() {+ crate::core::recovery::remove(id);+ crate::core::queue_history::remove(id);+ }+ result+ }++ fn remove_inner(&mut self, id: u64) -> Option<Option<usize>> {+ if let Some(pos) = self.items.iter().position(|i| i.id == id) {+ let item = &self.items[pos];+ if item.status == QueueStatus::Active {+ item.cancel_token.cancel();+ }+ // For paused magnet items, the cancel_token was not cancelled during pause+ if item.status == QueueStatus::Paused && item.platform == "magnet" {+ item.cancel_token.cancel();+ }+ let torrent_id = if item.status == QueueStatus::Seeding+ || (item.status == QueueStatus::Paused && item.platform == "magnet")+ {+ item.torrent_id+ } else {+ None+ };+ self.items.remove(pos);+ return Some(torrent_id);+ }+ None+ }++ pub fn clear_finished(&mut self) {+ let to_remove: Vec<u64> = self+ .items+ .iter()+ .filter(|i| matches!(i.status, QueueStatus::Complete { .. }))+ .map(|i| i.id)+ .collect();+ for id in &to_remove {+ crate::core::recovery::remove(*id);+ crate::core::queue_history::remove(*id);+ }+ self.items+ .retain(|i| !matches!(i.status, QueueStatus::Complete { .. }));+ }++ pub fn get_state(&self) -> Vec<QueueItemInfo> {+ self.items.iter().map(|i| i.to_info()).collect()+ }++ pub fn has_url(&self, url: &str) -> bool {+ self.items.iter().any(|i| {+ i.url == url+ && matches!(+ i.status,+ QueueStatus::Queued+ | QueueStatus::Active+ | QueueStatus::Paused+ | QueueStatus::Seeding+ )+ })+ }+}++pub struct ProgressThrottle {+ last_emit: std::time::Instant,+ min_interval: std::time::Duration,+}++impl ProgressThrottle {+ pub fn new(min_interval_ms: u64) -> Self {+ Self {+ last_emit: std::time::Instant::now() - std::time::Duration::from_secs(10),+ min_interval: std::time::Duration::from_millis(min_interval_ms),+ }+ }++ pub fn should_emit(&mut self) -> bool {+ let now = std::time::Instant::now();+ if now.duration_since(self.last_emit) >= self.min_interval {+ self.last_emit = now;+ true+ } else {+ false+ }+ }+}++#[derive(Clone, Serialize)]+pub struct QueueItemProgress {+ pub id: u64,+ pub title: String,+ pub platform: String,+ pub percent: f64,+ pub speed_bytes_per_sec: f64,+ pub downloaded_bytes: u64,+ pub total_bytes: Option<u64>,+ pub phase: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub eta_seconds: Option<u64>,+}++pub fn emit_queue_state_from_state(app: &tauri::AppHandle, state: Vec<QueueItemInfo>) {+ let n = EMIT_COUNT.fetch_add(1, Ordering::Relaxed);+ if n.is_multiple_of(10) {+ tracing::debug!("[perf] emit_queue_state called {} times", n);+ }+ let _ = app.emit("queue-state-update", &state);+ let total = crate::tray::compute_total_active(app);+ crate::tray::update_active_count(app, total);+ crate::core::awake::sync(total > 0);++ let active_items: Vec<_> = state+ .iter()+ .filter(|i| i.status == QueueStatus::Active)+ .collect();+ let avg_percent = if !active_items.is_empty() {+ let sum: f64 = active_items.iter().map(|i| i.percent).sum();+ sum / active_items.len() as f64 / 100.0+ } else {+ 0.0+ };+ let total_speed: f64 = active_items.iter().map(|i| i.speed_bytes_per_sec).sum();+ crate::tray::update_speed_tooltip(app, total, total_speed);+ crate::tray::update_taskbar_badge(app, total, avg_percent);++ if let Some(window) = app.get_webview_window("main") {+ let title = if total > 0 {+ format!("({}) omniget", total)+ } else {+ "omniget".into()+ };+ let _ = window.set_title(&title);+ }+}++pub fn emit_queue_state(app: &tauri::AppHandle, queue: &DownloadQueue) {+ let state = queue.get_state();+ emit_queue_state_from_state(app, state);+}++/// RAII guard that ensures an Active queue item never leaks a slot.+///+/// If the download future panics or is dropped before reaching `mark_complete`+/// / `mark_seeding`, the Drop impl spawns a task that transitions the item to+/// Error("Download interrupted") and calls `try_start_next`, unblocking the+/// queue.+///+/// When the download reaches a terminal state through the normal paths, the+/// guard sees the item is no longer Active and does nothing (idempotent).+struct ActiveJobSlot {+ app: tauri::AppHandle,+ queue: Arc<tokio::sync::Mutex<DownloadQueue>>,+ item_id: u64,+ armed: bool,+}++impl ActiveJobSlot {+ fn new(+ app: tauri::AppHandle,+ queue: Arc<tokio::sync::Mutex<DownloadQueue>>,+ item_id: u64,+ ) -> Self {+ Self {+ app,+ queue,+ item_id,+ armed: true,+ }+ }++ fn disarm(mut self) {+ self.armed = false;+ }+}++impl Drop for ActiveJobSlot {+ fn drop(&mut self) {+ if !self.armed {+ return;+ }+ let app = self.app.clone();+ let queue = self.queue.clone();+ let item_id = self.item_id;+ tokio::spawn(async move {+ let state = {+ let mut q = queue.lock().await;+ let still_active = q+ .items+ .iter()+ .find(|i| i.id == item_id)+ .map(|i| i.status == QueueStatus::Active)+ .unwrap_or(false);+ if !still_active {+ return;+ }+ tracing::warn!(+ "[queue] ActiveJobSlot guard firing for {} — download ended without clean release",+ item_id+ );+ q.mark_complete(+ item_id,+ false,+ Some("Download interrupted".to_string()),+ None,+ None,+ );+ q.get_state()+ };+ emit_queue_state_from_state(&app, state);+ try_start_next(app, queue).await;+ });+ }+}++pub fn spawn_download(+ app: tauri::AppHandle,+ queue: Arc<tokio::sync::Mutex<DownloadQueue>>,+ item_id: u64,+) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> {+ Box::pin(async move {+ let _timer_start = std::time::Instant::now();+ let slot = ActiveJobSlot::new(app.clone(), queue.clone(), item_id);+ spawn_download_inner(app, queue, item_id).await;+ slot.disarm();+ tracing::debug!(+ "[perf] spawn_download {} took {:?}",+ item_id,+ _timer_start.elapsed()+ );+ })+}++async fn spawn_download_inner(+ app: tauri::AppHandle,+ queue: Arc<tokio::sync::Mutex<DownloadQueue>>,+ item_id: u64,+) {+ tracing::info!("[queue] download {} started", item_id);++ let _ = app.emit(+ "queue-item-progress",+ &QueueItemProgress {+ id: item_id,+ title: "".to_string(),+ platform: "".to_string(),+ percent: 0.0,+ speed_bytes_per_sec: 0.0,+ downloaded_bytes: 0,+ total_bytes: None,+ phase: "preparing".to_string(),+ eta_seconds: None,+ },+ );++ let host_key = {+ let q = queue.lock().await;+ q.items+ .iter()+ .find(|i| i.id == item_id)+ .map(|i| crate::core::host_limiter::host_key_for_url(&i.url))+ };+ let _host_lease = match host_key {+ Some(key) => Some(crate::core::host_limiter::acquire(&key).await),+ None => None,+ };++ let (+ url,+ output_dir,+ download_mode,+ quality,+ format_id,+ referer,+ extra_headers,+ page_url,+ user_agent,+ cancel_token,+ media_info,+ platform_name,+ downloader,+ ytdlp_path,+ from_hotkey,+ cookie_slug,+ custom_ytdlp_args,+ torrent_files,+ ) = {+ let q = queue.lock().await;+ let item = match q.items.iter().find(|i| i.id == item_id) {+ Some(i) => i,+ None => return,+ };+ (+ item.url.clone(),+ item.output_dir.clone(),+ item.download_mode.clone(),+ item.quality.clone(),+ item.format_id.clone(),+ item.referer.clone(),+ item.extra_headers.clone(),+ item.page_url.clone(),+ item.user_agent.clone(),+ item.cancel_token.clone(),+ item.media_info.clone(),+ item.platform.clone(),+ item.downloader.clone(),+ item.ytdlp_path.clone(),+ item.from_hotkey,+ item.cookie_slug.clone(),+ item.custom_ytdlp_args.clone(),+ item.torrent_files.clone(),+ )+ };++ {+ let settings = crate::storage::config::load_settings(&app);+ let proxy = settings.proxy.clone();+ crate::core::http_client::init_proxy(proxy.clone());+ let proxy_status = if !proxy.enabled {+ "disabled; system/env proxy honored if set".to_string()+ } else if proxy.host.trim().is_empty() {+ "enabled but host is empty; falling back to system/env proxy".to_string()+ } else {+ format!(+ "enabled; {}://{}:{}",+ proxy.proxy_type, proxy.host, proxy.port+ )+ };+ append_download_log(+ &app,+ item_id,+ format!("[network] proxy setting: {}", proxy_status),+ );+ }++ let info_start = std::time::Instant::now();+ let info = match media_info {+ Some(i) if !i.available_qualities.is_empty() => {+ tracing::info!(+ "[queue] info for {} from cache/pre-fetched in {:?}",+ item_id,+ info_start.elapsed()+ );+ append_download_log(+ &app,+ item_id,+ format!(+ "[omniget] using cached video info: platform={} title=\"{}\"",+ platform_name, i.title+ ),+ );+ i+ }+ _ => {+ tracing::debug!(+ "[perf] spawn_download_inner {}: media_info is None, fetching info",+ item_id+ );+ append_download_log(+ &app,+ item_id,+ format!(+ "[omniget] fetching video info: platform={} url={}",+ platform_name, url+ ),+ );+ if let Some(slug) = cookie_slug.as_deref() {+ append_download_log(+ &app,+ item_id,+ format!("[cookies] selected managed cookie account: {}", slug),+ );+ }+ let _ = app.emit(+ "queue-item-progress",+ &QueueItemProgress {+ id: item_id,+ title: url.clone(),+ platform: platform_name.clone(),+ percent: 0.0,+ speed_bytes_per_sec: 0.0,+ downloaded_bytes: 0,+ total_bytes: None,+ phase: "fetching_info".to_string(),+ eta_seconds: None,+ },+ );++ let info_future =+ fetch_and_cache_info(&url, &*downloader, &platform_name, ytdlp_path.as_deref());+ let scoped_info_future = omniget_core::core::log_hook::CURRENT_COOKIE_SLUG.scope(+ cookie_slug.clone(),+ omniget_core::core::log_hook::CURRENT_DOWNLOAD_ID.scope(item_id, info_future),+ );+ let info_timeout_secs = if platform_name == "youtube"+ || url.to_ascii_lowercase().contains("youtube.com")+ || url.to_ascii_lowercase().contains("youtu.be")+ {+ omniget_core::core::ytdlp::YOUTUBE_VIDEO_INFO_TOTAL_TIMEOUT_SECS+ } else if platform_name == "douyin" {+ 30+ } else {+ omniget_core::core::ytdlp::DEFAULT_VIDEO_INFO_TOTAL_TIMEOUT_SECS+ };+ let info_result = tokio::time::timeout(+ std::time::Duration::from_secs(info_timeout_secs),+ scoped_info_future,+ )+ .await;++ match info_result {+ Ok(Ok(i)) => {+ append_download_log(+ &app,+ item_id,+ format!(+ "[omniget] video info fetched in {:.1}s: title=\"{}\"",+ info_start.elapsed().as_secs_f64(),+ i.title+ ),+ );+ i+ }+ Ok(Err(e)) => {+ append_download_log(+ &app,+ item_id,+ format!(+ "[omniget] failed fetching video info after {:.1}s: {}",+ info_start.elapsed().as_secs_f64(),+ e+ ),+ );+ let state = {+ let mut q = queue.lock().await;+ q.mark_complete(item_id, false, Some(e.to_string()), None, None);+ q.get_state()+ };+ emit_queue_state_from_state(&app, state);+ try_start_next(app, queue).await;+ return;+ }+ Err(_) => {+ tracing::warn!(+ "[queue] info fetch timed out for {} after {}s",+ item_id,+ info_timeout_secs+ );+ append_download_log(+ &app,+ item_id,+ format!(+ "[omniget] video info timed out after {}s",+ info_timeout_secs+ ),+ );+ let state = {+ let mut q = queue.lock().await;+ q.mark_complete(+ item_id,+ false,+ Some("Timed out fetching video info".to_string()),+ None,+ None,+ );+ q.get_state()+ };+ emit_queue_state_from_state(&app, state);+ try_start_next(app, queue).await;+ return;+ }+ }+ }+ };+ tracing::info!(+ "[queue] info fetch for {} took {:?}",+ item_id,+ info_start.elapsed()+ );++ let mut info = info;+ if is_generic_title(&info.title) {+ let pokemon = omniget_core::core::pokemon_names::random_pokemon_name();+ info.title = format!("video_{}", pokemon);+ }++ let state = {+ let mut q = queue.lock().await;+ if let Some(item) = q.items.iter_mut().find(|i| i.id == item_id) {+ item.title = info.title.clone();+ item.total_bytes = info.file_size_bytes;+ let fc = if info.media_type == crate::models::media::MediaType::Carousel+ || info.media_type == crate::models::media::MediaType::Playlist+ {+ info.available_qualities.len() as u32+ } else {+ 1+ };+ item.file_count = Some(fc);+ item.media_info = Some(info.clone());+ }+ q.get_state()+ };+ emit_queue_state_from_state(&app, state);++ let _ = app.emit(+ "queue-item-progress",+ &QueueItemProgress {+ id: item_id,+ title: info.title.clone(),+ platform: platform_name.clone(),+ percent: 0.5,+ speed_bytes_per_sec: 0.0,+ downloaded_bytes: 0,+ total_bytes: info.file_size_bytes,+ phase: "starting".to_string(),+ eta_seconds: None,+ },+ );++ let settings = config::load_settings(&app);+ let tmpl = settings.download.filename_template.clone();+ let mut final_output_dir = std::path::PathBuf::from(&output_dir);+ if settings.download.organize_by_platform {+ final_output_dir = final_output_dir.join(&platform_name);+ }+ let torrent_id_slot = Arc::new(tokio::sync::Mutex::new(None));+ let audio_format = if download_mode.as_deref() == Some("audio") {+ Some(settings.download.music_audio_format.clone())+ } else {+ None+ };+ let custom_ytdlp_args = {+ let mut args = custom_ytdlp_args.clone();+ if settings.download.skip_existing {+ let flags = args.get_or_insert_with(Vec::new);+ if !flags.iter().any(|f| f == "--no-overwrites") {+ flags.push("--no-overwrites".to_string());+ }+ }+ args+ };+ let opts = crate::models::media::DownloadOptions {+ quality: quality.or_else(|| Some(settings.download.video_quality.clone())),+ output_dir: final_output_dir,+ filename_template: Some(tmpl),+ download_subtitles: settings.download.download_subtitles,+ include_auto_subtitles: settings.download.include_auto_subtitles,+ download_mode,+ audio_format,+ format_id,+ referer,+ extra_headers,+ page_url,+ user_agent,+ cancel_token: cancel_token.clone(),+ concurrent_fragments: settings.advanced.concurrent_fragments,+ ytdlp_path,+ torrent_listen_port: Some(settings.advanced.torrent_listen_port),+ torrent_id_slot: Some(torrent_id_slot.clone()),+ custom_ytdlp_args: custom_ytdlp_args.clone(),+ torrent_files: torrent_files.clone(),+ torrent_auto_trackers: settings.advanced.torrent_auto_trackers,+ torrent_upnp: settings.advanced.torrent_upnp,+ };++ 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);++ let app_progress = app.clone();+ let queue_progress = queue.clone();+ let torrent_id_slot_progress = torrent_id_slot.clone();+ let progress_forwarder = tokio::spawn(async move {+ const STALL_AFTER: std::time::Duration = std::time::Duration::from_secs(6);++ let mut last_bytes: u64 = 0;+ let mut last_time = std::time::Instant::now();+ let mut throttle = ProgressThrottle::new(250);+ let mut current_speed: f64 = 0.0;+ let mut last_percent: f64 = 0.0;+ let mut last_advance = std::time::Instant::now();+ let mut stalled = false;++ loop {+ let update = tokio::select! {+ msg = rx.recv() => match msg {+ Some(u) => u,+ None => break,+ },+ _ = tokio::time::sleep(std::time::Duration::from_secs(2)) => {+ if !stalled && last_advance.elapsed() >= STALL_AFTER {+ stalled = true;+ current_speed = 0.0;+ {+ let mut q = queue_progress.lock().await;+ let tid = { *torrent_id_slot_progress.lock().await };+ q.update_progress(+ item_id, last_percent, 0.0, last_bytes, total_bytes, tid, None,+ );+ }+ let _ = app_progress.emit(+ "queue-item-progress",+ &QueueItemProgress {+ id: item_id,+ title: item_title.clone(),+ platform: item_platform.clone(),+ percent: last_percent,+ speed_bytes_per_sec: 0.0,+ downloaded_bytes: last_bytes,+ total_bytes,+ phase: "stalled".to_string(),+ eta_seconds: None,+ },+ );+ }+ continue;+ }+ };++ let percent = update.percent;+ if !throttle.should_emit() && percent < 100.0 && !update.has_real_metrics() {+ continue;+ }++ let now = std::time::Instant::now();+ let resolved_total = update.total_bytes.or(total_bytes);+ 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;+ } else if downloaded_bytes > last_bytes {+ let dt = now.duration_since(last_time).as_secs_f64();+ if dt > 0.1 {+ let instant_speed = (downloaded_bytes - last_bytes) as f64 / dt;+ current_speed = if current_speed > 0.0 {+ current_speed * 0.7 + instant_speed * 0.3+ } else {+ instant_speed+ };+ }+ }++ if downloaded_bytes > last_bytes || clamped > last_percent || update.speed_bps.is_some()+ {+ last_advance = now;+ stalled = false;+ }+ last_bytes = downloaded_bytes;+ last_time = now;+ last_percent = clamped;++ 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",+ p if p > 0.0 => "downloading",+ _ => "starting",+ };++ let eta_seconds = update+ .eta_seconds+ .or_else(|| omniget_core::core::ytdlp::get_eta(item_id))+ .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)+ })+ } else {+ None+ }+ });++ {+ let mut q = queue_progress.lock().await;+ let tid = { *torrent_id_slot_progress.lock().await };+ q.update_progress(+ item_id,+ clamped,+ current_speed,+ downloaded_bytes,+ resolved_total,+ tid,+ eta_seconds,+ );+ }++ let _ = app_progress.emit(+ "queue-item-progress",+ &QueueItemProgress {+ id: item_id,+ title: item_title.clone(),+ platform: item_platform.clone(),+ percent: clamped,+ speed_bytes_per_sec: current_speed,+ downloaded_bytes,+ total_bytes: resolved_total,+ phase: phase.to_string(),+ eta_seconds,+ },+ );+ }+ omniget_core::core::ytdlp::clear_eta(item_id);+ });++ if let Some(ua) = opts.user_agent.clone() {+ omniget_core::core::ytdlp::register_ext_user_agent(url.clone(), ua);+ }+ if let Some(hdrs) = opts.extra_headers.clone() {+ omniget_core::core::ytdlp::register_ext_headers(url.clone(), hdrs);+ }++ 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,+ _ = cancel_token.cancelled() => {+ Err(anyhow::anyhow!("Download cancelado"))+ }+ }+ };+ let result = omniget_core::core::log_hook::CURRENT_COOKIE_SLUG+ .scope(+ cookie_slug.clone(),+ omniget_core::core::log_hook::CURRENT_DOWNLOAD_ID.scope(item_id, dl_future),+ )+ .await;+ omniget_core::core::ytdlp::clear_ext_user_agent(&url);+ omniget_core::core::ytdlp::clear_ext_headers(&url);+ tracing::info!(+ "[queue] download {} completed in {:?}",+ item_id,+ dl_start.elapsed()+ );++ let _ = progress_forwarder.await;++ let was_paused = {+ let q = queue.lock().await;+ q.items+ .iter()+ .find(|i| i.id == item_id)+ .map(|i| i.status == QueueStatus::Paused)+ .unwrap_or(false)+ };++ if was_paused {+ let state = {+ let q = queue.lock().await;+ q.get_state()+ };+ emit_queue_state_from_state(&app, state);+ try_start_next(app, queue).await;+ return;+ }++ 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+ ),+ );+ let is_seeding = platform_name == "magnet" && dl.torrent_id.is_some();+ if !is_seeding {+ if let Err(msg) = validate_download_output(&dl.file_path).await {+ tracing::error!(+ "[queue] download {} reported success but output is missing or empty: {:?}",+ item_id,+ dl.file_path+ );+ append_download_log(+ &app,+ item_id,+ format!(+ "[omniget] download reported success but output missing or empty: {}",+ dl.file_path.to_string_lossy()+ ),+ );+ let state = {+ let mut q = queue.lock().await;+ q.mark_complete(item_id, false, Some(msg), None, None);+ q.get_state()+ };+ emit_queue_state_from_state(&app, state);+ try_start_next(app, queue).await;+ return;+ }+ }++ if settings.download.embed_metadata+ && platform_name != "magnet"+ && ffmpeg::is_ffmpeg_available().await+ {+ let metadata = MetadataEmbed {+ title: Some(info.title.clone()),+ artist: Some(info.author.clone()),+ thumbnail_url: info.thumbnail_url.clone(),+ ..Default::default()+ };+ if let Err(e) = ffmpeg::embed_metadata(+ &dl.file_path,+ &metadata,+ settings.download.embed_thumbnail,+ shared_http_client(),+ )+ .await+ {+ tracing::warn!("Metadata embed failed for '{}': {}", info.title, e);+ }+ }++ if from_hotkey && settings.download.copy_to_clipboard_on_hotkey {+ #[cfg(not(target_os = "android"))]+ {+ match crate::core::clipboard::copy_file_to_clipboard(&dl.file_path).await {+ Ok(()) => {+ let _ = app.emit(+ "file-copied-to-clipboard",+ serde_json::json!({+ "path": dl.file_path.to_string_lossy(),+ }),+ );+ }+ Err(e) => {+ tracing::warn!("[clipboard] failed to copy file: {}", e);+ }+ }+ }+ }++ let state = {+ let mut q = queue.lock().await;+ if platform_name == "magnet" && dl.torrent_id.is_some() {+ q.mark_seeding(+ item_id,+ Some(dl.file_path.to_string_lossy().to_string()),+ Some(dl.file_size_bytes),+ dl.torrent_id,+ );+ } else {+ q.mark_complete(+ item_id,+ true,+ None,+ Some(dl.file_path.to_string_lossy().to_string()),+ Some(dl.file_size_bytes),+ );+ }+ q.get_state()+ };+ emit_queue_state_from_state(&app, state);+ }+ 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)+ } else {+ raw_err.clone()+ };+ tracing::error!(+ "Download error '{}' [{}]: {}",+ platform_name,+ category,+ raw_err+ );++ let retry_decision = {+ let mut q = queue.lock().await;+ if let Some(item) = q.items.iter_mut().find(|i| i.id == item_id) {+ if item.downloaded_bytes > 5 * 1024 * 1024 {+ item.retry_count = 0;+ }+ let retryable = is_retryable_category(category);+ let attempt = item.retry_count;+ let max = item.max_retries;+ if retryable && attempt < max {+ item.retry_count = attempt + 1;+ Some((attempt + 1, max))+ } else {+ None+ }+ } else {+ None+ }+ };++ if let Some((next_attempt, max)) = retry_decision {+ let delay_secs = (1u64 << (next_attempt - 1).min(5)).min(30);+ tracing::warn!(+ "[queue] retry {}/{} for {} in {}s (category={})",+ next_attempt,+ max,+ item_id,+ delay_secs,+ category+ );+ let state = {+ let mut q = queue.lock().await;+ if let Some(item) = q.items.iter_mut().find(|i| i.id == item_id) {+ item.status = QueueStatus::Queued;+ item.cancel_token = CancellationToken::new();+ item.percent = 0.0;+ item.speed_bytes_per_sec = 0.0;+ item.downloaded_bytes = 0;+ }+ q.get_state()+ };+ emit_queue_state_from_state(&app, state);+ let app_for_retry = app.clone();+ let queue_for_retry = queue.clone();+ tokio::spawn(async move {+ tokio::time::sleep(std::time::Duration::from_secs(delay_secs)).await;+ try_start_next(app_for_retry, queue_for_retry).await;+ });+ return;+ }++ let state = {+ let mut q = queue.lock().await;+ q.mark_complete(item_id, false, Some(user_msg), None, None);+ q.get_state()+ };+ emit_queue_state_from_state(&app, state);+ }+ }++ try_start_next(app, queue).await;+}++fn is_retryable_category(category: &str) -> bool {+ matches!(category, "unknown" | "rate_limited")+}++const OUTPUT_MISSING_ERROR: &str =+ "Download reported success but the file is missing or empty. Check disk space and antivirus exclusions, then retry.";++async fn validate_download_output(path: &std::path::Path) -> Result<(), String> {+ if path.as_os_str().is_empty() {+ return Err(OUTPUT_MISSING_ERROR.to_string());+ }+ let meta = match tokio::fs::metadata(path).await {+ Ok(m) => m,+ Err(_) => return Err(OUTPUT_MISSING_ERROR.to_string()),+ };+ if meta.is_dir() {+ let mut entries = match tokio::fs::read_dir(path).await {+ Ok(e) => e,+ Err(_) => return Err(OUTPUT_MISSING_ERROR.to_string()),+ };+ match entries.next_entry().await {+ Ok(Some(_)) => Ok(()),+ _ => Err(OUTPUT_MISSING_ERROR.to_string()),+ }+ } else if meta.len() > 0 {+ Ok(())+ } else {+ Err(OUTPUT_MISSING_ERROR.to_string())+ }+}++async fn fetch_and_cache_info(+ url: &str,+ downloader: &dyn PlatformDownloader,+ platform: &str,+ ytdlp_path: Option<&std::path::Path>,+) -> anyhow::Result<MediaInfo> {+ {+ let cache = info_cache().lock().await;+ if let Some(entry) = cache.get(url) {+ if entry.cached_at.elapsed() < INFO_CACHE_TTL {+ tracing::debug!("[perf] fetch_and_cache_info: cache hit for {}", platform);+ return Ok(entry.info.clone());+ }+ }+ }++ let url_lock = {+ let mut map = in_flight_map().lock().await;+ map.entry(url.to_string())+ .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))+ .clone()+ };+ let _guard = url_lock.lock().await;++ {+ let cache = info_cache().lock().await;+ if let Some(entry) = cache.get(url) {+ if entry.cached_at.elapsed() < INFO_CACHE_TTL {+ tracing::debug!(+ "[perf] fetch_and_cache_info: dedup cache hit for {}",+ platform+ );+ return Ok(entry.info.clone());+ }+ }+ }++ tracing::debug!("[perf] fetch_and_cache_info: fetching for {}", platform);+ let info = if let Some(ytdlp) = ytdlp_path {+ match platform {+ "youtube" => {+ omniget_core::platforms::YouTubeDownloader::fetch_with_ytdlp(url, ytdlp).await?+ }+ "generic" => {+ if crate::platforms::generic_ytdlp::is_direct_media_url(url).is_some() {+ downloader.get_media_info(url).await?+ } else {+ let json = crate::core::ytdlp::get_video_info(ytdlp, url, &[]).await?;+ crate::platforms::generic_ytdlp::GenericYtdlpDownloader::parse_video_info(+ &json,+ )?+ }+ }+ _ => downloader.get_media_info(url).await?,+ }+ } else {+ downloader.get_media_info(url).await?+ };++ let mut cache = info_cache().lock().await;+ cache.insert(+ url.to_string(),+ CachedInfo {+ info: info.clone(),+ cached_at: std::time::Instant::now(),+ },+ );+ if cache.len() > 50 {+ cache.retain(|_, v| v.cached_at.elapsed() < INFO_CACHE_TTL);+ }+ Ok(info)+}++pub async fn try_get_cached_info(url: &str) -> Option<MediaInfo> {+ let cache = info_cache().lock().await;+ cache+ .get(url)+ .filter(|entry| entry.cached_at.elapsed() < INFO_CACHE_TTL)+ .map(|entry| entry.info.clone())+}++pub async fn prefetch_info(+ url: &str,+ downloader: &dyn PlatformDownloader,+ platform: &str,+ ytdlp_path: Option<&std::path::Path>,+) {+ prefetch_info_with_emit(url, downloader, platform, ytdlp_path, None).await;+}++pub async fn prefetch_info_with_emit(+ url: &str,+ downloader: &dyn PlatformDownloader,+ platform: &str,+ ytdlp_path: Option<&std::path::Path>,+ app: Option<tauri::AppHandle>,+) {+ let _timer_start = std::time::Instant::now();+ tracing::debug!("[perf] prefetch_info: started");+ let result = tokio::time::timeout(+ std::time::Duration::from_secs(15),+ fetch_and_cache_info(url, downloader, platform, ytdlp_path),+ )+ .await;+ match result {+ Ok(Ok(info)) => {+ tracing::debug!(+ "[perf] prefetch_info: completed in {:?} — {}",+ _timer_start.elapsed(),+ info.title+ );+ if let Some(app) = app {+ let preview = MediaPreviewEvent {+ url: url.to_string(),+ title: info.title.clone(),+ author: info.author.clone(),+ thumbnail_url: info.thumbnail_url.clone(),+ duration_seconds: info.duration_seconds,+ };+ let _ = app.emit("media-info-preview", preview);+ }+ }+ Ok(Err(e)) => tracing::warn!(+ "[perf] prefetch_info: failed in {:?} — {}",+ _timer_start.elapsed(),+ e+ ),+ Err(_) => tracing::warn!(+ "[perf] prefetch_info: timed out after {:?}",+ _timer_start.elapsed()+ ),+ }+}++pub async fn try_start_next(app: tauri::AppHandle, queue: Arc<tokio::sync::Mutex<DownloadQueue>>) {+ let _timer_start = std::time::Instant::now();+ let (next_ids, stagger, state_to_emit) = {+ let mut q = queue.lock().await;+ let ids = q.next_queued_ids();+ for nid in &ids {+ q.mark_active(*nid);+ }+ let state = if !ids.is_empty() {+ Some(q.get_state())+ } else {+ None+ };+ (ids, q.stagger_delay_ms, state)+ };++ if let Some(state) = state_to_emit {+ emit_queue_state_from_state(&app, state);+ }++ let batch_size = next_ids.len();+ for (i, nid) in next_ids.into_iter().enumerate() {+ let _ = app.emit(+ "queue-item-progress",+ &QueueItemProgress {+ id: nid,+ title: String::new(),+ platform: String::new(),+ percent: 0.0,+ speed_bytes_per_sec: 0.0,+ downloaded_bytes: 0,+ total_bytes: None,+ phase: "queued_starting".to_string(),+ eta_seconds: None,+ },+ );++ if i > 0 {+ let item_platform = {+ let q = queue.lock().await;+ q.items+ .iter()+ .find(|item| item.id == nid)+ .map(|item| item.platform.clone())+ };+ let delay_ms = if item_platform.as_deref() == Some("youtube") {+ 2000+ } else if batch_size > 3 {+ stagger.max(1000)+ } else {+ stagger+ };+ if delay_ms > 0 {+ tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;+ }+ }+ let app_c = app.clone();+ let queue_c = queue.clone();+ tokio::spawn(async move {+ spawn_download(app_c, queue_c, nid).await;+ });+ }+ tracing::debug!("[perf] try_start_next took {:?}", _timer_start.elapsed());+}++// Periodic tick so a future-scheduled download still starts when its time+// arrives even if the queue is otherwise idle, and so a download with a+// stop time is cancelled when that time passes.+pub fn start_scheduler(app: tauri::AppHandle) {+ tauri::async_runtime::spawn(async move {+ tokio::time::sleep(std::time::Duration::from_secs(15)).await;+ loop {+ let state = app.state::<crate::AppState>();+ let queue = state.download_queue.clone();+ let (has_due, stopped_any) = {+ let q = queue.lock().await;+ let now = now_ms();+ let mut stopped = false;+ for item in &q.items {+ if item.status == QueueStatus::Active {+ if let Some(stop) = item.stop_at_ms {+ if now >= stop {+ item.cancel_token.cancel();+ stopped = true;+ }+ }+ }+ }+ let due = q.items.iter().any(|i| {+ i.status == QueueStatus::Queued+ && i.scheduled_at_ms.map(|t| now >= t).unwrap_or(false)+ });+ (due, stopped)+ };+ if has_due || stopped_any {+ try_start_next(app.clone(), queue.clone()).await;+ }+ tokio::time::sleep(std::time::Duration::from_secs(15)).await;+ }+ });+}++fn is_generic_title(title: &str) -> bool {+ let t = title.to_lowercase();+ let t = t.trim();+ t.is_empty()+ || t == "video"+ || t == "media"+ || t == "untitled"+ || t == "unknown"+ || t.starts_with("video [video]")+ || t.starts_with("media [media]")+}++#[cfg(test)]+mod kind_tests {+ use super::{kind_from_platform, QueueKind};++ #[test]+ fn youtube_and_video_platforms_map_to_video() {+ assert_eq!(kind_from_platform("youtube"), QueueKind::Video);+ assert_eq!(kind_from_platform("vimeo"), QueueKind::Video);+ assert_eq!(kind_from_platform("twitch"), QueueKind::Video);+ assert_eq!(kind_from_platform("bilibili"), QueueKind::Video);+ assert_eq!(kind_from_platform("tiktok"), QueueKind::Video);+ assert_eq!(kind_from_platform("instagram"), QueueKind::Video);+ assert_eq!(kind_from_platform("reddit"), QueueKind::Video);+ assert_eq!(kind_from_platform("bluesky"), QueueKind::Video);+ assert_eq!(kind_from_platform("generic_ytdlp"), QueueKind::Video);+ }++ #[test]+ fn audio_platforms() {+ assert_eq!(kind_from_platform("soundcloud"), QueueKind::Audio);+ assert_eq!(kind_from_platform("spotify"), QueueKind::Audio);+ }++ #[test]+ fn pinterest_is_image() {+ assert_eq!(kind_from_platform("pinterest"), QueueKind::Image);+ }++ #[test]+ fn pdf_kind() {+ assert_eq!(kind_from_platform("pdf"), QueueKind::Pdf);+ }++ #[test]+ fn book_platforms() {+ assert_eq!(kind_from_platform("annas_archive"), QueueKind::Book);+ assert_eq!(kind_from_platform("libgen"), QueueKind::Book);+ assert_eq!(kind_from_platform("gutendex"), QueueKind::Book);+ assert_eq!(kind_from_platform("book"), QueueKind::Book);+ }++ #[test]+ fn webpage_kind() {+ assert_eq!(kind_from_platform("webpage"), QueueKind::Webpage);+ assert_eq!(kind_from_platform("embed"), QueueKind::Webpage);+ }++ #[test]+ fn telegram_kind() {+ assert_eq!(kind_from_platform("telegram"), QueueKind::TelegramMedia);+ assert_eq!(+ kind_from_platform("telegram_media"),+ QueueKind::TelegramMedia+ );+ }++ #[test]+ fn course_lesson_kind() {+ assert_eq!(kind_from_platform("courses"), QueueKind::CourseLesson);+ assert_eq!(kind_from_platform("course_lesson"), QueueKind::CourseLesson);+ }++ #[test]+ fn generic_for_torrents_and_p2p() {+ assert_eq!(kind_from_platform("magnet"), QueueKind::Generic);+ assert_eq!(kind_from_platform("p2p"), QueueKind::Generic);+ assert_eq!(kind_from_platform("torrent"), QueueKind::Generic);+ }++ #[test]+ fn unknown_platform_falls_back_to_generic() {+ assert_eq!(kind_from_platform(""), QueueKind::Generic);+ assert_eq!(kind_from_platform("totally-unknown"), QueueKind::Generic);+ assert_eq!(kind_from_platform("xyz123"), QueueKind::Generic);+ }++ #[test]+ fn case_insensitive() {+ assert_eq!(kind_from_platform("YouTube"), QueueKind::Video);+ assert_eq!(kind_from_platform("TELEGRAM"), QueueKind::TelegramMedia);+ }+}diff --git a/src-tauri/src/core/state_file.rs b/src-tauri/src/core/state_file.rsindex bd47a251..6a2721c2 100644--- a/src-tauri/src/core/state_file.rs+++ b/src-tauri/src/core/state_file.rs@@ -148,7 +148,10 @@ mod tests {let lido: Option<Estado> = load_or_quarantine(&path, "estado");assert!(lido.is_none());- assert!(!path.exists(), "o arquivo corrompido precisa sair do caminho de gravação");+ assert!(+ !path.exists(),+ "o arquivo corrompido precisa sair do caminho de gravação"+ );let preservados: Vec<_> = std::fs::read_dir(&dir).unwrap()@@ -156,10 +159,17 @@ mod tests {.map(|e| e.file_name().to_string_lossy().to_string()).filter(|n| n.starts_with("estado.json.corrupt-")).collect();- assert_eq!(preservados.len(), 1, "esperava exatamente uma quarentena, achei {preservados:?}");+ assert_eq!(+ preservados.len(),+ 1,+ "esperava exatamente uma quarentena, achei {preservados:?}"+ );let conteudo = std::fs::read_to_string(dir.join(&preservados[0])).unwrap();- assert_eq!(conteudo, "{ isto nao e json", "a quarentena precisa ser byte a byte");+ assert_eq!(+ conteudo, "{ isto nao e json",+ "a quarentena precisa ser byte a byte"+ );let _ = std::fs::remove_dir_all(&dir);}diff --git a/src-tauri/src/hotkey.rs b/src-tauri/src/hotkey.rsindex 1ceac307..5fd79a20 100644--- a/src-tauri/src/hotkey.rs+++ b/src-tauri/src/hotkey.rs@@ -129,9 +129,7 @@ async fn enqueue_from_clipboard(app: &tauri::AppHandle, url: String) {use crate::external_url::QueueUrlOutcome;match crate::external_url::queue_url_with_defaults(app, url.clone(), true, None).await {Ok(QueueUrlOutcome::Queued) => emit_hotkey_result(app, "queued", Some(&url)),- Ok(QueueUrlOutcome::AlreadyQueued) => {- emit_hotkey_result(app, "already_queued", Some(&url))- }+ Ok(QueueUrlOutcome::AlreadyQueued) => emit_hotkey_result(app, "already_queued", Some(&url)),Err(e) => {tracing::warn!("[hotkey] enfileiramento recusado: {}", e);emit_hotkey_result(app, "unsupported", Some(&url));diff --git a/src-tauri/src/platforms/gallerydl/mod.rs b/src-tauri/src/platforms/gallerydl/mod.rsindex 9e9cea22..f2ebe68c 100644--- a/src-tauri/src/platforms/gallerydl/mod.rs+++ b/src-tauri/src/platforms/gallerydl/mod.rs@@ -59,9 +59,24 @@ pub fn is_gallery_url(url: &str) -> bool {/// Twitter path segments that are app routes, not usernames.const TWITTER_RESERVED: &[&str] = &[- "home", "explore", "notifications", "messages", "settings", "search",- "hashtag", "intent", "share", "login", "logout", "signup", "i", "about",- "tos", "privacy", "compose", "jobs",+ "home",+ "explore",+ "notifications",+ "messages",+ "settings",+ "search",+ "hashtag",+ "intent",+ "share",+ "login",+ "logout",+ "signup",+ "i",+ "about",+ "tos",+ "privacy",+ "compose",+ "jobs",];/// Bulk-listing URLs (profiles, subreddits) that the single-post platform@@ -96,9 +111,7 @@ pub fn is_bulk_media_url(url: &str) -> bool {if host == "twitter.com" || host == "x.com" {return match segments.as_slice() {[user] => !TWITTER_RESERVED.contains(user),- [user, tail] => {- !TWITTER_RESERVED.contains(user) && matches!(*tail, "media" | "likes")- }+ [user, tail] => !TWITTER_RESERVED.contains(user) && matches!(*tail, "media" | "likes"),_ => false,};}diff --git a/src-tauri/src/plugin_host.rs b/src-tauri/src/plugin_host.rsindex bd6e640b..48e2f30c 100644--- a/src-tauri/src/plugin_host.rs+++ b/src-tauri/src/plugin_host.rs@@ -139,10 +139,7 @@ impl<R: Runtime + 'static> PluginHost for PluginHostImpl<R> {})?.join("wtf.tonho.omniget")};- let dir = base- .join("external-cache")- .join(plugin_id)- .join(namespace);+ let dir = base.join("external-cache").join(plugin_id).join(namespace);std::fs::create_dir_all(&dir).map_err(|e| {anyhow::anyhow!("external_data_cache: failed to create {}: {}",diff --git a/src-tauri/src/plugin_loader.rs b/src-tauri/src/plugin_loader.rsindex 5ddf64b7..7294b5d7 100644--- a/src-tauri/src/plugin_loader.rs+++ b/src-tauri/src/plugin_loader.rs@@ -93,12 +93,13 @@ impl PluginManager {self.loaded.contains_key(id)}- pub fn load_one(- &mut self,- id: &str,- host: Arc<dyn PluginHost>,- ) -> Result<(), PluginLoadError> {- let plugin_dir = self.plugins_dir.join(id);+ pub fn load_one(&mut self, id: &str, host: Arc<dyn PluginHost>) -> Result<(), PluginLoadError> {+ let plugin_dir = self.plugin_dir(id).map_err(|e| PluginLoadError {+ message: e.to_string(),+ kind: "invalid_id".to_string(),+ plugin_abi: None,+ expected_abi: None,+ })?;match load_single_plugin(&plugin_dir, host) {Ok(loaded) => {tracing::info!(@@ -190,7 +191,7 @@ impl PluginManager {self.user_removed.insert(plugin_id.to_string());save_removed_list(&self.plugins_dir, &self.user_removed)?;- let plugin_dir = self.plugins_dir.join(plugin_id);+ let plugin_dir = self.plugin_dir(plugin_id)?;if plugin_dir.exists() {fs::remove_dir_all(&plugin_dir)?;}@@ -207,6 +208,43 @@ impl PluginManager {pub fn plugins_dir(&self) -> &Path {&self.plugins_dir}++ /// Diretorio de um plugin, com o id validado.+ ///+ /// Todo caminho derivado de `plugin_id` passa por aqui. O id chega de fora+ /// — registro remoto -> `installed.json` -> frontend -> comando Tauri — e+ /// nenhum ponto dessa cadeia o sanitizava, entao um id com `..` escapava do+ /// diretorio de plugins e o `remove_dir_all` do `unregister` apagava+ /// caminho arbitrario.+ pub fn plugin_dir(&self, plugin_id: &str) -> anyhow::Result<PathBuf> {+ validate_plugin_id(plugin_id)?;+ Ok(self.plugins_dir.join(plugin_id))+ }+}++/// Aceita apenas `[A-Za-z0-9._-]`, recusando separador de caminho, byte nulo,+/// componente relativo e id vazio.+///+/// Allowlist e nao blocklist de proposito: o conjunto de ids reais e pequeno e+/// conhecido (`courses`, `study`, `telegram`, `convert`, `misc`), e uma+/// blocklist erra por omissao a cada codificacao nova.+pub fn validate_plugin_id(plugin_id: &str) -> anyhow::Result<()> {+ if plugin_id.is_empty() {+ anyhow::bail!("plugin id must not be empty");+ }+ if plugin_id == "." || plugin_id == ".." || plugin_id.starts_with('.') {+ anyhow::bail!("plugin id must not be a relative path component: {plugin_id:?}");+ }+ if let Some(bad) = plugin_id+ .chars()+ .find(|c| !c.is_ascii_alphanumeric() && !matches!(c, '.' | '_' | '-'))+ {+ anyhow::bail!("plugin id contains an illegal character {bad:?}: {plugin_id:?}");+ }+ if plugin_id.contains("..") {+ anyhow::bail!("plugin id must not contain '..': {plugin_id:?}");+ }+ Ok(())}fn load_single_plugin(@@ -324,21 +362,20 @@ fn load_single_plugin(// A plugin's init entrypoint runs arbitrary foreign code; convert panics// into load errors instead of aborting the whole app.- let plugin_ptr =- match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| init_fn())) {- Ok(ptr) => ptr,- Err(_) => {- // The plugin may already have spawned threads before panicking;- // leak the library instead of dropping it (dlclose would unmap- // code those threads are still executing → SIGSEGV). Mirrors- // the deliberate leak in `PluginManager::unregister`.- std::mem::forget(lib);- return Err(PluginLoadError::simple(- "initialize",- "Plugin panicked in omniget_plugin_init",- ));- }- };+ let plugin_ptr = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| init_fn())) {+ Ok(ptr) => ptr,+ Err(_) => {+ // The plugin may already have spawned threads before panicking;+ // leak the library instead of dropping it (dlclose would unmap+ // code those threads are still executing → SIGSEGV). Mirrors+ // the deliberate leak in `PluginManager::unregister`.+ std::mem::forget(lib);+ return Err(PluginLoadError::simple(+ "initialize",+ "Plugin panicked in omniget_plugin_init",+ ));+ }+ };if plugin_ptr.is_null() {std::mem::forget(lib);return Err(PluginLoadError::simple(@@ -348,9 +385,8 @@ fn load_single_plugin(}let mut plugin = unsafe { Box::from_raw(plugin_ptr) };- let init_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {- plugin.initialize(host)- }));+ let init_result =+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| plugin.initialize(host)));match init_result {Ok(Ok(())) => {}Ok(Err(e)) => {@@ -510,3 +546,62 @@ fn save_removed_list(plugins_dir: &Path, removed: &HashSet<String>) -> anyhow::Rfs::write(&path, content)?;Ok(())}++#[cfg(test)]+mod plugin_id_tests {+ use super::*;++ #[test]+ fn aceita_os_ids_reais() {+ for id in [+ "courses",+ "study",+ "telegram",+ "convert",+ "misc",+ "my-plugin_2",+ "wtf.tonho.x",+ ] {+ assert!(validate_plugin_id(id).is_ok(), "recusou id valido {id:?}");+ }+ }++ #[test]+ fn recusa_travessia_de_caminho() {+ // Criterio de aceite do B48: um id relativo falha explicitamente em vez+ // de virar um caminho fora do diretorio de plugins.+ for id in [+ "../../algo",+ "..",+ ".",+ "../etc",+ "a/../../b",+ ".oculto",+ "sub/dir",+ "sub\\dir",+ "com:dois",+ "nulo\0byte",+ "",+ ] {+ assert!(+ validate_plugin_id(id).is_err(),+ "aceitou id perigoso {id:?}"+ );+ }+ }++ #[test]+ fn plugin_dir_nunca_escapa_do_diretorio_base() {+ let base = std::path::PathBuf::from("/tmp/omniget-plugins");+ let manager = PluginManager::new(base.clone());++ let ok = manager.plugin_dir("courses").expect("id valido");+ assert_eq!(ok, base.join("courses"));+ assert!(ok.starts_with(&base));++ // Sem o guard, `join("../../etc")` normalizaria para fora de `base` e o+ // `remove_dir_all` do `unregister` apagaria caminho arbitrario.+ assert!(manager.plugin_dir("../../etc").is_err());+ assert!(manager.plugin_dir("..").is_err());+ }+}