Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.
Rust downloadmanagerguihacktoberfesthomebrewlightweightlinuxlinux-distributionlocal-firstmacosmacos-packagemedia-toolboxopen-sourcerustsveltetauritrendingtrending-repositorieswindowswindows-desktopytdlp
feat: add proxy support for downloads
Hanakoe6b26975cab9
diff --git a/src-tauri/omniget-cli/src/commands/batch.rs b/src-tauri/omniget-cli/src/commands/batch.rsindex d1df0d36..1a23a7eb 100644--- a/src-tauri/omniget-cli/src/commands/batch.rs+++ b/src-tauri/omniget-cli/src/commands/batch.rs@@ -4,7 +4,7 @@ use tokio::sync::Semaphore;use crate::output;-pub async fn execute(file: String, max_concurrent: usize, output_dir: 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))?;@@ -31,11 +31,12 @@ pub async fn execute(file: String, max_concurrent: usize, output_dir: Option<Strfor url in &urls {let permit = semaphore.clone().acquire_owned().await?;let dir = output_dir.clone();+ let px = proxy.clone();let url = url.clone();handles.push(tokio::spawn(async move {let _permit = permit;- crate::commands::download::execute(url, None, dir, false, None, None).await+ crate::commands::download::execute(url, None, dir, false, None, None, px).await}));}@@ -46,7 +47,7 @@ pub async fn execute(file: String, max_concurrent: usize, output_dir: Option<Strmatch handle.await {Ok(Ok(())) => success += 1,Ok(Err(e)) => {- eprintln!("Download error: {}", e);+ eprintln!("Error: {}", e);failed += 1;}Err(e) => {@@ -57,13 +58,9 @@ pub async fn execute(file: String, max_concurrent: usize, output_dir: Option<Str}if output::is_json_mode() {- output::print_json(&serde_json::json!({- "total": total,- "success": success,- "failed": failed,- }));+ println!(r#"{{"total":{},"success":{},"failed":{}}}"#, total, success, failed);} else {- println!("Batch complete: {} succeeded, {} failed", success, failed);+ println!("Done: {} ok, {} failed", success, failed);}Ok(())diff --git a/src-tauri/omniget-cli/src/commands/download.rs b/src-tauri/omniget-cli/src/commands/download.rsindex 42e2d14c..c4724ccf 100644--- a/src-tauri/omniget-cli/src/commands/download.rs+++ b/src-tauri/omniget-cli/src/commands/download.rs@@ -1,6 +1,6 @@use anyhow::Result;+use indicatif::{ProgressBar, ProgressStyle};use std::path::PathBuf;-use std::sync::Arc;use tokio::sync::mpsc;use tokio_util::sync::CancellationToken;@@ -8,47 +8,72 @@ use omniget_core::core::ytdlp;use omniget_core::models::progress::ProgressUpdate;use crate::output;-use crate::reporter::{self, CliReporter};+use crate::reporter;++const PROGRESS_STYLE: &str = "{spinner:.cyan} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({bytes_per_sec}, ETA {eta})";+const SPINNER_STYLE: &str = "{spinner:.cyan} {msg:.dim}";pub async fn execute(url: String,quality: Option<u32>,output_dir: Option<String>,audio_only: bool,- _subs: Option<String>,+ subs: Option<String>,format: Option<String>,+ proxy: Option<String>,) -> Result<()> {- let reporter = Arc::new(CliReporter::new(output::is_json_mode()));+ let json_mode = output::is_json_mode();+ let pb = ProgressBar::new(100);+ pb.set_style(ProgressStyle::default_bar().template(SPINNER_STYLE).unwrap());+ pb.set_message("Searching for yt-dlp...");- // 1. Find yt-dlp binary- reporter.message("Searching for yt-dlp...");let ytdlp = reporter::find_yt_dlp().await?;+ pb.set_message("yt-dlp found");- // 2. Determine output directorylet output_path = match output_dir {Some(dir) => PathBuf::from(dir),None => reporter::default_output_dir(),};tokio::fs::create_dir_all(&output_path).await.ok();- // 3. Set up progress channellet (tx, mut rx) = mpsc::channel::<ProgressUpdate>(100);- let reporter_arc = reporter.clone();- let progress_handle = tokio::spawn(async move {++ let pb_clone = pb.clone();+ let progress_task = tokio::spawn(async move {while let Some(update) = rx.recv().await {- reporter_arc.update(&update);+ if json_mode {+ println!(+ r#"{{"type":"progress","percent":{},"downloaded_bytes":{:?},"total_bytes":{:?}}}"#,+ update.percent, update.downloaded_bytes, update.total_bytes+ );+ } else if update.percent >= 0.0 {+ pb_clone.set_position((update.percent * 100.0) as u64);+ pb_clone.set_style(+ ProgressStyle::default_bar()+ .template(PROGRESS_STYLE)+ .unwrap(),+ );+ }}});- // 4. Determine download modelet download_mode = if audio_only { Some("audio") } else { None };+ let msg = format!("Starting: {}", url);+ pb.set_message(msg);- // 5. Set up cancellation- let cancel_token = CancellationToken::new();+ // Build extra flags for proxy and subtitles+ let mut extra_flags: Vec<String> = Vec::new();+ if let Some(p) = &proxy {+ extra_flags.push("--proxy".to_string());+ extra_flags.push(p.clone());+ }- // 6. Execute download- reporter.message(&format!("Starting download from: {}", url));- reporter.message(&format!("Output: {}", output_path.display()));+ let download_subtitles = subs.is_some();+ if let Some(lang) = &subs {+ extra_flags.push("--write-subs".to_string());+ extra_flags.push("--sub-langs".to_string());+ extra_flags.push(lang.clone());+ }let result = ytdlp::download_video(&ytdlp,@@ -58,43 +83,40 @@ pub async fn execute(tx.clone(),download_mode,format.as_deref(),- None, // filename_template- None, // referer- cancel_token,+ None,+ None,+ CancellationToken::new(),reporter::default_cookie_path().as_deref(),- 4, // concurrent_fragments- false, // download_subtitles- &[], // extra_flags- None, // audio_format+ 4,+ download_subtitles,+ &extra_flags,+ None,).await;drop(tx);- progress_handle.await.ok();+ let _ = progress_task.await;+ pb.finish();match result {Ok(dl_result) => {- reporter.finish(- true,- &format!("Downloaded to: {}", dl_result.file_path.display()),- );- if output::is_json_mode() {- output::print_json(&serde_json::json!({- "success": true,- "file_path": dl_result.file_path,- "size": dl_result.file_size_bytes,- "duration": dl_result.duration_seconds,- }));+ if json_mode {+ println!(+ r#"{{"type":"complete","success":true,"file_path":"{}","size":{},"duration":{}}}"#,+ dl_result.file_path.display(),+ dl_result.file_size_bytes,+ dl_result.duration_seconds+ );+ } else {+ println!("✓ Downloaded to: {}", dl_result.file_path.display());}Ok(())}Err(e) => {- reporter.finish(false, &format!("Download failed: {}", e));- if output::is_json_mode() {- output::print_json(&serde_json::json!({- "success": false,- "error": format!("{}", e),- }));+ if json_mode {+ println!(r#"{{"type":"complete","success":false,"error":"{}"}}"#, e);+ } else {+ eprintln!("✗ Failed: {}", e);}Err(e)}diff --git a/src-tauri/omniget-cli/src/commands/info.rs b/src-tauri/omniget-cli/src/commands/info.rsindex 8deb8562..ed16c9ce 100644--- a/src-tauri/omniget-cli/src/commands/info.rs+++ b/src-tauri/omniget-cli/src/commands/info.rs@@ -5,22 +5,34 @@ use omniget_core::core::ytdlp;use crate::output;use crate::reporter::find_yt_dlp;-pub async fn execute(url: String) -> Result<()> {+pub async fn execute(url: String, proxy: Option<String>) -> Result<()> {let ytdlp = find_yt_dlp().await?;++ let extra_flags: Vec<String> = match &proxy {+ Some(p) => vec!["--proxy".to_string(), p.clone()],+ None => vec![],+ };++ let info = match tokio::time::timeout(+ std::time::Duration::from_secs(120),+ ytdlp::get_video_info(&ytdlp, &url, &extra_flags)+ ).await {+ Ok(Ok(info)) => info,+ Ok(Err(e)) => return Err(e),+ Err(_) => anyhow::bail!("Timed out after 120s"),+ };- let info = ytdlp::get_video_info(&ytdlp, &url, &[]).await?;let formats = ytdlp::parse_formats(&info);if output::is_json_mode() {- output::print_json(&serde_json::json!({- "url": url,- "title": info.get("title").and_then(|v| v.as_str()).unwrap_or(""),- "duration": info.get("duration").and_then(|v| v.as_f64()).unwrap_or(0.0),- "uploader": info.get("uploader").and_then(|v| v.as_str()).unwrap_or(""),- "view_count": info.get("view_count").and_then(|v| v.as_u64()),- "thumbnail": info.get("thumbnail").and_then(|v| v.as_str()).unwrap_or(""),- "formats": formats,- }));+ println!(+ r#"{{"url":"{}","title":"{}","duration":{},"uploader":"{}","format_count":{}}}"#,+ url.replace('"', "\\\""),+ info.get("title").and_then(|v| v.as_str()).unwrap_or("").replace('"', "\\\""),+ info.get("duration").and_then(|v| v.as_f64()).unwrap_or(0.0),+ info.get("uploader").and_then(|v| v.as_str()).unwrap_or("").replace('"', "\\\""),+ formats.len()+ );} else {println!("Title: {}",@@ -30,24 +42,16 @@ pub async fn execute(url: String) -> Result<()> {"Duration: {:.0}s",info.get("duration").and_then(|v| v.as_f64()).unwrap_or(0.0));- println!(- "Uploader: {}",- info.get("uploader").and_then(|v| v.as_str()).unwrap_or("")- );- println!("\nAvailable formats:");- for f in &formats {+ println!("Uploader: {}", info.get("uploader").and_then(|v| v.as_str()).unwrap_or(""));+ println!("Formats: {}", formats.len());+ for f in formats.iter().take(15) {let res = f.resolution.as_deref().unwrap_or("?");- let note = f.format_note.as_deref().unwrap_or("");println!(- " {:<10} {:<8} {:>5} fps={:<4} {:<10} {}",+ " {:<10} {:<6} {:>5} {}",f.format_id,f.ext,res,- f.fps- .map(|v| format!("{:.0}", v))- .unwrap_or_else(|| "-".to_string()),- if f.has_audio { "audio" } else { "video-only" },- note,+ f.format_note.as_deref().unwrap_or(""));}}diff --git a/src-tauri/omniget-cli/src/main.rs b/src-tauri/omniget-cli/src/main.rsindex 08688823..9be31b08 100644--- a/src-tauri/omniget-cli/src/main.rs+++ b/src-tauri/omniget-cli/src/main.rs@@ -10,6 +10,9 @@ struct Cli {#[arg(long, global = true, help = "Output in JSON format")]json: bool,+ #[arg(long, global = true, help = "Proxy URL (e.g. http://127.0.0.1:7897)")]+ proxy: Option<String>,+#[command(subcommand)]command: Commands,}@@ -75,17 +78,17 @@ async fn main() -> anyhow::Result<()> {subs,format,} => {- commands::download::execute(url, quality, output, audio_only, subs, format).await?;+ commands::download::execute(url, quality, output, audio_only, subs, format, cli.proxy).await?;}Commands::Info { url } => {- commands::info::execute(url).await?;+ commands::info::execute(url, cli.proxy).await?;}Commands::Batch {file,max_concurrent,output,} => {- commands::batch::execute(file, max_concurrent, output).await?;+ commands::batch::execute(file, max_concurrent, output, cli.proxy).await?;}}