Skip to content

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

feat(cli): add search and resumable archive commands for video datasets

Diego Nogueira3727a5e7276a
diff --git a/.agents/skills/video-archive/SKILL.md b/.agents/skills/video-archive/SKILL.md
new file mode 100644
index 00000000..1610b345
--- /dev/null
+++ b/.agents/skills/video-archive/SKILL.md
@@ -0,0 +1,76 @@
+---
+name: video-archive
+description: >-
+ Build or grow a local video dataset from YouTube with the OmniGet CLI
+ (`omniget-cli search` + `omniget-cli archive`): many search terms in many
+ languages, duration and title filters, low-resolution H.264 files, subtitles
+ and `.info.json` metadata, a GB cap, and a queue that resumes after a stop.
+ Use when asked to "download every video about X", "build a gameplay/tutorial
+ dataset", "archive a channel", "continue the archive", or "how far is the
+ download".
+---
+
+# Video archive with the OmniGet CLI
+
+The CLI binary is `omniget-cli` (installed with
+`cargo install --path src-tauri/omniget-cli --root ~/.local --locked`).
+Everything below runs without the desktop app open. `yt-dlp` is found on PATH
+or in the app's data folder; `ffmpeg` must be on PATH.
+
+## Layout of a dataset folder (outside the repo)
+
+```
+~/datasets/<topic>/
+ queries.txt one search term per line, # for comments
+ hits.ndjson output of search (one video per line)
+ videos/ the archive: <uploader>/<title> [<id>].mp4 + .srt + .info.json
+ videos/.omniget-archive.json queue state (pending/ok/failed/skipped)
+ run.log NDJSON log of the last archive run
+```
+
+## Workflow
+
+1. **Search.** One term per language and theme; filters cut shorts, live
+ streams and off-topic results. Results are deduplicated across terms.
+ ```bash
+ omniget-cli --json search --queries-file queries.txt -n 100 \
+ --min-duration 120 --max-duration 5400 --title-has "mir4,mir 4" \
+ > hits.ndjson 2> search.log
+ ```
+ `-n` goes up to 500 per term. Progress per term is on stderr.
+2. **Seed and download.** `--seed` adds only new ids; what is already done
+ stays done.
+ ```bash
+ omniget-cli --json archive --dest videos --seed hits.ndjson \
+ --quality 360 --subs ".*-orig" --info-json --max-gb 30 --sleep 5 \
+ >> run.log 2>&1
+ ```
+ Run it in the background for big queues. A channel or playlist URL can be
+ passed instead of (or with) `--seed`; it is re-listed on every run so new
+ uploads join the queue.
+3. **Check progress** without downloading:
+ `omniget-cli --json archive --dest videos --scan-only | tail -1`
+ (the last line is the summary: `done`, `failed`, `pending`, `size_bytes`,
+ `cap_reached`).
+4. **Resume** by running the same archive command again. Ctrl+C (SIGINT to the
+ process group) puts the current item back in the queue.
+5. **Retry failures** later with `--retry-failed`.
+
+## Choices and why
+
+| Flag | Value | Why |
+| :--- | :--- | :--- |
+| `--quality` | `360` | Caps height and prefers H.264/AAC: ~200 MB per hour, decodes everywhere. Use `480`/`720` when the model needs small UI text. |
+| `--subs` | `".*-orig"` | Only YouTube's original-language transcript. Translated tracks multiply requests and trigger HTTP 429. Subtitle errors never fail the video. |
+| `--sleep` | `5` | Spacing between videos (randomised up to 2×) keeps YouTube from throttling. |
+| `--max-gb` | disk budget | Checked before each video; the run stops with `cap_reached: true`. |
+| `--cookies` | only if needed | Age-gated or members-only videos. Off by default so a mass download never runs on the user's account. |
+
+## Rules
+
+- Keep datasets outside the repository. Do not commit media.
+- The archive is for private use (research, training, testing); do not
+ re-upload the videos.
+- When `failed` grows with `HTTP Error 429`, stop, raise `--sleep`, and resume
+ later; do not loop retries.
+- Report to the user with the summary line, not with the raw log.
diff --git a/AGENTS.md b/AGENTS.md
index 5b2ac617..9edb6d79 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -100,6 +100,10 @@ Canonical triage roles (`needs-triage`, `needs-info`, `ready-for-agent`, `ready-
Single-context (`GLOSSARY.md` and `docs/adr/`). See `docs/agents/domain.md`.
+### Video datasets from the CLI
+
+`omniget-cli search` + `omniget-cli archive` build a resumable local video archive (search terms, filters, size cap). See [.agents/skills/video-archive/SKILL.md](.agents/skills/video-archive/SKILL.md).
+
---
## Local Overrides & Session Protocol
diff --git a/src-tauri/omniget-cli/src/commands/archive.rs b/src-tauri/omniget-cli/src/commands/archive.rs
new file mode 100644
index 00000000..aed6cc51
--- /dev/null
+++ b/src-tauri/omniget-cli/src/commands/archive.rs
@@ -0,0 +1,197 @@
+//! `omniget archive`: acervo retomável numa pasta, pela linha de comando.
+//!
+//! Embrulha `yt_archive` (o mesmo motor da tela "Arquivar" do app) e o
+//! `yt_dataset` (semeadura a partir de buscas). Rodar de novo continua de onde
+//! parou; Ctrl+C devolve o item em andamento à fila. Com `--json` cada evento
+//! sai numa linha, para um agente acompanhar sem interpretar texto.
+
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+
+use anyhow::{bail, Context, Result};
+use omniget_core::core::tools::yt_archive::{self, ArchiveResult, ItemStatus, Options};
+use omniget_core::core::tools::{yt_dataset, ProgressFn, ToolProgress};
+use serde_json::json;
+
+use crate::commands::common;
+use crate::output;
+
+#[derive(clap::Args)]
+pub struct ArchiveArgs {
+ /// Channel, playlist or video URL to enumerate into the queue (optional with --seed)
+ pub url: Option<String>,
+
+ #[arg(long, help = "Archive folder (the queue state lives in it)")]
+ pub dest: String,
+
+ #[arg(long, help = "NDJSON from `omniget search --json` to add to the queue")]
+ pub seed: Option<String>,
+
+ #[arg(short, long, default_value = "best", help = "best | audio | max height (e.g. 360)")]
+ pub quality: String,
+
+ #[arg(long, help = "Subtitle languages, yt-dlp syntax (e.g. \".*-orig,en\")")]
+ pub subs: Option<String>,
+
+ #[arg(long, help = "Save the .info.json metadata next to each video")]
+ pub info_json: bool,
+
+ #[arg(long, help = "Save the thumbnail next to each video")]
+ pub thumbnail: bool,
+
+ #[arg(long, default_value_t = 0, help = "Stop after N items this run (0 = all)")]
+ pub max_items: u32,
+
+ #[arg(long, help = "Stop when the folder reaches this size in GB")]
+ pub max_gb: Option<f64>,
+
+ #[arg(long, default_value_t = 0, help = "Seconds to wait before each download")]
+ pub sleep: u32,
+
+ #[arg(long, help = "Put failed items back in the queue")]
+ pub retry_failed: bool,
+
+ #[arg(long, help = "cookies.txt (Netscape) to send with the requests")]
+ pub cookies: Option<String>,
+
+ #[arg(long, help = "Only build the queue; download nothing")]
+ pub scan_only: bool,
+}
+
+pub async fn execute(args: ArchiveArgs, proxy: Option<String>) -> Result<()> {
+ common::init_cli_runtime(proxy.as_deref())?;
+ let dest = PathBuf::from(&args.dest);
+ std::fs::create_dir_all(&dest).with_context(|| format!("creating {}", dest.display()))?;
+ if let Some(seed) = &args.seed {
+ seed_queue(&dest, seed)?;
+ }
+ let opts = build_options(&args)?;
+ let has_queue = yt_archive::load_state(&dest).is_some();
+ if opts.url.is_empty() && !has_queue {
+ bail!("nothing to archive: pass a URL or --seed");
+ }
+
+ let result = if args.scan_only {
+ if opts.url.is_empty() {
+ yt_archive::state(&args.dest)?
+ } else {
+ yt_archive::scan(&opts, &progress_printer()).await?
+ }
+ } else {
+ tokio::spawn(async {
+ if tokio::signal::ctrl_c().await.is_ok() {
+ eprintln!("stopping: the current item goes back to the queue");
+ yt_archive::cancel();
+ }
+ });
+ yt_archive::run(opts, progress_printer()).await?
+ };
+ print_summary(&result, &dest);
+ Ok(())
+}
+
+fn seed_queue(dest: &Path, seed: &str) -> Result<()> {
+ let text = std::fs::read_to_string(seed).with_context(|| format!("reading {seed}"))?;
+ let title = dest
+ .file_name()
+ .map(|n| n.to_string_lossy().to_string())
+ .unwrap_or_default();
+ let r = yt_dataset::seed(dest, &title, yt_dataset::parse_seed(&text))?;
+ if output::is_json_mode() {
+ println!("{}", json!({ "type": "seeded", "added": r.added, "total": r.total }));
+ } else {
+ println!("Queue: +{} new, {} total", r.added, r.total);
+ }
+ Ok(())
+}
+
+/// Com URL, a coleção é sempre reenumerada e fundida à fila: rodar de novo
+/// pega os vídeos novos do canal sem perder o que já foi baixado.
+fn build_options(args: &ArchiveArgs) -> Result<Options> {
+ let session_netscape = match &args.cookies {
+ Some(path) => {
+ Some(std::fs::read_to_string(path).with_context(|| format!("reading {path}"))?)
+ }
+ None => None,
+ };
+ let url = args.url.clone().unwrap_or_default().trim().to_string();
+ Ok(Options {
+ refresh: !url.is_empty(),
+ url,
+ dest: args.dest.clone(),
+ quality: args.quality.clone(),
+ write_subs: args.subs.is_some(),
+ sub_langs: args.subs.clone(),
+ write_thumbnail: args.thumbnail,
+ write_info_json: args.info_json,
+ max_items: args.max_items,
+ retry_failed: args.retry_failed,
+ account_slug: None,
+ session_netscape,
+ max_bytes: args.max_gb.map(gb_to_bytes).unwrap_or(0),
+ sleep_seconds: args.sleep,
+ })
+}
+
+fn gb_to_bytes(gb: f64) -> u64 {
+ (gb.max(0.0) * 1_000_000_000.0) as u64
+}
+
+/// O percentual de cada item ("item") é ruidoso demais para um log; só a
+/// troca de item e o fim são impressos.
+fn progress_printer() -> ProgressFn {
+ Arc::new(|p: ToolProgress| {
+ if p.stage == "item" {
+ return;
+ }
+ if output::is_json_mode() {
+ println!(
+ "{}",
+ json!({ "type": "progress", "stage": p.stage, "done": p.done,
+ "total": p.total, "message": p.message })
+ );
+ } else if let Some(msg) = p.message {
+ println!("[{}/{}] {}", p.done, p.total.unwrap_or(0), msg);
+ }
+ })
+}
+
+fn print_summary(r: &ArchiveResult, dest: &Path) {
+ let failures: Vec<_> = r
+ .items
+ .iter()
+ .filter(|i| i.status == ItemStatus::Failed)
+ .take(10)
+ .map(|i| json!({ "id": i.id, "title": i.title, "error": i.error }))
+ .collect();
+ let size_bytes = yt_dataset::dir_size(dest);
+ if output::is_json_mode() {
+ println!(
+ "{}",
+ json!({ "type": "summary", "dest": r.dest, "state_path": r.state_path,
+ "total": r.total, "done": r.done, "failed": r.failed,
+ "skipped": r.skipped, "pending": r.pending,
+ "cap_reached": r.cap_reached, "cancelled": r.cancelled,
+ "size_bytes": size_bytes, "failures": failures })
+ );
+ return;
+ }
+ println!(
+ "Done {} | failed {} | skipped {} | pending {} | total {} | {:.2} GB",
+ r.done,
+ r.failed,
+ r.skipped,
+ r.pending,
+ r.total,
+ size_bytes as f64 / 1e9
+ );
+ if r.cap_reached {
+ println!("Stopped: the folder reached the --max-gb cap");
+ }
+ if r.cancelled {
+ println!("Stopped by request; run again to continue");
+ }
+ for f in &failures {
+ println!(" failed {} — {}", f["id"], f["error"]);
+ }
+}
diff --git a/src-tauri/omniget-cli/src/commands/mod.rs b/src-tauri/omniget-cli/src/commands/mod.rs
index 76d18b0d..1f6cc7e9 100644
--- a/src-tauri/omniget-cli/src/commands/mod.rs
+++ b/src-tauri/omniget-cli/src/commands/mod.rs
@@ -1,5 +1,7 @@
+pub mod archive;
pub mod batch;
pub mod common;
pub mod download;
pub mod import_cookies;
pub mod info;
+pub mod search;
diff --git a/src-tauri/omniget-cli/src/commands/search.rs b/src-tauri/omniget-cli/src/commands/search.rs
new file mode 100644
index 00000000..8376a773
--- /dev/null
+++ b/src-tauri/omniget-cli/src/commands/search.rs
@@ -0,0 +1,105 @@
+//! `omniget search`: busca por texto e imprime um vídeo por linha.
+//!
+//! Com `--json` a saída é NDJSON e serve de semente para `omniget archive
+//! --seed`, o que permite a um agente montar um acervo a partir de uma lista
+//! de termos sem abrir o app. Progresso e erros vão para o stderr para não
+//! sujar o NDJSON do stdout.
+
+use std::collections::HashSet;
+
+use anyhow::{bail, Context, Result};
+use omniget_core::core::tools::yt_search::{self, SearchHit, SearchOptions};
+
+use crate::commands::common;
+use crate::output;
+
+#[derive(clap::Args)]
+pub struct SearchArgs {
+ /// Search terms (each one is a separate search)
+ pub queries: Vec<String>,
+
+ #[arg(long, help = "File with one search term per line (# starts a comment)")]
+ pub queries_file: Option<String>,
+
+ #[arg(short = 'n', long, default_value_t = 20, help = "Results per term (max 500)")]
+ pub max_results: u32,
+
+ #[arg(long, default_value = "youtube", help = "youtube | soundcloud")]
+ pub platform: String,
+
+ #[arg(long, help = "Drop videos shorter than this (seconds)")]
+ pub min_duration: Option<f64>,
+
+ #[arg(long, help = "Drop videos longer than this (seconds)")]
+ pub max_duration: Option<f64>,
+
+ #[arg(long, value_delimiter = ',', help = "Keep titles containing any of these (comma-separated)")]
+ pub title_has: Vec<String>,
+}
+
+pub async fn execute(args: SearchArgs, proxy: Option<String>) -> Result<()> {
+ common::init_cli_runtime(proxy.as_deref())?;
+ let queries = collect_queries(&args)?;
+ if queries.is_empty() {
+ bail!("give at least one search term or --queries-file");
+ }
+
+ let mut seen = HashSet::new();
+ let mut failures = 0usize;
+ for query in &queries {
+ let opts = SearchOptions {
+ query: query.clone(),
+ platform: args.platform.clone(),
+ max_results: args.max_results,
+ min_duration: args.min_duration,
+ max_duration: args.max_duration,
+ title_has: args.title_has.clone(),
+ };
+ match yt_search::search(&opts).await {
+ Ok(hits) => {
+ let fresh: Vec<SearchHit> =
+ hits.into_iter().filter(|h| seen.insert(h.id.clone())).collect();
+ eprintln!("{query}: {} new", fresh.len());
+ fresh.iter().try_for_each(print_hit)?;
+ }
+ Err(e) => {
+ failures += 1;
+ eprintln!("{query}: {e}");
+ }
+ }
+ }
+ if failures == queries.len() {
+ bail!("every search failed");
+ }
+ Ok(())
+}
+
+fn collect_queries(args: &SearchArgs) -> Result<Vec<String>> {
+ let mut out: Vec<String> = args.queries.clone();
+ if let Some(path) = &args.queries_file {
+ let text = std::fs::read_to_string(path).with_context(|| format!("reading {path}"))?;
+ out.extend(
+ text.lines()
+ .map(str::trim)
+ .filter(|l| !l.is_empty() && !l.starts_with('#'))
+ .map(str::to_string),
+ );
+ }
+ Ok(out)
+}
+
+fn print_hit(hit: &SearchHit) -> Result<()> {
+ if output::is_json_mode() {
+ println!("{}", serde_json::to_string(hit)?);
+ } else {
+ let mins = hit.duration.map(|d| format!("{:>4.0}m", d / 60.0));
+ println!(
+ "{} {:<24.24} {} {}",
+ mins.unwrap_or_else(|| " ?".into()),
+ hit.uploader,
+ hit.title,
+ hit.url
+ );
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-cli/src/main.rs b/src-tauri/omniget-cli/src/main.rs
index faf30117..8e708595 100644
--- a/src-tauri/omniget-cli/src/main.rs
+++ b/src-tauri/omniget-cli/src/main.rs
@@ -54,6 +54,10 @@ enum Commands {
#[arg(short, long)]
output: Option<String>,
},
+ /// Search videos by text (one per line; NDJSON with --json)
+ Search(commands::search::SearchArgs),
+ /// Resumable archive of a channel, playlist or search results in a folder
+ Archive(commands::archive::ArchiveArgs),
/// Import a cookies.txt file (Netscape format)
ImportCookies {
file: String,
@@ -103,6 +107,12 @@ async fn main() -> anyhow::Result<()> {
} => {
commands::batch::execute(file, max_concurrent, output, cli.proxy).await?;
}
+ Commands::Search(args) => {
+ commands::search::execute(args, cli.proxy).await?;
+ }
+ Commands::Archive(args) => {
+ commands::archive::execute(args, cli.proxy).await?;
+ }
Commands::ImportCookies {
file,
name,
diff --git a/src-tauri/omniget-core/src/core/tools/mod.rs b/src-tauri/omniget-core/src/core/tools/mod.rs
index 3dc0f235..e0fbffd7 100644
--- a/src-tauri/omniget-core/src/core/tools/mod.rs
+++ b/src-tauri/omniget-core/src/core/tools/mod.rs
@@ -83,7 +83,9 @@ pub mod win_updater;
pub mod x;
pub mod yt_archive;
pub mod yt_chapters;
+pub mod yt_dataset;
pub mod yt_notes;
+pub mod yt_search;
use std::sync::Arc;
diff --git a/src-tauri/omniget-core/src/core/tools/yt_archive.rs b/src-tauri/omniget-core/src/core/tools/yt_archive.rs
index 65001602..4f9e4bf1 100644
--- a/src-tauri/omniget-core/src/core/tools/yt_archive.rs
+++ b/src-tauri/omniget-core/src/core/tools/yt_archive.rs
@@ -385,25 +385,39 @@ pub struct Options {
pub account_slug: Option<String>,
#[serde(default)]
pub session_netscape: Option<String>,
+ /// Idiomas de legenda no formato do `--sub-langs` (padrão "pt.*,en.*").
+ #[serde(default)]
+ pub sub_langs: Option<String>,
+ /// Para antes do próximo item quando a pasta passar disso (0 = sem teto).
+ #[serde(default)]
+ pub max_bytes: u64,
+ /// Pausa antes de cada download, contra o limite de taxa do YouTube.
+ #[serde(default)]
+ pub sleep_seconds: u32,
}
fn default_quality() -> String {
"best".to_string()
}
-/// Tradução da qualidade escolhida para o seletor do yt-dlp.
+/// Tradução da qualidade escolhida para o seletor do yt-dlp. Qualquer altura
+/// numérica vale (360, 240...); entre formatos da mesma altura o H.264/AAC
+/// ganha, porque o MP4 final toca em qualquer lugar e decodifica rápido.
pub fn format_args(quality: &str) -> Vec<String> {
- match quality {
- "audio" => vec![
+ let height = quality.parse::<u32>().ok().filter(|h| *h > 0);
+ match (quality, height) {
+ ("audio", _) => vec![
"-f".into(),
"bestaudio/best".into(),
"-x".into(),
"--audio-format".into(),
"mp3".into(),
],
- "1080" | "720" | "480" => vec![
+ (_, Some(h)) => vec![
"-f".into(),
- format!("bv*[height<={h}]+ba/b[height<={h}]/bv*+ba/b", h = quality),
+ format!("bv*[height<={h}]+ba/b[height<={h}]/bv*+ba/b"),
+ "-S".into(),
+ format!("res:{h},vcodec:h264,acodec:aac"),
"--merge-output-format".into(),
"mp4".into(),
],
@@ -430,6 +444,8 @@ pub struct ArchiveResult {
pub items: Vec<ArchiveItem>,
pub used_session: bool,
pub cancelled: bool,
+ /// A rodada parou porque a pasta atingiu `max_bytes`.
+ pub cap_reached: bool,
}
fn result_of(
@@ -452,6 +468,7 @@ fn result_of(
items: state.items.clone(),
used_session,
cancelled,
+ cap_reached: false,
}
}
@@ -555,11 +572,16 @@ pub async fn run(opts: Options, progress: super::ProgressFn) -> anyhow::Result<A
let mut rodados = 0usize;
let mut cancelled = false;
+ let mut cap_reached = false;
while rodados < limit {
if CANCEL.load(Ordering::SeqCst) {
cancelled = true;
break;
}
+ if over_cap(&dest, opts.max_bytes) {
+ cap_reached = true;
+ break;
+ }
let Some(idx) = st.next_pending() else { break };
let item = st.items[idx].clone();
let feitos = st.counts().done as u64;
@@ -573,6 +595,12 @@ pub async fn run(opts: Options, progress: super::ProgressFn) -> anyhow::Result<A
);
match download_one(&bin, &opts, &cookie, &archive_txt, &dest, &item, &progress).await {
Ok(file) => st.mark(&item.id, ItemStatus::Ok, file, None),
+ // Ctrl+C mata o yt-dlp junto: o item foi interrompido, não falhou,
+ // e continua na fila para a próxima rodada.
+ Err(_) if CANCEL.load(Ordering::SeqCst) => {
+ cancelled = true;
+ break;
+ }
Err(e) => {
tracing::warn!("[yt-archive] {}: {}", item.id, e);
st.mark(&item.id, ItemStatus::Failed, None, Some(e.to_string()));
@@ -591,7 +619,50 @@ pub async fn run(opts: Options, progress: super::ProgressFn) -> anyhow::Result<A
Some(total),
None,
);
- Ok(result_of(&dest, &st, has_session(&opts), cancelled))
+ let mut result = result_of(&dest, &st, has_session(&opts), cancelled);
+ result.cap_reached = cap_reached;
+ Ok(result)
+}
+
+fn over_cap(dest: &Path, max_bytes: u64) -> bool {
+ max_bytes > 0 && super::yt_dataset::dir_size(dest) >= max_bytes
+}
+
+/// Legendas e pausa entre downloads, conforme as opções.
+fn extra_args(opts: &Options) -> Vec<String> {
+ let mut args = Vec::new();
+ if opts.write_subs {
+ let langs = opts
+ .sub_langs
+ .as_deref()
+ .map(str::trim)
+ .filter(|l| !l.is_empty())
+ .unwrap_or("pt.*,en.*");
+ // `--ignore-errors` rebaixa erro de legenda (o 429 do YouTube é
+ // comum) a aviso: o vídeo é o que importa. Erro no vídeo continua
+ // saindo com código 1 e o item fica como falha.
+ args.extend(
+ [
+ "--write-subs",
+ "--write-auto-subs",
+ "--sub-langs",
+ langs,
+ "--convert-subs",
+ "srt",
+ "--ignore-errors",
+ ]
+ .map(String::from),
+ );
+ }
+ if opts.sleep_seconds > 0 {
+ args.extend([
+ "--sleep-interval".to_string(),
+ opts.sleep_seconds.to_string(),
+ "--max-sleep-interval".to_string(),
+ (opts.sleep_seconds * 2).to_string(),
+ ]);
+ }
+ args
}
#[allow(clippy::too_many_arguments)]
@@ -620,16 +691,7 @@ async fn download_one(
"-o".to_string(),
template.to_string_lossy().to_string(),
]);
- if opts.write_subs {
- args.extend([
- "--write-subs".to_string(),
- "--write-auto-subs".to_string(),
- "--sub-langs".to_string(),
- "pt.*,en.*".to_string(),
- "--convert-subs".to_string(),
- "srt".to_string(),
- ]);
- }
+ args.extend(extra_args(opts));
if opts.write_thumbnail {
args.push("--write-thumbnail".to_string());
}
@@ -904,6 +966,54 @@ mod tests {
.iter()
.any(|a| a.contains("height<=1080")));
assert!(format_args("best").iter().any(|a| a == "bv*+ba/b"));
+ let low = format_args("360");
+ assert!(low.iter().any(|a| a.contains("height<=360")));
+ assert!(low.iter().any(|a| a == "res:360,vcodec:h264,acodec:aac"));
+ assert!(!format_args("0").iter().any(|a| a.contains("height")));
+ }
+
+ fn opts_for(dest: &str) -> Options {
+ serde_json::from_value(serde_json::json!({ "url": "", "dest": dest }))
+ .expect("opções mínimas")
+ }
+
+ #[test]
+ fn extra_args_follow_subs_and_sleep_options() {
+ let mut o = opts_for("x");
+ assert!(extra_args(&o).is_empty(), "sem legenda nem pausa");
+ o.write_subs = true;
+ assert!(extra_args(&o).contains(&"pt.*,en.*".to_string()));
+ o.sub_langs = Some(".*-orig,en".into());
+ o.sleep_seconds = 5;
+ let a = extra_args(&o);
+ assert!(a.contains(&".*-orig,en".to_string()));
+ assert!(a.contains(&"--ignore-errors".to_string()));
+ let i = a.iter().position(|x| x == "--max-sleep-interval").expect("pausa");
+ assert_eq!(a[i + 1], "10");
+ }
+
+ /// Com o teto já estourado a rodada nem chama o yt-dlp: sai antes do
+ /// primeiro item, com a fila intacta.
+ #[tokio::test]
+ async fn run_stops_before_downloading_when_folder_is_over_cap() {
+ let dir = super::super::temp_dir().join(format!("yt-archive-cap-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).expect("pasta");
+ std::fs::write(dir.join("big.bin"), vec![0u8; 2048]).expect("arquivo");
+ let items = super::super::yt_dataset::parse_seed("{\"id\":\"a1\"}\n{\"id\":\"b2\"}");
+ super::super::yt_dataset::seed(&dir, "cap", items).expect("semeia");
+
+ let mut o = opts_for(&dir.to_string_lossy());
+ o.max_bytes = 1024;
+ let r = run(o, super::super::noop_progress()).await;
+ let _ = std::fs::remove_dir_all(&dir);
+ let r = match r {
+ Ok(r) => r,
+ // Máquina sem yt-dlp: o teto não chegou a ser testado aqui.
+ Err(e) if e.to_string().contains("yt-dlp") => return,
+ Err(e) => panic!("{e}"),
+ };
+ assert!(r.cap_reached);
+ assert_eq!((r.pending, r.done, r.failed), (2, 0, 0));
}
#[test]
@@ -949,6 +1059,9 @@ mod tests {
retry_failed: false,
account_slug: None,
session_netscape: None,
+ sub_langs: None,
+ max_bytes: 0,
+ sleep_seconds: 0,
};
let r = run(opts.clone(), super::super::noop_progress())
.await
@@ -992,6 +1105,9 @@ mod tests {
retry_failed: false,
account_slug: None,
session_netscape: None,
+ sub_langs: None,
+ max_bytes: 0,
+ sleep_seconds: 0,
};
let r = scan(&opts, &super::super::noop_progress())
.await
diff --git a/src-tauri/omniget-core/src/core/tools/yt_dataset.rs b/src-tauri/omniget-core/src/core/tools/yt_dataset.rs
new file mode 100644
index 00000000..7fe72337
--- /dev/null
+++ b/src-tauri/omniget-core/src/core/tools/yt_dataset.rs
@@ -0,0 +1,141 @@
+//! Acervo montado a partir de buscas, não de um canal ou playlist.
+//!
+//! O `yt_archive` sabe enumerar uma URL; para juntar vídeos de várias buscas
+//! (ex.: todos os guias de um jogo, em vários idiomas) a fila precisa ser
+//! semeada com resultados já filtrados. `seed` grava esses itens no mesmo
+//! estado `.omniget-archive.json`, sem rede, e o `yt_archive::run` segue dali
+//! com retomada, falhas registradas e teto de espaço em disco.
+
+use std::path::Path;
+
+use serde::Serialize;
+
+use super::yt_archive::{self, ArchiveItem, ArchiveState, ItemStatus};
+
+#[derive(Debug, Clone, Serialize)]
+pub struct SeedResult {
+ pub state_path: String,
+ /// Itens novos que entraram na fila agora.
+ pub added: usize,
+ /// Tamanho da fila depois da semeadura.
+ pub total: usize,
+}
+
+/// Lê NDJSON (uma linha por vídeo, como o `omniget search --json` imprime)
+/// e devolve itens pendentes. Linha sem `id` ou que não é JSON é ignorada.
+pub fn parse_seed(text: &str) -> Vec<ArchiveItem> {
+ let mut seen = std::collections::HashSet::new();
+ text.lines()
+ .filter_map(|line| serde_json::from_str::<serde_json::Value>(line.trim()).ok())
+ .filter_map(|json| {
+ let id = json.get("id")?.as_str()?.trim().to_string();
+ if id.is_empty() || !seen.insert(id.clone()) {
+ return None;
+ }
+ let text_of = |k: &str| {
+ json.get(k)
+ .and_then(|v| v.as_str())
+ .unwrap_or_default()
+ .to_string()
+ };
+ let url = Some(text_of("url"))
+ .filter(|u| !u.is_empty())
+ .unwrap_or_else(|| format!("https://www.youtube.com/watch?v={}", id));
+ Some(ArchiveItem {
+ title: text_of("title"),
+ url,
+ duration_seconds: json.get("duration").and_then(|v| v.as_f64()).unwrap_or(0.0),
+ status: ItemStatus::Pending,
+ error: None,
+ file: None,
+ attempts: 0,
+ id,
+ })
+ })
+ .collect()
+}
+
+/// Junta os itens à fila da pasta sem perder o que já foi baixado ou falhou.
+pub fn seed(dest: &Path, title: &str, items: Vec<ArchiveItem>) -> anyhow::Result<SeedResult> {
+ let mut st = yt_archive::load_state(dest).unwrap_or_else(|| ArchiveState::new("", title));
+ let added = st.merge(title, items, false);
+ let path = yt_archive::save_state(dest, &mut st)?;
+ Ok(SeedResult {
+ state_path: path.to_string_lossy().to_string(),
+ added,
+ total: st.items.len(),
+ })
+}
+
+/// Soma o tamanho dos arquivos sob `dir` (sem seguir links). Usado como teto
+/// do acervo: a medida é o disco de fato, não o que o estado acha que baixou.
+pub fn dir_size(dir: &Path) -> u64 {
+ let Ok(entries) = std::fs::read_dir(dir) else {
+ return 0;
+ };
+ entries
+ .flatten()
+ .map(|e| match e.file_type() {
+ Ok(t) if t.is_dir() => dir_size(&e.path()),
+ Ok(t) if t.is_file() => e.metadata().map(|m| m.len()).unwrap_or(0),
+ _ => 0,
+ })
+ .sum()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn temp(name: &str) -> std::path::PathBuf {
+ let dir = super::super::temp_dir().join(format!("{}-{}", name, uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).expect("pasta temporária");
+ dir
+ }
+
+ const HITS: &str = r#"{"id":"a1","title":"A","url":"https://youtu.be/a1","duration":600.0}
+{"id":"b2","title":"B"}
+lixo
+{"id":"a1","title":"A de novo"}
+{"id":" ","title":"vazio"}"#;
+
+ #[test]
+ fn parse_seed_keeps_first_of_each_id() {
+ let items = parse_seed(HITS);
+ assert_eq!(items.len(), 2);
+ assert_eq!(items[0].title, "A");
+ assert_eq!(items[0].duration_seconds, 600.0);
+ assert_eq!(items[1].url, "https://www.youtube.com/watch?v=b2");
+ assert!(items.iter().all(|i| i.status == ItemStatus::Pending));
+ }
+
+ #[test]
+ fn seeding_twice_adds_only_new_ids_and_keeps_status() {
+ let dir = temp("yt-dataset-seed");
+ let r = seed(&dir, "Mir4", parse_seed(HITS)).expect("primeira semeadura");
+ assert_eq!((r.added, r.total), (2, 2));
+
+ let mut st = yt_archive::load_state(&dir).expect("estado gravado");
+ st.mark("a1", ItemStatus::Ok, Some("a1.mp4".into()), None);
+ yt_archive::save_state(&dir, &mut st).expect("grava");
+
+ let more = parse_seed("{\"id\":\"a1\"}\n{\"id\":\"c3\",\"title\":\"C\"}");
+ let r2 = seed(&dir, "Mir4", more).expect("segunda semeadura");
+ assert_eq!((r2.added, r2.total), (1, 3));
+ let st = yt_archive::load_state(&dir).expect("estado");
+ let a1 = st.items.iter().find(|i| i.id == "a1").expect("a1");
+ assert_eq!(a1.status, ItemStatus::Ok, "o que já baixou não volta à fila");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn dir_size_sums_nested_files() {
+ let dir = temp("yt-dataset-size");
+ std::fs::create_dir_all(dir.join("canal")).expect("subpasta");
+ std::fs::write(dir.join("a.bin"), vec![0u8; 100]).expect("a");
+ std::fs::write(dir.join("canal").join("b.bin"), vec![0u8; 50]).expect("b");
+ assert_eq!(dir_size(&dir), 150);
+ assert_eq!(dir_size(&dir.join("não-existe")), 0);
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
diff --git a/src-tauri/omniget-core/src/core/tools/yt_search.rs b/src-tauri/omniget-core/src/core/tools/yt_search.rs
new file mode 100644
index 00000000..904d7002
--- /dev/null
+++ b/src-tauri/omniget-core/src/core/tools/yt_search.rs
@@ -0,0 +1,235 @@
+//! Busca de vídeos por texto (YouTube/SoundCloud) via `ytsearchN:`.
+//!
+//! Mora no core, e não só no comando Tauri, para que a UI e o `omniget-cli`
+//! usem a mesma busca: a CLI precisa dela para montar acervos a partir de uma
+//! lista de termos (ex.: `omniget search "mir4 boss" --json > hits.ndjson`),
+//! e os filtros de duração/título ficam numa função pura testável sem rede.
+
+use serde::Serialize;
+
+/// Teto do yt-dlp por consulta; acima disso a busca fica lenta e o YouTube
+/// começa a devolver páginas vazias.
+pub const MAX_RESULTS: u32 = 500;
+
+#[derive(Debug, Clone, Default)]
+pub struct SearchOptions {
+ pub query: String,
+ /// "youtube" (padrão) | "soundcloud"
+ pub platform: String,
+ pub max_results: u32,
+ /// Descarta vídeos mais curtos que isso (segundos).
+ pub min_duration: Option<f64>,
+ /// Descarta vídeos mais longos que isso (segundos).
+ pub max_duration: Option<f64>,
+ /// Mantém só títulos que contenham algum destes termos (sem caixa).
+ pub title_has: Vec<String>,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct SearchHit {
+ pub id: String,
+ pub title: String,
+ pub url: String,
+ pub uploader: String,
+ pub duration: Option<f64>,
+ pub view_count: Option<u64>,
+ pub upload_date: Option<String>,
+ pub thumbnail_url: Option<String>,
+ pub platform: String,
+ /// Termo que trouxe o vídeo — vira metadado de proveniência no acervo.
+ pub query: String,
+}
+
+fn search_prefix(platform: &str) -> &'static str {
+ match platform {
+ "soundcloud" => "scsearch",
+ _ => "ytsearch",
+ }
+}
+
+/// Roda a busca no yt-dlp e devolve os resultados já filtrados.
+pub async fn search(opts: &SearchOptions) -> anyhow::Result<Vec<SearchHit>> {
+ let query = opts.query.trim();
+ if query.is_empty() {
+ anyhow::bail!("search query is empty");
+ }
+ let ytdlp_path = crate::core::ytdlp::ensure_ytdlp()
+ .await
+ .map_err(|e| anyhow::anyhow!("yt-dlp unavailable: {}", e))?;
+ let n = opts.max_results.clamp(1, MAX_RESULTS);
+
+ let mut args = vec![
+ "--flat-playlist".to_string(),
+ "--dump-json".to_string(),
+ "--no-warnings".to_string(),
+ "--socket-timeout".to_string(),
+ "15".to_string(),
+ ];
+ args.extend(crate::core::ytdlp::insecure_tls_args());
+ args.push(format!("{}{}:{}", search_prefix(&opts.platform), n, query));
+
+ let output = crate::core::ytdlp::ytdlp_command(&ytdlp_path)
+ .args(&args)
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped())
+ .output()
+ .await
+ .map_err(|e| anyhow::anyhow!("Failed to run yt-dlp: {}", e))?;
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ anyhow::bail!("Search failed: {}", stderr.trim());
+ }
+ Ok(parse_hits(&String::from_utf8_lossy(&output.stdout), opts))
+}
+
+fn str_field(json: &serde_json::Value, keys: &[&str]) -> Option<String> {
+ keys.iter()
+ .filter_map(|k| json.get(*k).and_then(|v| v.as_str()))
+ .find(|s| !s.is_empty())
+ .map(str::to_string)
+}
+
+fn thumbnail_of(json: &serde_json::Value) -> Option<String> {
+ json.get("thumbnails")
+ .and_then(|v| v.as_array())
+ .and_then(|arr| arr.last())
+ .and_then(|t| t.get("url"))
+ .and_then(|v| v.as_str())
+ .map(str::to_string)
+ .or_else(|| str_field(json, &["thumbnail"]))
+}
+
+fn hit_from(json: &serde_json::Value, opts: &SearchOptions) -> Option<SearchHit> {
+ let id = str_field(json, &["id"])?;
+ let url = str_field(json, &["url", "webpage_url"])
+ .unwrap_or_else(|| format!("https://www.youtube.com/watch?v={}", id));
+ Some(SearchHit {
+ title: str_field(json, &["title"]).unwrap_or_else(|| "Untitled".into()),
+ uploader: str_field(json, &["uploader", "channel", "uploader_id"]).unwrap_or_default(),
+ duration: json.get("duration").and_then(|v| v.as_f64()),
+ view_count: json.get("view_count").and_then(|v| v.as_u64()),
+ upload_date: str_field(json, &["upload_date"]),
+ thumbnail_url: thumbnail_of(json),
+ platform: if opts.platform.is_empty() {
+ "youtube".into()
+ } else {
+ opts.platform.clone()
+ },
+ query: opts.query.trim().to_string(),
+ id,
+ url,
+ })
+}
+
+/// Sem duração conhecida (live, estreia) o vídeo só passa quando nenhum
+/// limite foi pedido: uma live não termina e estouraria o acervo.
+fn passes(hit: &SearchHit, opts: &SearchOptions, needles: &[String]) -> bool {
+ if opts.min_duration.is_some() || opts.max_duration.is_some() {
+ let Some(d) = hit.duration else { return false };
+ if opts.min_duration.is_some_and(|min| d < min) {
+ return false;
+ }
+ if opts.max_duration.is_some_and(|max| d > max) {
+ return false;
+ }
+ }
+ if needles.is_empty() {
+ return true;
+ }
+ let title = hit.title.to_lowercase();
+ needles.iter().any(|n| title.contains(n.as_str()))
+}
+
+/// Lê o NDJSON do `--dump-json`, aplica os filtros e tira repetidos.
+pub fn parse_hits(stdout: &str, opts: &SearchOptions) -> Vec<SearchHit> {
+ let needles: Vec<String> = opts
+ .title_has
+ .iter()
+ .map(|t| t.trim().to_lowercase())
+ .filter(|t| !t.is_empty())
+ .collect();
+ let mut seen = std::collections::HashSet::new();
+ stdout
+ .lines()
+ .filter_map(|line| serde_json::from_str::<serde_json::Value>(line.trim()).ok())
+ .filter_map(|json| hit_from(&json, opts))
+ .filter(|hit| passes(hit, opts, &needles))
+ .filter(|hit| seen.insert(hit.id.clone()))
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const OUT: &str = r#"{"id":"a1","title":"MIR4 Boss Guide","url":"https://www.youtube.com/watch?v=a1","channel":"Chan","duration":600.0,"view_count":10}
+{"id":"b2","title":"Minecraft speedrun","duration":900.0}
+
+not json
+{"id":"c3","title":"미르4 공략","duration":60.0}
+{"id":"d4","title":"mir4 live","duration":null}
+{"id":"a1","title":"MIR4 Boss Guide","duration":600.0}
+{"title":"sem id"}"#;
+
+ fn opts() -> SearchOptions {
+ SearchOptions {
+ query: " mir4 ".into(),
+ platform: "youtube".into(),
+ max_results: 10,
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn parses_every_hit_once_without_filters() {
+ let hits = parse_hits(OUT, &opts());
+ let ids: Vec<&str> = hits.iter().map(|h| h.id.as_str()).collect();
+ assert_eq!(ids, ["a1", "b2", "c3", "d4"], "repetido e sem id saem");
+ assert_eq!(hits[0].uploader, "Chan");
+ assert_eq!(hits[0].view_count, Some(10));
+ assert_eq!(hits[0].query, "mir4");
+ assert_eq!(hits[1].url, "https://www.youtube.com/watch?v=b2");
+ }
+
+ #[test]
+ fn duration_filters_drop_short_long_and_unknown() {
+ let o = SearchOptions {
+ min_duration: Some(120.0),
+ max_duration: Some(700.0),
+ ..opts()
+ };
+ let ids: Vec<String> = parse_hits(OUT, &o).into_iter().map(|h| h.id).collect();
+ assert_eq!(ids, ["a1"], "60s é curto, 900s longo, live sem duração");
+ }
+
+ #[test]
+ fn title_filter_is_case_insensitive_and_any_match() {
+ let o = SearchOptions {
+ title_has: vec!["MIR4".into(), "미르4".into(), " ".into()],
+ ..opts()
+ };
+ let ids: Vec<String> = parse_hits(OUT, &o).into_iter().map(|h| h.id).collect();
+ assert_eq!(ids, ["a1", "c3", "d4"]);
+ }
+
+ #[test]
+ fn soundcloud_uses_its_own_prefix() {
+ assert_eq!(search_prefix("soundcloud"), "scsearch");
+ assert_eq!(search_prefix(""), "ytsearch");
+ }
+
+ /// Precisa de rede e do yt-dlp.
+ /// `cargo test -p omniget-core --lib -- --ignored live_yt_search`
+ #[tokio::test]
+ #[ignore]
+ async fn live_yt_search_returns_hits() {
+ let o = SearchOptions {
+ query: "mir4 gameplay".into(),
+ max_results: 3,
+ ..opts()
+ };
+ let hits = search(&o).await.expect("a busca devia responder");
+ assert!(!hits.is_empty());
+ eprintln!("{:?}", hits.iter().map(|h| &h.title).collect::<Vec<_>>());
+ }
+}
diff --git a/src-tauri/src/commands/search.rs b/src-tauri/src/commands/search.rs
index b3aa10a1..52f66b8f 100644
--- a/src-tauri/src/commands/search.rs
+++ b/src-tauri/src/commands/search.rs
@@ -1,6 +1,9 @@
use serde::Serialize;
-use crate::core::ytdlp;
+use omniget_core::core::tools::yt_search::{self, SearchHit, SearchOptions};
+
+/// Teto da tela de busca; a CLI pede mais direto ao core.
+const UI_MAX_RESULTS: u32 = 20;
#[derive(Clone, Serialize)]
pub struct SearchResult {
@@ -13,115 +16,34 @@ pub struct SearchResult {
pub platform: String,
}
+impl From<SearchHit> for SearchResult {
+ fn from(h: SearchHit) -> Self {
+ Self {
+ id: h.id,
+ title: h.title,
+ author: h.uploader,
+ duration: h.duration,
+ thumbnail_url: h.thumbnail_url,
+ url: h.url,
+ platform: h.platform,
+ }
+ }
+}
+
#[tauri::command]
pub async fn search_videos(
query: String,
platform: String,
max_results: u32,
) -> Result<Vec<SearchResult>, String> {
- let ytdlp_path = ytdlp::ensure_ytdlp()
- .await
- .map_err(|e| format!("yt-dlp unavailable: {}", e))?;
-
- let n = max_results.clamp(1, 20);
-
- let search_query = match platform.as_str() {
- "youtube" => format!("ytsearch{}:{}", n, query),
- "soundcloud" => format!("scsearch{}:{}", n, query),
- _ => format!("ytsearch{}:{}", n, query),
+ let opts = SearchOptions {
+ query,
+ platform,
+ max_results: max_results.clamp(1, UI_MAX_RESULTS),
+ ..Default::default()
};
-
- let mut args = vec![
- "--flat-playlist".to_string(),
- "--dump-json".to_string(),
- "--no-warnings".to_string(),
- "--socket-timeout".to_string(),
- "15".to_string(),
- ];
- args.extend(omniget_core::core::ytdlp::insecure_tls_args());
- args.push(search_query);
-
- let output = omniget_core::core::ytdlp::ytdlp_command(&ytdlp_path)
- .args(&args)
- .stdout(std::process::Stdio::piped())
- .stderr(std::process::Stdio::piped())
- .output()
+ yt_search::search(&opts)
.await
- .map_err(|e| format!("Failed to run yt-dlp: {}", e))?;
-
- if !output.status.success() {
- let stderr = String::from_utf8_lossy(&output.stderr);
- return Err(format!("Search failed: {}", stderr.trim()));
- }
-
- let stdout = String::from_utf8_lossy(&output.stdout);
- let mut results = Vec::new();
-
- for line in stdout.lines() {
- if line.trim().is_empty() {
- continue;
- }
-
- let json: serde_json::Value = match serde_json::from_str(line) {
- Ok(v) => v,
- Err(_) => continue,
- };
-
- let id = json
- .get("id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- if id.is_empty() {
- continue;
- }
-
- let title = json
- .get("title")
- .and_then(|v| v.as_str())
- .unwrap_or("Untitled")
- .to_string();
-
- let author = json
- .get("uploader")
- .or_else(|| json.get("channel"))
- .or_else(|| json.get("uploader_id"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let duration = json.get("duration").and_then(|v| v.as_f64());
-
- let thumbnail_url = json
- .get("thumbnails")
- .and_then(|v| v.as_array())
- .and_then(|arr| arr.last())
- .and_then(|t| t.get("url"))
- .or_else(|| json.get("thumbnail"))
- .and_then(|v| v.as_str())
- .map(|s| s.to_string());
-
- let url = json
- .get("url")
- .or_else(|| json.get("webpage_url"))
- .and_then(|v| v.as_str())
- .map(|s| s.to_string())
- .unwrap_or_else(|| match platform.as_str() {
- "youtube" => format!("https://www.youtube.com/watch?v={}", id),
- _ => format!("https://www.youtube.com/watch?v={}", id),
- });
-
- results.push(SearchResult {
- id,
- title,
- author,
- duration,
- thumbnail_url,
- url,
- platform: platform.clone(),
- });
- }
-
- Ok(results)
+ .map(|hits| hits.into_iter().map(SearchResult::from).collect())
+ .map_err(|e| e.to_string())
}