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
fix(downloads): restore yt-dlp progress/path output; fix HLS referer and progress
Antonio Leandro2de7420f250d
diff --git a/src-tauri/omniget-core/src/core/hls_downloader.rs b/src-tauri/omniget-core/src/core/hls_downloader.rsindex d942f6fd..0a135e7a 100644--- a/src-tauri/omniget-core/src/core/hls_downloader.rs+++ b/src-tauri/omniget-core/src/core/hls_downloader.rs@@ -1,6 +1,6 @@use std::collections::{BTreeMap, HashMap};use std::path::PathBuf;-use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};use std::sync::Arc;use std::time::Duration;@@ -11,6 +11,8 @@ use tokio::sync::mpsc::{self, UnboundedSender};use tokio::sync::Semaphore;use tokio_util::sync::CancellationToken;+use crate::models::progress::ProgressUpdate;+const USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";pub struct HlsDownloadResult {@@ -22,6 +24,9 @@ pub struct HlsDownloadResult {pub struct HlsDownloader {client: Client,user_agent_override: Option<String>,+ /// Optional rich progress channel; receives percent (completed/total+ /// segments) plus accumulated downloaded bytes as segments finish.+ progress_tx: Option<mpsc::Sender<ProgressUpdate>>,}impl Default for HlsDownloader {@@ -53,6 +58,7 @@ impl HlsDownloader {Self {client,user_agent_override: None,+ progress_tx: None,}}@@ -61,6 +67,13 @@ impl HlsDownloader {self}+ /// Attach a channel that receives per-segment progress updates+ /// (percent = completed / total segments, with accumulated bytes).+ pub fn with_progress(mut self, tx: mpsc::Sender<ProgressUpdate>) -> Self {+ self.progress_tx = Some(tx);+ self+ }+fn effective_user_agent(&self) -> &str {self.user_agent_override.as_deref().unwrap_or(USER_AGENT)}@@ -151,18 +164,20 @@ impl HlsDownloader {) -> anyhow::Result<String> {let mut last_err = None;for attempt in 0..max_retries {- match self- .client- .get(url)- .header("Referer", referer)- .header("User-Agent", self.effective_user_agent())- .send()- .await- {- Ok(resp) => match resp.text().await {- Ok(text) => return Ok(text),- Err(e) => last_err = Some(anyhow::anyhow!(e)),- },+ let req = apply_referer_headers(self.client.get(url), referer)+ .header("User-Agent", self.effective_user_agent());+ match req.send().await {+ Ok(resp) => {+ if !resp.status().is_success() {+ last_err =+ Some(anyhow::anyhow!("HTTP {} fetching playlist", resp.status()));+ } else {+ match resp.text().await {+ Ok(text) => return Ok(text),+ Err(e) => last_err = Some(anyhow::anyhow!(e)),+ }+ }+ }Err(e) => last_err = Some(anyhow::anyhow!(e)),}if attempt < max_retries - 1 {@@ -187,14 +202,15 @@ impl HlsDownloader {max_concurrent: u32,max_retries: u32,) -> anyhow::Result<HlsDownloadResult> {- let resp = self- .client- .get(m3u8_url)- .header("Referer", referer)+ let resp = apply_referer_headers(self.client.get(m3u8_url), referer).header("User-Agent", self.effective_user_agent()).send().await?;+ if !resp.status().is_success() {+ anyhow::bail!("HTTP {} fetching playlist", resp.status());+ }+let text = resp.text().await?;let (_, playlist) = parse_media_playlist(text.as_bytes())@@ -233,6 +249,7 @@ impl HlsDownloader {let semaphore = Arc::new(Semaphore::new(max_concurrent as usize));let completed = Arc::new(AtomicUsize::new(0));+ let downloaded_bytes = Arc::new(AtomicU64::new(0));let fail_token = cancel_token.child_token();let errors: Arc<tokio::sync::Mutex<HashMap<String, u32>>> =Arc::new(tokio::sync::Mutex::new(HashMap::new()));@@ -247,10 +264,12 @@ impl HlsDownloader {let client = &self.client;let errors_ref = &errors;let completed_ref = &completed;+ let downloaded_ref = &downloaded_bytes;let fail_ref = &fail_token;let sem_ref = &semaphore;let user_agent = self.effective_user_agent().to_string();let user_agent_ref = &user_agent;+ let progress_ref = &self.progress_tx;stream::iter(segment_urls).map(|(i, url)| {@@ -276,7 +295,26 @@ impl HlsDownloader {if let Some(ref btx) = bytes_tx {let _ = btx.send(data.len() as u64);}- completed_ref.fetch_add(1, Ordering::Relaxed);+ let done = completed_ref.fetch_add(1, Ordering::Relaxed) + 1;+ let total_dl = downloaded_ref+ .fetch_add(data.len() as u64, Ordering::Relaxed)+ + data.len() as u64;+ if let Some(ptx) = progress_ref {+ let percent = if total_segments > 0 {+ (done as f64 / total_segments as f64) * 100.0+ } else {+ 0.0+ };+ // try_send: progress is best-effort and must+ // never stall segment downloads.+ let _ = ptx.try_send(ProgressUpdate::rich(+ percent,+ Some(total_dl),+ None,+ None,+ None,+ ));+ }let _ = seg_tx.send((i, data)).await;}Err(e) => {@@ -369,14 +407,9 @@ impl HlsDownloader {) -> anyhow::Result<Vec<u8>> {let mut last_err = None;for attempt in 0..max_retries {- match self- .client- .get(url)- .header("Referer", referer)- .header("User-Agent", self.effective_user_agent())- .send()- .await- {+ let req = apply_referer_headers(self.client.get(url), referer)+ .header("User-Agent", self.effective_user_agent());+ match req.send().await {Ok(resp) => {if !resp.status().is_success() {last_err = Some(anyhow::anyhow!("HTTP {} fetching AES key", resp.status()));@@ -406,6 +439,34 @@ struct EncryptionInfo {iv: Option<[u8; 16]>,}+/// 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 {+ if referer.is_empty() {+ return req;+ }+ let req = req.header("Referer", referer);+ match url_origin(referer) {+ Some(origin) => req.header("Origin", origin),+ None => req,+ }+}++/// Origin (`scheme://host[:port]`, no path, no trailing slash) of a URL.+fn url_origin(url: &str) -> Option<String> {+ let parsed = url::Url::parse(url).ok()?;+ let host = parsed.host_str()?;+ let scheme = parsed.scheme();+ Some(match parsed.port() {+ Some(port) => format!("{}://{}:{}", scheme, host, port),+ None => format!("{}://{}", scheme, host),+ })+}+fn select_best_variant(master: &MasterPlaylist, max_height: u32) -> Option<&VariantStream> {let real: Vec<&VariantStream> = master.variants.iter().filter(|v| !v.is_i_frame).collect();@@ -519,9 +580,7 @@ async fn download_segment_with_retry(}let result = tokio::time::timeout(SEGMENT_TIMEOUT, async {- let resp = client- .get(url)- .header("Referer", referer)+ let resp = apply_referer_headers(client.get(url), referer).header("User-Agent", user_agent).send().await?;@@ -588,6 +647,28 @@ mod tests {use super::*;use m3u8_rs::{MasterPlaylist, Resolution, VariantStream};+ #[test]+ fn url_origin_basic() {+ assert_eq!(+ url_origin("https://cdn.example.com/path/master.m3u8?token=abc").as_deref(),+ Some("https://cdn.example.com")+ );+ }++ #[test]+ fn url_origin_with_port() {+ assert_eq!(+ url_origin("http://cdn.example.com:8080/video/seg.ts").as_deref(),+ Some("http://cdn.example.com:8080")+ );+ }++ #[test]+ fn url_origin_invalid_returns_none() {+ assert_eq!(url_origin("not a url"), None);+ assert_eq!(url_origin(""), None);+ }+#[test]fn resolve_url_absolute_passthrough() {assert_eq!(diff --git a/src-tauri/omniget-core/src/core/ytdlp.rs b/src-tauri/omniget-core/src/core/ytdlp.rsindex 29ff43c3..e60201fd 100644--- a/src-tauri/omniget-core/src/core/ytdlp.rs+++ b/src-tauri/omniget-core/src/core/ytdlp.rs@@ -1633,12 +1633,13 @@ pub async fn get_playlist_info(}let stdout = String::from_utf8_lossy(&output.stdout);- Ok(parse_playlist_dump(&stdout))+ Ok(parse_playlist_dump(&stdout, url))}-fn parse_playlist_dump(stdout: &str) -> (String, Vec<PlaylistEntry>) {+fn parse_playlist_dump(stdout: &str, source_url: &str) -> (String, Vec<PlaylistEntry>) {let mut entries = Vec::new();let mut playlist_title = String::new();+ let source_is_youtube = is_youtube_url(source_url);for line in stdout.lines() {if line.trim().is_empty() {@@ -1664,11 +1665,37 @@ fn parse_playlist_dump(stdout: &str) -> (String, Vec<PlaylistEntry>) {.and_then(|v| v.as_str()).unwrap_or("unknown").to_string();+ // Flat-playlist entries usually carry a top-level "url"; some+ // extractors (e.g. Bilibili cheese seasons) emit full info dicts+ // that only have "webpage_url".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(|| format!("https://www.youtube.com/watch?v={}", id));+ .map(|s| s.to_string());+ let url = match url {+ Some(u) => u,+ None => {+ // Only fabricate a youtube.com/watch URL when the entry is+ // actually a YouTube video; otherwise skip the entry rather+ // than produce a bogus URL (issue #157).+ let entry_is_youtube = json+ .get("ie_key")+ .or_else(|| json.get("extractor_key"))+ .and_then(|v| v.as_str())+ .map(|k| k.eq_ignore_ascii_case("youtube"))+ .unwrap_or(source_is_youtube);+ if entry_is_youtube && !id.is_empty() {+ format!("https://www.youtube.com/watch?v={}", id)+ } else {+ tracing::warn!(+ "[ytdlp] skipping playlist entry without url/webpage_url: id={}",+ id+ );+ continue;+ }+ }+ };let duration = json.get("duration").and_then(|v| v.as_f64());if !id.is_empty() {@@ -1787,7 +1814,7 @@ pub async fn get_playlist_info_incremental(.map_err(|e| anyhow!("Failed to run yt-dlp: {}", e))?;let stdout = String::from_utf8_lossy(&output.stdout);- let (title, entries) = parse_playlist_dump(&stdout);+ let (title, entries) = parse_playlist_dump(&stdout, url);if !output.status.success() && entries.is_empty() {let stderr = String::from_utf8_lossy(&output.stderr);@@ -2070,8 +2097,15 @@ pub async fn download_video(format_selector,"--encoding".to_string(),"utf-8".to_string(),+ // NOTE: `after_move` is the only print stage where yt-dlp populates+ // %(filepath)s (it is NA at `after_video`). Any --print implies+ // --quiet (and therefore noprogress), which would starve our stdout+ // parsing of progress / Destination / Merger lines — so explicitly+ // restore verbose output and progress below."--print".to_string(),- "after_video:OMNIGET_FILEPATH:%(filepath)s".to_string(),+ "after_move:OMNIGET_FILEPATH:%(filepath)s".to_string(),+ "--no-quiet".to_string(),+ "--progress".to_string(),];base_args.extend(js_runtime_args());@@ -2363,7 +2397,7 @@ pub async fn download_video(Some(url) => format!(" --all-proxy={}", url),None => String::new(),};- args.push(format!("aria2c:-x {} -k 1M -j {} --min-split-size=1M --file-allocation=none --optimize-concurrent-downloads=true --auto-file-renaming=false --summary-interval=1 --console-log-level=warn{}", conns, conns, aria2c_proxy));+ args.push(format!("aria2c:-x {} -k 1M -j {} --min-split-size=1M --file-allocation=none --optimize-concurrent-downloads=true --auto-file-renaming=false --summary-interval=1 --console-log-level=notice{}", conns, conns, aria2c_proxy));}}@@ -2569,13 +2603,22 @@ pub async fn download_video(if mp4_candidate.exists() {mp4_candidate} else {+ tracing::warn!(+ "[yt-dlp] captured path {} has an audio extension for a video download and no .mp4 sibling; falling back to output-dir glob scan",+ p.display()+ );find_downloaded_file(output_dir, url).await.unwrap_or(p)}} else {p}}- _ => find_downloaded_file(output_dir, url).await?,+ _ => {+ tracing::warn!(+ "[yt-dlp] no output path captured from yt-dlp stdout (OMNIGET_FILEPATH / Destination / Merger); falling back to output-dir glob scan"+ );+ find_downloaded_file(output_dir, url).await?+ }};if download_subtitles {let moved = ensure_subtitles_next_to_media(@@ -3437,6 +3480,53 @@ fn extract_id_from_url(url: &str) -> Option<String> {mod tests {use super::*;+ #[test]+ fn playlist_dump_uses_top_level_url() {+ let dump = r#"{"id":"abc","title":"Video A","url":"https://example.com/video/abc","playlist_title":"My List"}"#;+ let (title, entries) = parse_playlist_dump(dump, "https://example.com/playlist/1");+ assert_eq!(title, "My List");+ assert_eq!(entries.len(), 1);+ assert_eq!(entries[0].url, "https://example.com/video/abc");+ }++ #[test]+ fn playlist_dump_falls_back_to_webpage_url() {+ // 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");+ assert_eq!(entries.len(), 1);+ assert_eq!(entries[0].url, "https://www.bilibili.com/cheese/play/ep12345");+ }++ #[test]+ fn playlist_dump_fabricates_youtube_url_only_for_youtube_entries() {+ 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");+ }++ #[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",+ );+ assert_eq!(entries.len(), 1);+ 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");+ assert!(entries.is_empty());+ }+#[test]fn parse_progress_download_prefix() {assert_eq!(parse_progress_line("download: 45.2%"), Some(45.2));diff --git a/src-tauri/omniget-core/src/platforms/generic_ytdlp.rs b/src-tauri/omniget-core/src/platforms/generic_ytdlp.rsindex 95765cfa..aafabf0f 100644--- a/src-tauri/omniget-core/src/platforms/generic_ytdlp.rs+++ b/src-tauri/omniget-core/src/platforms/generic_ytdlp.rs@@ -302,11 +302,11 @@ impl PlatformDownloader for GenericYtdlpDownloader {let output_path = opts.output_dir.join(&filename);let output_str = output_path.to_string_lossy().to_string();- let referer = opts- .referer- .as_deref()- .or_else(|| platform_referer(&selected.url))- .unwrap_or("");+ let referer = build_hls_referer(+ opts.referer.as_deref(),+ opts.page_url.as_deref(),+ &selected.url,+ );let mut builder =crate::core::http_client::apply_global_proxy(reqwest::Client::builder())@@ -343,14 +343,15 @@ impl PlatformDownloader for GenericYtdlpDownloader {let client = builder.build().unwrap_or_default();let downloader = HlsDownloader::with_client(client)- .with_user_agent_override(opts.user_agent.clone());+ .with_user_agent_override(opts.user_agent.clone())+ .with_progress(progress.clone());let _ = progress.send(ProgressUpdate::percent(0.0)).await;let result = downloader.download(&selected.url,&output_str,- referer,+ &referer,None,opts.cancel_token.clone(),20,@@ -505,6 +506,37 @@ impl PlatformDownloader for GenericYtdlpDownloader {}}+/// Build the Referer for a raw HLS download, in priority order:+/// explicit referer from options → the page URL the stream was found on →+/// a known per-platform referer → the m3u8 URL's own origin.+/// Returns an empty string only for unparseable URLs, in which case the+/// downloader sends no Referer header at all.+fn build_hls_referer(+ explicit_referer: Option<&str>,+ page_url: Option<&str>,+ m3u8_url: &str,+) -> String {+ if let Some(r) = explicit_referer.map(str::trim).filter(|r| !r.is_empty()) {+ return r.to_string();+ }+ if let Some(p) = page_url.map(str::trim).filter(|p| !p.is_empty()) {+ return p.to_string();+ }+ if let Some(r) = platform_referer(m3u8_url) {+ return r.to_string();+ }+ url::Url::parse(m3u8_url)+ .ok()+ .and_then(|u| {+ let host = u.host_str()?.to_string();+ Some(match u.port() {+ Some(port) => format!("{}://{}:{}/", u.scheme(), host, port),+ None => format!("{}://{}/", u.scheme(), host),+ })+ })+ .unwrap_or_default()+}+fn platform_extra_flags(url: &str) -> Vec<String> {match platform_referer(url) {Some(r) => vec!["--referer".into(), r.to_string()],@@ -542,3 +574,73 @@ fn platform_referer(url: &str) -> Option<&'static str> {None}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn hls_referer_prefers_explicit() {+ assert_eq!(+ build_hls_referer(+ Some("https://page.example.com/watch"),+ Some("https://other.example.com/"),+ "https://cdn.douyin.com/v/master.m3u8"+ ),+ "https://page.example.com/watch"+ );+ }++ #[test]+ fn hls_referer_falls_back_to_page_url() {+ assert_eq!(+ build_hls_referer(+ None,+ Some("https://page.example.com/watch"),+ "https://cdn.example.com/v/master.m3u8"+ ),+ "https://page.example.com/watch"+ );+ }++ #[test]+ fn hls_referer_ignores_empty_and_whitespace() {+ assert_eq!(+ build_hls_referer(+ Some(" "),+ Some(""),+ "https://cdn.example.com/v/master.m3u8"+ ),+ "https://cdn.example.com/"+ );+ }++ #[test]+ fn hls_referer_uses_platform_referer() {+ assert_eq!(+ build_hls_referer(None, None, "https://cdn.douyin.com/v/master.m3u8"),+ "https://www.douyin.com/"+ );+ }++ #[test]+ fn hls_referer_defaults_to_m3u8_origin() {+ assert_eq!(+ build_hls_referer(None, None, "https://cdn.example.com/v/master.m3u8?tok=1"),+ "https://cdn.example.com/"+ );+ }++ #[test]+ fn hls_referer_keeps_port_in_origin() {+ assert_eq!(+ build_hls_referer(None, None, "http://cdn.example.com:8080/v/master.m3u8"),+ "http://cdn.example.com:8080/"+ );+ }++ #[test]+ fn hls_referer_empty_for_unparseable_url() {+ assert_eq!(build_hls_referer(None, None, "not a url"), "");+ }+}