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: port YouTube downloader and GenericYtdlpDownloader to core
Hanakodef767ef04ca
diff --git a/src-tauri/omniget-core/src/platforms/generic_ytdlp.rs b/src-tauri/omniget-core/src/platforms/generic_ytdlp.rsnew file mode 100644index 00000000..95765cfa--- /dev/null+++ b/src-tauri/omniget-core/src/platforms/generic_ytdlp.rs@@ -0,0 +1,544 @@+use crate::models::progress::ProgressUpdate;+use std::collections::HashSet;++use anyhow::anyhow;+use async_trait::async_trait;+use tokio::sync::mpsc;++use crate::core::direct_downloader;+use crate::core::hls_downloader::HlsDownloader;+use crate::core::ytdlp;+use crate::models::media::{+ DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality as MediaVideoQuality,+};+use crate::platforms::traits::PlatformDownloader;++pub struct GenericYtdlpDownloader;++impl Default for GenericYtdlpDownloader {+ fn default() -> Self {+ Self::new()+ }+}++impl GenericYtdlpDownloader {+ pub fn new() -> Self {+ Self+ }++ fn extract_quality_height(quality_str: &str) -> Option<u32> {+ let s = quality_str.trim().to_lowercase();+ if s == "best" || s == "highest" {+ return None;+ }+ s.trim_end_matches('p').parse::<u32>().ok()+ }++ fn detect_platform(json: &serde_json::Value) -> String {+ json.get("extractor_key")+ .or_else(|| json.get("extractor"))+ .and_then(|v| v.as_str())+ .map(|s| s.to_lowercase())+ .unwrap_or_else(|| "generic".to_string())+ }++ fn detect_media_type(json: &serde_json::Value) -> MediaType {+ let has_video = json+ .get("formats")+ .and_then(|v| v.as_array())+ .map(|formats| {+ formats.iter().any(|f| {+ f.get("vcodec")+ .and_then(|v| v.as_str())+ .map(|v| v != "none")+ .unwrap_or(false)+ })+ })+ .unwrap_or(false);++ if has_video {+ MediaType::Video+ } else {+ MediaType::Audio+ }+ }++ pub fn parse_video_info(json: &serde_json::Value) -> anyhow::Result<MediaInfo> {+ let title = json+ .get("title")+ .and_then(|v| v.as_str())+ .unwrap_or("unknown")+ .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("unknown")+ .to_string();++ let duration = json.get("duration").and_then(|v| v.as_f64());++ let thumbnail = json+ .get("thumbnail")+ .and_then(|v| v.as_str())+ .map(|s| s.to_string());++ let webpage_url = json+ .get("webpage_url")+ .or_else(|| json.get("url"))+ .and_then(|v| v.as_str())+ .unwrap_or("")+ .to_string();++ let platform = Self::detect_platform(json);+ let media_type = Self::detect_media_type(json);++ let mut qualities: Vec<MediaVideoQuality> = Vec::new();+ let mut seen_heights: HashSet<u32> = HashSet::new();++ if media_type == MediaType::Video {+ if let Some(formats) = json.get("formats").and_then(|v| v.as_array()) {+ for f in formats {+ let height = f.get("height").and_then(|v| v.as_u64()).unwrap_or(0) as u32;+ let width = f.get("width").and_then(|v| v.as_u64()).unwrap_or(0) as u32;+ let vcodec = f.get("vcodec").and_then(|v| v.as_str()).unwrap_or("none");++ if vcodec == "none" || height == 0 {+ continue;+ }++ if seen_heights.insert(height) {+ qualities.push(MediaVideoQuality {+ label: format!("{}p", height),+ width,+ height,+ url: webpage_url.clone(),+ format: "ytdlp".to_string(),+ });+ }+ }+ }++ qualities.sort_by(|a, b| b.height.cmp(&a.height));+ }++ if qualities.is_empty() {+ qualities.push(MediaVideoQuality {+ label: "best".to_string(),+ width: 0,+ height: 0,+ url: webpage_url,+ format: "ytdlp".to_string(),+ });+ }++ Ok(MediaInfo {+ title,+ author,+ platform,+ duration_seconds: duration,+ thumbnail_url: thumbnail,+ available_qualities: qualities,+ media_type,+ file_size_bytes: None,+ })+ }+}++fn is_direct_media_url(url: &str) -> Option<&'static str> {+ let path = url::Url::parse(url).ok().map(|u| u.path().to_lowercase())?;++ if path.contains(".m3u8") {+ return Some("hls");+ }++ for ext in &[".mp4", ".webm", ".m4v", ".mkv", ".avi", ".mov", ".flv"] {+ if path.contains(ext) {+ return Some("direct");+ }+ }++ for ext in &[".mp3", ".m4a", ".ogg", ".wav", ".flac", ".aac"] {+ if path.contains(ext) {+ return Some("direct");+ }+ }++ None+}++fn filename_from_url(url: &str) -> String {+ url::Url::parse(url)+ .ok()+ .and_then(|u| {+ let path = u.path();+ let last = path.rsplit('/').next()?;+ if last.is_empty() || !last.contains('.') {+ return None;+ }+ Some(+ urlencoding::decode(last)+ .unwrap_or_else(|_| last.into())+ .to_string(),+ )+ })+ .map(|name| sanitize_filename::sanitize(&name))+ .unwrap_or_else(|| "download".to_string())+}++fn build_direct_media_info(url: &str, media_type_hint: &str) -> MediaInfo {+ let title = filename_from_url(url);+ let (format, media_type) = match media_type_hint {+ "hls" => ("hls".to_string(), MediaType::Video),+ _ => {+ let lower = url.to_lowercase();+ if lower.contains(".mp3")+ || lower.contains(".m4a")+ || lower.contains(".ogg")+ || lower.contains(".wav")+ || lower.contains(".flac")+ || lower.contains(".aac")+ {+ ("direct_audio".to_string(), MediaType::Audio)+ } else {+ ("direct_video".to_string(), MediaType::Video)+ }+ }+ };++ MediaInfo {+ title,+ author: String::new(),+ platform: "generic".to_string(),+ duration_seconds: None,+ thumbnail_url: None,+ available_qualities: vec![MediaVideoQuality {+ label: "original".to_string(),+ width: 0,+ height: 0,+ url: url.to_string(),+ format,+ }],+ media_type,+ file_size_bytes: None,+ }+}++#[async_trait]+impl PlatformDownloader for GenericYtdlpDownloader {+ fn name(&self) -> &str {+ "generic"+ }++ fn can_handle(&self, url: &str) -> bool {+ if let Ok(parsed) = url::Url::parse(url) {+ let scheme = parsed.scheme();+ return scheme == "http" || scheme == "https";+ }+ false+ }++ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {+ if let Some(media_type) = is_direct_media_url(url) {+ return Ok(build_direct_media_info(url, media_type));+ }++ let ytdlp_path = ytdlp::ensure_ytdlp()+ .await+ .map_err(|e| anyhow!("yt-dlp unavailable: {}", e))?;++ let extra = platform_extra_flags(url);+ let json = ytdlp::get_video_info(&ytdlp_path, url, &extra).await?;+ Self::parse_video_info(&json)+ }++ async fn download(+ &self,+ info: &MediaInfo,+ opts: &DownloadOptions,+ progress: mpsc::Sender<ProgressUpdate>,+ ) -> anyhow::Result<DownloadResult> {+ let _ = progress.send(ProgressUpdate::percent(0.0)).await;++ let first = info+ .available_qualities+ .first()+ .ok_or_else(|| anyhow!("No quality available"))?;++ let requested_height = opts+ .quality+ .as_deref()+ .and_then(Self::extract_quality_height);++ let selected = if let Some(h) = requested_height {+ info.available_qualities+ .iter()+ .filter(|q| q.height > 0 && q.height <= h)+ .max_by_key(|q| q.height)+ .or_else(|| {+ opts.quality+ .as_deref()+ .and_then(|w| info.available_qualities.iter().find(|q| q.label == *w))+ })+ .unwrap_or(first)+ } else if let Some(ref wanted) = opts.quality {+ info.available_qualities+ .iter()+ .find(|q| q.label == *wanted)+ .unwrap_or(first)+ } else {+ first+ };++ if selected.format == "hls" {+ let title = sanitize_filename::sanitize(&info.title);+ let filename = if title.ends_with(".mp4") {+ title+ } else {+ format!("{}.mp4", title)+ };+ 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 mut builder =+ crate::core::http_client::apply_global_proxy(reqwest::Client::builder())+ .timeout(std::time::Duration::from_secs(600));++ if let Some(ua) = opts.user_agent.as_deref() {+ builder = builder.user_agent(ua);+ }++ if let Some(ref hdrs) = opts.extra_headers {+ let mut default_headers = reqwest::header::HeaderMap::new();+ for (name, value) in hdrs {+ if let (Ok(hname), Ok(hval)) = (+ reqwest::header::HeaderName::from_bytes(name.as_bytes()),+ reqwest::header::HeaderValue::from_str(value),+ ) {+ default_headers.insert(hname, hval);+ }+ }+ if !default_headers.is_empty() {+ builder = builder.default_headers(default_headers);+ }+ }++ let jar = crate::core::cookie_parser::load_extension_cookies_for_url(&selected.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);+ }++ let client = builder.build().unwrap_or_default();+ let downloader = HlsDownloader::with_client(client)+ .with_user_agent_override(opts.user_agent.clone());+ let _ = progress.send(ProgressUpdate::percent(0.0)).await;++ let result = downloader+ .download(+ &selected.url,+ &output_str,+ referer,+ None,+ opts.cancel_token.clone(),+ 20,+ 3,+ )+ .await?;++ let _ = progress.send(ProgressUpdate::percent(100.0)).await;++ return Ok(DownloadResult {+ file_path: result.path,+ file_size_bytes: result.file_size,+ duration_seconds: 0.0,+ torrent_id: None,+ });+ }++ if selected.format == "direct_video" || selected.format == "direct_audio" {+ let title = sanitize_filename::sanitize(&info.title);+ let output_path = opts.output_dir.join(&title);++ let mut builder =+ crate::core::http_client::apply_global_proxy(reqwest::Client::builder())+ .timeout(std::time::Duration::from_secs(600));++ if let Some(ua) = opts.user_agent.as_deref() {+ builder = builder.user_agent(ua);+ }++ let jar = crate::core::cookie_parser::load_extension_cookies_for_url(&selected.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);+ }++ let client = builder.build().unwrap_or_default();++ let mut headers = reqwest::header::HeaderMap::new();+ if let Some(ref r) = opts.referer {+ if let Ok(val) = reqwest::header::HeaderValue::from_str(r) {+ headers.insert(reqwest::header::REFERER, val);+ }+ }+ if let Some(ref hdrs) = opts.extra_headers {+ for (name, value) in hdrs {+ if let (Ok(hname), Ok(hval)) = (+ reqwest::header::HeaderName::from_bytes(name.as_bytes()),+ reqwest::header::HeaderValue::from_str(value),+ ) {+ headers.insert(hname, hval);+ }+ }+ }+ crate::core::http_client::inject_ua_header(&mut headers, opts.user_agent.as_deref());++ let bytes = direct_downloader::download_direct_with_headers(+ &client,+ &selected.url,+ &output_path,+ progress,+ Some(headers),+ Some(&opts.cancel_token),+ )+ .await?;++ return Ok(DownloadResult {+ file_path: output_path,+ file_size_bytes: bytes,+ duration_seconds: 0.0,+ torrent_id: None,+ });+ }++ let ytdlp_path = if let Some(ref p) = opts.ytdlp_path {+ p.clone()+ } else {+ ytdlp::ensure_ytdlp().await?+ };++ let quality_height =+ requested_height.or_else(|| Self::extract_quality_height(&selected.label));+ let video_url = &selected.url;++ let referer = opts+ .referer+ .as_deref()+ .or_else(|| platform_referer(video_url));++ let format_fallbacks: &[Option<&str>] = if opts.format_id.is_some() {+ &[None]+ } else {+ &[None, Some("b"), Some("worst")]+ };++ let mut last_err: Option<anyhow::Error> = None;+ let extra_flags_owned: Vec<String> = opts+ .custom_ytdlp_args+ .as_deref()+ .map(|v| v.to_vec())+ .unwrap_or_default();+ for (idx, override_format) in format_fallbacks.iter().enumerate() {+ let effective_format = override_format.or(opts.format_id.as_deref());+ let attempt_progress = progress.clone();+ let result = ytdlp::download_video(+ &ytdlp_path,+ video_url,+ &opts.output_dir,+ quality_height,+ attempt_progress,+ opts.download_mode.as_deref(),+ effective_format,+ opts.filename_template.as_deref(),+ referer,+ opts.cancel_token.clone(),+ None,+ opts.concurrent_fragments,+ opts.download_subtitles,+ &extra_flags_owned,+ opts.audio_format.as_deref(),+ )+ .await;++ match result {+ Ok(r) => return Ok(r),+ Err(e) => {+ let msg = e.to_string().to_lowercase();+ let is_format_error = msg.contains("requested format")+ || msg.contains("format is not available")+ || msg.contains("no video formats")+ || msg.contains("no suitable format");+ let has_more = idx + 1 < format_fallbacks.len();+ if is_format_error && has_more && !opts.cancel_token.is_cancelled() {+ tracing::warn!(+ "[generic_ytdlp] format fallback {}/{} after error: {}",+ idx + 1,+ format_fallbacks.len() - 1,+ e+ );+ last_err = Some(e);+ continue;+ }+ return Err(e);+ }+ }+ }++ Err(last_err.unwrap_or_else(|| anyhow!("download failed without specific error")))+ }+}++fn platform_extra_flags(url: &str) -> Vec<String> {+ match platform_referer(url) {+ Some(r) => vec!["--referer".into(), r.to_string()],+ None => Vec::new(),+ }+}++fn platform_referer(url: &str) -> Option<&'static str> {+ let lower = url.to_lowercase();++ if lower.contains("douyin.com") || lower.contains("iesdouyin.com") {+ return Some("https://www.douyin.com/");+ }+ if lower.contains("v.qq.com") || lower.contains("qq.com/x/") {+ return Some("https://v.qq.com/");+ }+ if lower.contains("youku.com") {+ return Some("https://www.youku.com/");+ }+ if lower.contains("iqiyi.com") {+ return Some("https://www.iqiyi.com/");+ }+ if lower.contains("mgtv.com") {+ return Some("https://www.mgtv.com/");+ }+ if lower.contains("kuaishou.com") {+ return Some("https://www.kuaishou.com/");+ }+ if lower.contains("xiaohongshu.com") || lower.contains("xhslink.com") {+ return Some("https://www.xiaohongshu.com/");+ }+ if lower.contains("bilibili.com") || lower.contains("bilibili.tv") {+ return Some("https://www.bilibili.com/");+ }++ None+}diff --git a/src-tauri/omniget-core/src/platforms/mod.rs b/src-tauri/omniget-core/src/platforms/mod.rsindex 9eb8c891..5a73c081 100644--- a/src-tauri/omniget-core/src/platforms/mod.rs+++ b/src-tauri/omniget-core/src/platforms/mod.rs@@ -1,4 +1,10 @@+pub mod generic_ytdlp;pub mod traits;+pub mod youtube;++pub use generic_ytdlp::GenericYtdlpDownloader;+pub use traits::PlatformDownloader;+pub use youtube::YouTubeDownloader;use serde::{Deserialize, Serialize};use std::fmt;diff --git a/src-tauri/omniget-core/src/platforms/youtube.rs b/src-tauri/omniget-core/src/platforms/youtube.rsnew file mode 100644index 00000000..1eae88a1--- /dev/null+++ b/src-tauri/omniget-core/src/platforms/youtube.rs@@ -0,0 +1,441 @@+use crate::models::progress::ProgressUpdate;+use crate::platforms::traits::PlatformDownloader;+use std::collections::HashSet;++use anyhow::anyhow;+use async_trait::async_trait;+use tokio::sync::mpsc;++use crate::core::ytdlp;+use crate::models::media::{+ DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality as MediaVideoQuality,+};++pub struct YouTubeDownloader;++impl Default for YouTubeDownloader {+ fn default() -> Self {+ Self::new()+ }+}++impl YouTubeDownloader {+ pub fn new() -> Self {+ Self+ }++ fn extract_video_id(url: &str) -> Option<String> {+ let parsed = url::Url::parse(url).ok()?;+ let host = parsed.host_str()?.to_lowercase();++ if host.contains("youtu.be") {+ let segments: Vec<&str> = parsed.path().split('/').filter(|s| !s.is_empty()).collect();+ return segments.first().map(|s| s.to_string());+ }++ if host.contains("youtube.com") && parsed.path().starts_with("/embed/") {+ let segments: Vec<&str> = parsed.path().split('/').filter(|s| !s.is_empty()).collect();+ return segments.last().map(|s| s.to_string());+ }++ if host.contains("youtube.com") || host.contains("youtube-nocookie.com") {+ let segments: Vec<&str> = parsed.path().split('/').filter(|s| !s.is_empty()).collect();++ if segments.first() == Some(&"shorts") {+ return segments.get(1).map(|s| s.to_string());+ }++ return parsed+ .query_pairs()+ .find(|(k, _)| k == "v")+ .map(|(_, v)| v.to_string());+ }++ None+ }++ pub fn is_playlist_url(url: &str) -> bool {+ if let Ok(parsed) = url::Url::parse(url) {+ if parsed.path().starts_with("/playlist") {+ return true;+ }++ let mut has_list = false;+ let mut has_video = false;+ for (key, value) in parsed.query_pairs() {+ if key == "list" && !value.is_empty() {+ has_list = true;+ }+ if key == "v" && !value.is_empty() {+ has_video = true;+ }+ }++ return has_list && !has_video;+ }+ false+ }++ pub async fn fetch_with_ytdlp(+ url: &str,+ ytdlp_path: &std::path::Path,+ ) -> anyhow::Result<MediaInfo> {+ if Self::is_playlist_url(url) {+ let (playlist_title, entries) = ytdlp::get_playlist_info(ytdlp_path, url, &[]).await?;++ if entries.is_empty() {+ return Err(anyhow!("Playlist empty or unavailable"));+ }++ let qualities: Vec<MediaVideoQuality> = entries+ .into_iter()+ .enumerate()+ .map(|(i, entry)| MediaVideoQuality {+ label: format!("{}. {}", i + 1, entry.title),+ width: 0,+ height: 0,+ url: entry.url,+ format: "ytdlp_playlist".to_string(),+ })+ .collect();++ return Ok(MediaInfo {+ title: sanitize_filename::sanitize(&playlist_title),+ author: playlist_title,+ platform: "youtube".to_string(),+ duration_seconds: None,+ thumbnail_url: None,+ available_qualities: qualities,+ media_type: MediaType::Playlist,+ file_size_bytes: None,+ });+ }++ let _video_id = Self::extract_video_id(url)+ .ok_or_else(|| anyhow!("Could not extract YouTube video ID"))?;++ let json = ytdlp::get_video_info(ytdlp_path, url, &[]).await?;+ Self::parse_video_info(&json)+ }++ fn extract_quality_height(quality_str: &str) -> Option<u32> {+ let s = quality_str.trim().to_lowercase();+ if s == "best" || s == "highest" {+ return None;+ }+ s.trim_end_matches('p').parse::<u32>().ok()+ }++ pub fn parse_video_info(json: &serde_json::Value) -> anyhow::Result<MediaInfo> {+ let video_id = json+ .get("id")+ .and_then(|v| v.as_str())+ .unwrap_or("unknown")+ .to_string();++ let title = json+ .get("title")+ .and_then(|v| v.as_str())+ .unwrap_or("unknown")+ .to_string();++ let author = json+ .get("uploader")+ .or_else(|| json.get("channel"))+ .and_then(|v| v.as_str())+ .unwrap_or("unknown")+ .to_string();++ let duration = json.get("duration").and_then(|v| v.as_f64());++ let thumbnail = json+ .get("thumbnail")+ .and_then(|v| v.as_str())+ .map(|s| s.to_string());++ let is_live = json+ .get("is_live")+ .and_then(|v| v.as_bool())+ .unwrap_or(false);++ if is_live {+ return Err(anyhow!("Livestreams not supported"));+ }++ let mut qualities: Vec<MediaVideoQuality> = Vec::new();+ let mut seen_heights: HashSet<u32> = HashSet::new();++ if let Some(formats) = json.get("formats").and_then(|v| v.as_array()) {+ for f in formats {+ let height = f.get("height").and_then(|v| v.as_u64()).unwrap_or(0) as u32;+ let width = f.get("width").and_then(|v| v.as_u64()).unwrap_or(0) as u32;+ let vcodec = f.get("vcodec").and_then(|v| v.as_str()).unwrap_or("none");+ let acodec = f.get("acodec").and_then(|v| v.as_str()).unwrap_or("none");++ if vcodec == "none" || height == 0 {+ continue;+ }++ let has_audio = acodec != "none";++ if seen_heights.insert(height) {+ let label = if has_audio {+ format!("{}p", height)+ } else {+ format!("{}p (HD)", height)+ };++ qualities.push(MediaVideoQuality {+ label,+ width,+ height,+ url: format!("https://www.youtube.com/watch?v={}", video_id),+ format: "ytdlp".to_string(),+ });+ }+ }+ }++ qualities.sort_by(|a, b| b.height.cmp(&a.height));++ if qualities.is_empty() {+ qualities.push(MediaVideoQuality {+ label: "best".to_string(),+ width: 0,+ height: 0,+ url: format!("https://www.youtube.com/watch?v={}", video_id),+ format: "ytdlp".to_string(),+ });+ }++ Ok(MediaInfo {+ title,+ author,+ platform: "youtube".to_string(),+ duration_seconds: duration,+ thumbnail_url: thumbnail,+ available_qualities: qualities,+ media_type: MediaType::Video,+ file_size_bytes: None,+ })+ }+}++#[cfg(test)]+mod tests {+ use super::YouTubeDownloader;++ #[test]+ fn watch_url_with_playlist_param_is_single_video() {+ assert!(!YouTubeDownloader::is_playlist_url(+ "https://www.youtube.com/watch?v=abc123&list=PLxyz&index=2",+ ));+ }++ #[test]+ fn playlist_url_is_playlist() {+ assert!(YouTubeDownloader::is_playlist_url(+ "https://www.youtube.com/playlist?list=PLxyz",+ ));+ }++ #[test]+ fn list_only_watch_url_is_playlist() {+ assert!(YouTubeDownloader::is_playlist_url(+ "https://www.youtube.com/watch?list=PLxyz",+ ));+ }+}++#[async_trait]+impl PlatformDownloader for YouTubeDownloader {+ fn name(&self) -> &str {+ "youtube"+ }++ fn can_handle(&self, url: &str) -> bool {+ if let Ok(parsed) = url::Url::parse(url) {+ if let Some(host) = parsed.host_str() {+ let host = host.to_lowercase();+ return host == "youtube.com"+ || host.ends_with(".youtube.com")+ || host == "youtu.be"+ || host == "youtube-nocookie.com"+ || host.ends_with(".youtube-nocookie.com");+ }+ }+ false+ }++ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {+ let ytdlp_path = ytdlp::ensure_ytdlp().await.map_err(|e| {+ anyhow!(+ "YouTube requires yt-dlp. Failed to get yt-dlp: {}",+ e+ )+ })?;++ Self::fetch_with_ytdlp(url, &ytdlp_path).await+ }++ async fn download(+ &self,+ info: &MediaInfo,+ opts: &DownloadOptions,+ progress: mpsc::Sender<ProgressUpdate>,+ ) -> anyhow::Result<DownloadResult> {+ let _ = progress.send(ProgressUpdate::percent(0.0)).await;++ let ytdlp_path = if let Some(ref p) = opts.ytdlp_path {+ p.clone()+ } else {+ ytdlp::ensure_ytdlp().await?+ };++ let quality_height = opts+ .quality+ .as_deref()+ .and_then(Self::extract_quality_height);++ if info.media_type == MediaType::Playlist {+ return self+ .download_playlist(info, opts, progress, &ytdlp_path, quality_height)+ .await;+ }++ let first = info+ .available_qualities+ .first()+ .ok_or_else(|| anyhow!("No quality available"))?;++ let selected = match quality_height {+ Some(h) => info+ .available_qualities+ .iter()+ .filter(|q| q.height > 0 && q.height <= h)+ .max_by_key(|q| q.height)+ .unwrap_or(first),+ None => first,+ };+ let video_url = &selected.url;++ ytdlp::download_video(+ &ytdlp_path,+ video_url,+ &opts.output_dir,+ quality_height,+ progress,+ opts.download_mode.as_deref(),+ opts.format_id.as_deref(),+ opts.filename_template.as_deref(),+ opts.referer.as_deref().or(Some("https://www.youtube.com/")),+ opts.cancel_token.clone(),+ None,+ opts.concurrent_fragments,+ opts.download_subtitles,+ &[],+ opts.audio_format.as_deref(),+ )+ .await+ }+}++impl YouTubeDownloader {+ async fn download_playlist(+ &self,+ info: &MediaInfo,+ opts: &DownloadOptions,+ progress: mpsc::Sender<ProgressUpdate>,+ ytdlp_path: &std::path::Path,+ quality_height: Option<u32>,+ ) -> anyhow::Result<DownloadResult> {+ let playlist_dir = opts+ .output_dir+ .join(sanitize_filename::sanitize(&info.title));+ tokio::fs::create_dir_all(&playlist_dir).await?;++ let total = info.available_qualities.len();+ let mut total_bytes = 0u64;+ let mut last_path = playlist_dir.clone();+ let mut success_count = 0usize;+ let mut last_err: Option<anyhow::Error> = None;++ for (i, entry) in info.available_qualities.iter().enumerate() {+ if opts.cancel_token.is_cancelled() {+ anyhow::bail!("Download cancelled");+ }++ let (video_tx, mut video_rx) = mpsc::channel::<ProgressUpdate>(16);+ let progress_tx = progress.clone();+ let video_idx = i;+ let video_total = total;+ let forwarder = tokio::spawn(async move {+ let mut max_pct = 0.0_f64;+ while let Some(pu) = video_rx.recv().await {+ max_pct = max_pct.max(pu.percent);+ let overall = (video_idx as f64 / video_total as f64) * 100.0+ + (max_pct / video_total as f64);+ let _ = progress_tx+ .send(ProgressUpdate::rich(+ overall,+ None,+ None,+ pu.speed_bps,+ None,+ ))+ .await;+ }+ });++ match ytdlp::download_video(+ ytdlp_path,+ &entry.url,+ &playlist_dir,+ quality_height,+ video_tx,+ opts.download_mode.as_deref(),+ None,+ opts.filename_template.as_deref(),+ opts.referer.as_deref().or(Some("https://www.youtube.com/")),+ opts.cancel_token.clone(),+ None,+ opts.concurrent_fragments,+ opts.download_subtitles,+ &[],+ opts.audio_format.as_deref(),+ )+ .await+ {+ Ok(result) => {+ success_count += 1;+ total_bytes += result.file_size_bytes;+ last_path = result.file_path;+ }+ Err(e) => {+ tracing::warn!("Playlist video {} failed: {}", i + 1, e);+ last_err = Some(e);+ }+ }++ let _ = forwarder.await;+ }++ if success_count == 0 {+ return Err(last_err+ .unwrap_or_else(|| anyhow!("Playlist download finished without any files")));+ }++ if success_count > 1 {+ last_path = playlist_dir.clone();+ }++ let _ = progress.send(ProgressUpdate::percent(100.0)).await;++ Ok(DownloadResult {+ file_path: last_path,+ file_size_bytes: total_bytes,+ duration_seconds: 0.0,+ torrent_id: None,+ })+ }+}diff --git a/src-tauri/src/core/queue.rs b/src-tauri/src/core/queue.rsindex 4dc51a7f..48d946cb 100644--- a/src-tauri/src/core/queue.rs+++ b/src-tauri/src/core/queue.rs@@ -1807,7 +1807,7 @@ async fn fetch_and_cache_info(let info = if let Some(ytdlp) = ytdlp_path {match platform {"youtube" => {- crate::platforms::youtube::YouTubeDownloader::fetch_with_ytdlp(url, ytdlp).await?+ omniget_core::platforms::YouTubeDownloader::fetch_with_ytdlp(url, ytdlp).await?}"generic" => {let json = crate::core::ytdlp::get_video_info(ytdlp, url, &[]).await?;diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 66f3e895..1d4b4639 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -49,7 +49,7 @@ pub fn run() {registry.register(Arc::new(platforms::twitch::TwitchClipsDownloader::new()));registry.register(Arc::new(platforms::bluesky::BlueskyDownloader::new()));registry.register(Arc::new(platforms::reddit::RedditDownloader::new()));- registry.register(Arc::new(platforms::youtube::YouTubeDownloader::new()));+ registry.register(Arc::new(omniget_core::platforms::YouTubeDownloader::new()));registry.register(Arc::new(platforms::vimeo::VimeoDownloader::new()));registry.register(Arc::new(platforms::bilibili::BilibiliDownloader::new()));registry.register(Arc::new(platforms::douyin::DouyinDownloader::new()));diff --git a/src-tauri/src/platforms/generic_ytdlp/mod.rs b/src-tauri/src/platforms/generic_ytdlp/mod.rsindex 417de6cd..1cad401f 100644--- a/src-tauri/src/platforms/generic_ytdlp/mod.rs+++ b/src-tauri/src/platforms/generic_ytdlp/mod.rs@@ -1,544 +1,2 @@-use omniget_core::models::progress::ProgressUpdate;-use std::collections::HashSet;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::core::direct_downloader;-use crate::core::hls_downloader::HlsDownloader;-use crate::core::ytdlp;-use crate::models::media::{- DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality as MediaVideoQuality,-};-use crate::platforms::traits::PlatformDownloader;--pub struct GenericYtdlpDownloader;--impl Default for GenericYtdlpDownloader {- fn default() -> Self {- Self::new()- }-}--impl GenericYtdlpDownloader {- pub fn new() -> Self {- Self- }-- fn extract_quality_height(quality_str: &str) -> Option<u32> {- let s = quality_str.trim().to_lowercase();- if s == "best" || s == "highest" {- return None;- }- s.trim_end_matches('p').parse::<u32>().ok()- }-- fn detect_platform(json: &serde_json::Value) -> String {- json.get("extractor_key")- .or_else(|| json.get("extractor"))- .and_then(|v| v.as_str())- .map(|s| s.to_lowercase())- .unwrap_or_else(|| "generic".to_string())- }-- fn detect_media_type(json: &serde_json::Value) -> MediaType {- let has_video = json- .get("formats")- .and_then(|v| v.as_array())- .map(|formats| {- formats.iter().any(|f| {- f.get("vcodec")- .and_then(|v| v.as_str())- .map(|v| v != "none")- .unwrap_or(false)- })- })- .unwrap_or(false);-- if has_video {- MediaType::Video- } else {- MediaType::Audio- }- }-- pub fn parse_video_info(json: &serde_json::Value) -> anyhow::Result<MediaInfo> {- let title = json- .get("title")- .and_then(|v| v.as_str())- .unwrap_or("unknown")- .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("unknown")- .to_string();-- let duration = json.get("duration").and_then(|v| v.as_f64());-- let thumbnail = json- .get("thumbnail")- .and_then(|v| v.as_str())- .map(|s| s.to_string());-- let webpage_url = json- .get("webpage_url")- .or_else(|| json.get("url"))- .and_then(|v| v.as_str())- .unwrap_or("")- .to_string();-- let platform = Self::detect_platform(json);- let media_type = Self::detect_media_type(json);-- let mut qualities: Vec<MediaVideoQuality> = Vec::new();- let mut seen_heights: HashSet<u32> = HashSet::new();-- if media_type == MediaType::Video {- if let Some(formats) = json.get("formats").and_then(|v| v.as_array()) {- for f in formats {- let height = f.get("height").and_then(|v| v.as_u64()).unwrap_or(0) as u32;- let width = f.get("width").and_then(|v| v.as_u64()).unwrap_or(0) as u32;- let vcodec = f.get("vcodec").and_then(|v| v.as_str()).unwrap_or("none");-- if vcodec == "none" || height == 0 {- continue;- }-- if seen_heights.insert(height) {- qualities.push(MediaVideoQuality {- label: format!("{}p", height),- width,- height,- url: webpage_url.clone(),- format: "ytdlp".to_string(),- });- }- }- }-- qualities.sort_by(|a, b| b.height.cmp(&a.height));- }-- if qualities.is_empty() {- qualities.push(MediaVideoQuality {- label: "best".to_string(),- width: 0,- height: 0,- url: webpage_url,- format: "ytdlp".to_string(),- });- }-- Ok(MediaInfo {- title,- author,- platform,- duration_seconds: duration,- thumbnail_url: thumbnail,- available_qualities: qualities,- media_type,- file_size_bytes: None,- })- }-}--fn is_direct_media_url(url: &str) -> Option<&'static str> {- let path = url::Url::parse(url).ok().map(|u| u.path().to_lowercase())?;-- if path.contains(".m3u8") {- return Some("hls");- }-- for ext in &[".mp4", ".webm", ".m4v", ".mkv", ".avi", ".mov", ".flv"] {- if path.contains(ext) {- return Some("direct");- }- }-- for ext in &[".mp3", ".m4a", ".ogg", ".wav", ".flac", ".aac"] {- if path.contains(ext) {- return Some("direct");- }- }-- None-}--fn filename_from_url(url: &str) -> String {- url::Url::parse(url)- .ok()- .and_then(|u| {- let path = u.path();- let last = path.rsplit('/').next()?;- if last.is_empty() || !last.contains('.') {- return None;- }- Some(- urlencoding::decode(last)- .unwrap_or_else(|_| last.into())- .to_string(),- )- })- .map(|name| sanitize_filename::sanitize(&name))- .unwrap_or_else(|| "download".to_string())-}--fn build_direct_media_info(url: &str, media_type_hint: &str) -> MediaInfo {- let title = filename_from_url(url);- let (format, media_type) = match media_type_hint {- "hls" => ("hls".to_string(), MediaType::Video),- _ => {- let lower = url.to_lowercase();- if lower.contains(".mp3")- || lower.contains(".m4a")- || lower.contains(".ogg")- || lower.contains(".wav")- || lower.contains(".flac")- || lower.contains(".aac")- {- ("direct_audio".to_string(), MediaType::Audio)- } else {- ("direct_video".to_string(), MediaType::Video)- }- }- };-- MediaInfo {- title,- author: String::new(),- platform: "generic".to_string(),- duration_seconds: None,- thumbnail_url: None,- available_qualities: vec![MediaVideoQuality {- label: "original".to_string(),- width: 0,- height: 0,- url: url.to_string(),- format,- }],- media_type,- file_size_bytes: None,- }-}--#[async_trait]-impl PlatformDownloader for GenericYtdlpDownloader {- fn name(&self) -> &str {- "generic"- }-- fn can_handle(&self, url: &str) -> bool {- if let Ok(parsed) = url::Url::parse(url) {- let scheme = parsed.scheme();- return scheme == "http" || scheme == "https";- }- false- }-- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {- if let Some(media_type) = is_direct_media_url(url) {- return Ok(build_direct_media_info(url, media_type));- }-- let ytdlp_path = ytdlp::ensure_ytdlp()- .await- .map_err(|e| anyhow!("yt-dlp unavailable: {}", e))?;-- let extra = platform_extra_flags(url);- let json = ytdlp::get_video_info(&ytdlp_path, url, &extra).await?;- Self::parse_video_info(&json)- }-- async fn download(- &self,- info: &MediaInfo,- opts: &DownloadOptions,- progress: mpsc::Sender<ProgressUpdate>,- ) -> anyhow::Result<DownloadResult> {- let _ = progress.send(ProgressUpdate::percent(0.0)).await;-- let first = info- .available_qualities- .first()- .ok_or_else(|| anyhow!("No quality available"))?;-- let requested_height = opts- .quality- .as_deref()- .and_then(Self::extract_quality_height);-- let selected = if let Some(h) = requested_height {- info.available_qualities- .iter()- .filter(|q| q.height > 0 && q.height <= h)- .max_by_key(|q| q.height)- .or_else(|| {- opts.quality- .as_deref()- .and_then(|w| info.available_qualities.iter().find(|q| q.label == *w))- })- .unwrap_or(first)- } else if let Some(ref wanted) = opts.quality {- info.available_qualities- .iter()- .find(|q| q.label == *wanted)- .unwrap_or(first)- } else {- first- };-- if selected.format == "hls" {- let title = sanitize_filename::sanitize(&info.title);- let filename = if title.ends_with(".mp4") {- title- } else {- format!("{}.mp4", title)- };- 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 mut builder =- crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .timeout(std::time::Duration::from_secs(600));-- if let Some(ua) = opts.user_agent.as_deref() {- builder = builder.user_agent(ua);- }-- if let Some(ref hdrs) = opts.extra_headers {- let mut default_headers = reqwest::header::HeaderMap::new();- for (name, value) in hdrs {- if let (Ok(hname), Ok(hval)) = (- reqwest::header::HeaderName::from_bytes(name.as_bytes()),- reqwest::header::HeaderValue::from_str(value),- ) {- default_headers.insert(hname, hval);- }- }- if !default_headers.is_empty() {- builder = builder.default_headers(default_headers);- }- }-- let jar = crate::core::cookie_parser::load_extension_cookies_for_url(&selected.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);- }-- let client = builder.build().unwrap_or_default();- let downloader = HlsDownloader::with_client(client)- .with_user_agent_override(opts.user_agent.clone());- let _ = progress.send(ProgressUpdate::percent(0.0)).await;-- let result = downloader- .download(- &selected.url,- &output_str,- referer,- None,- opts.cancel_token.clone(),- 20,- 3,- )- .await?;-- let _ = progress.send(ProgressUpdate::percent(100.0)).await;-- return Ok(DownloadResult {- file_path: result.path,- file_size_bytes: result.file_size,- duration_seconds: 0.0,- torrent_id: None,- });- }-- if selected.format == "direct_video" || selected.format == "direct_audio" {- let title = sanitize_filename::sanitize(&info.title);- let output_path = opts.output_dir.join(&title);-- let mut builder =- crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .timeout(std::time::Duration::from_secs(600));-- if let Some(ua) = opts.user_agent.as_deref() {- builder = builder.user_agent(ua);- }-- let jar = crate::core::cookie_parser::load_extension_cookies_for_url(&selected.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);- }-- let client = builder.build().unwrap_or_default();-- let mut headers = reqwest::header::HeaderMap::new();- if let Some(ref r) = opts.referer {- if let Ok(val) = reqwest::header::HeaderValue::from_str(r) {- headers.insert(reqwest::header::REFERER, val);- }- }- if let Some(ref hdrs) = opts.extra_headers {- for (name, value) in hdrs {- if let (Ok(hname), Ok(hval)) = (- reqwest::header::HeaderName::from_bytes(name.as_bytes()),- reqwest::header::HeaderValue::from_str(value),- ) {- headers.insert(hname, hval);- }- }- }- crate::core::http_client::inject_ua_header(&mut headers, opts.user_agent.as_deref());-- let bytes = direct_downloader::download_direct_with_headers(- &client,- &selected.url,- &output_path,- progress,- Some(headers),- Some(&opts.cancel_token),- )- .await?;-- return Ok(DownloadResult {- file_path: output_path,- file_size_bytes: bytes,- duration_seconds: 0.0,- torrent_id: None,- });- }-- let ytdlp_path = if let Some(ref p) = opts.ytdlp_path {- p.clone()- } else {- ytdlp::ensure_ytdlp().await?- };-- let quality_height =- requested_height.or_else(|| Self::extract_quality_height(&selected.label));- let video_url = &selected.url;-- let referer = opts- .referer- .as_deref()- .or_else(|| platform_referer(video_url));-- let format_fallbacks: &[Option<&str>] = if opts.format_id.is_some() {- &[None]- } else {- &[None, Some("b"), Some("worst")]- };-- let mut last_err: Option<anyhow::Error> = None;- let extra_flags_owned: Vec<String> = opts- .custom_ytdlp_args- .as_deref()- .map(|v| v.to_vec())- .unwrap_or_default();- for (idx, override_format) in format_fallbacks.iter().enumerate() {- let effective_format = override_format.or(opts.format_id.as_deref());- let attempt_progress = progress.clone();- let result = ytdlp::download_video(- &ytdlp_path,- video_url,- &opts.output_dir,- quality_height,- attempt_progress,- opts.download_mode.as_deref(),- effective_format,- opts.filename_template.as_deref(),- referer,- opts.cancel_token.clone(),- None,- opts.concurrent_fragments,- opts.download_subtitles,- &extra_flags_owned,- opts.audio_format.as_deref(),- )- .await;-- match result {- Ok(r) => return Ok(r),- Err(e) => {- let msg = e.to_string().to_lowercase();- let is_format_error = msg.contains("requested format")- || msg.contains("format is not available")- || msg.contains("no video formats")- || msg.contains("no suitable format");- let has_more = idx + 1 < format_fallbacks.len();- if is_format_error && has_more && !opts.cancel_token.is_cancelled() {- tracing::warn!(- "[generic_ytdlp] format fallback {}/{} after error: {}",- idx + 1,- format_fallbacks.len() - 1,- e- );- last_err = Some(e);- continue;- }- return Err(e);- }- }- }-- Err(last_err.unwrap_or_else(|| anyhow!("download failed without specific error")))- }-}--fn platform_extra_flags(url: &str) -> Vec<String> {- match platform_referer(url) {- Some(r) => vec!["--referer".into(), r.to_string()],- None => Vec::new(),- }-}--fn platform_referer(url: &str) -> Option<&'static str> {- let lower = url.to_lowercase();-- if lower.contains("douyin.com") || lower.contains("iesdouyin.com") {- return Some("https://www.douyin.com/");- }- if lower.contains("v.qq.com") || lower.contains("qq.com/x/") {- return Some("https://v.qq.com/");- }- if lower.contains("youku.com") {- return Some("https://www.youku.com/");- }- if lower.contains("iqiyi.com") {- return Some("https://www.iqiyi.com/");- }- if lower.contains("mgtv.com") {- return Some("https://www.mgtv.com/");- }- if lower.contains("kuaishou.com") {- return Some("https://www.kuaishou.com/");- }- if lower.contains("xiaohongshu.com") || lower.contains("xhslink.com") {- return Some("https://www.xiaohongshu.com/");- }- if lower.contains("bilibili.com") || lower.contains("bilibili.tv") {- return Some("https://www.bilibili.com/");- }-- None-}+// Re-export from omniget-core+pub use omniget_core::platforms::generic_ytdlp::GenericYtdlpDownloader;diff --git a/src-tauri/src/platforms/mod.rs b/src-tauri/src/platforms/mod.rsindex 68598391..9a652d7e 100644--- a/src-tauri/src/platforms/mod.rs+++ b/src-tauri/src/platforms/mod.rs@@ -1,5 +1,7 @@pub use omniget_core::platforms::traits;pub use omniget_core::platforms::Platform;+pub use omniget_core::platforms::GenericYtdlpDownloader;+pub use omniget_core::platforms::YouTubeDownloader;pub mod bluesky;pub mod direct_file;@@ -25,5 +27,6 @@ pub mod p2p;pub mod reddit;#[cfg(not(target_os = "android"))]pub mod vimeo;-#[cfg(not(target_os = "android"))]-pub mod youtube;+// YouTube now lives in omniget-core+// #[cfg(not(target_os = "android"))]+// pub mod youtube;