first
This commit is contained in:
185
src-tauri/src/downloader.rs
Normal file
185
src-tauri/src/downloader.rs
Normal file
@@ -0,0 +1,185 @@
|
||||
// filepath: src-tauri/src/downloader.rs
|
||||
use tauri::{AppHandle, Emitter};
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
use tokio::process::Command;
|
||||
use std::process::Stdio;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use anyhow::{Result, anyhow};
|
||||
use regex::Regex;
|
||||
use crate::ytdlp;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct VideoMetadata {
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub thumbnail: String,
|
||||
pub duration: Option<f64>,
|
||||
pub uploader: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct PlaylistMetadata {
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub entries: Vec<VideoMetadata>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
#[serde(untagged)]
|
||||
pub enum MetadataResult {
|
||||
Video(VideoMetadata),
|
||||
Playlist(PlaylistMetadata),
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, Clone)]
|
||||
pub struct DownloadOptions {
|
||||
pub is_audio_only: bool,
|
||||
pub quality: String, // e.g., "1080", "720", "best"
|
||||
pub output_path: String, // Directory
|
||||
}
|
||||
|
||||
#[derive(Serialize, Clone, Debug)]
|
||||
pub struct ProgressEvent {
|
||||
pub id: String,
|
||||
pub progress: f64,
|
||||
pub speed: String,
|
||||
pub status: String, // "downloading", "processing", "finished", "error"
|
||||
}
|
||||
|
||||
pub async fn fetch_metadata(app: &AppHandle, url: &str) -> Result<MetadataResult> {
|
||||
let ytdlp_path = ytdlp::get_ytdlp_path(app)?;
|
||||
|
||||
// Use std::process for simple output capture if it's short, but tokio is safer for async.
|
||||
let output = Command::new(ytdlp_path)
|
||||
.arg("--dump-single-json")
|
||||
.arg("--flat-playlist")
|
||||
.arg(url)
|
||||
// Stop errors from cluttering
|
||||
.stderr(Stdio::piped())
|
||||
.output()
|
||||
.await?;
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
return Err(anyhow!("yt-dlp error: {}", stderr));
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let json: serde_json::Value = serde_json::from_str(&stdout)?;
|
||||
|
||||
// Check if playlist
|
||||
if let Some(_type) = json.get("_type") {
|
||||
if _type == "playlist" {
|
||||
let entries_json = json["entries"].as_array().ok_or(anyhow!("No entries in playlist"))?;
|
||||
let mut entries = Vec::new();
|
||||
|
||||
for entry in entries_json {
|
||||
entries.push(parse_video_metadata(entry));
|
||||
}
|
||||
|
||||
return Ok(MetadataResult::Playlist(PlaylistMetadata {
|
||||
id: json["id"].as_str().unwrap_or("").to_string(),
|
||||
title: json["title"].as_str().unwrap_or("Unknown Playlist").to_string(),
|
||||
entries,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
// Single video
|
||||
Ok(MetadataResult::Video(parse_video_metadata(&json)))
|
||||
}
|
||||
|
||||
fn parse_video_metadata(json: &serde_json::Value) -> VideoMetadata {
|
||||
VideoMetadata {
|
||||
id: json["id"].as_str().unwrap_or("").to_string(),
|
||||
title: json["title"].as_str().unwrap_or("Unknown Title").to_string(),
|
||||
thumbnail: json["thumbnail"].as_str().unwrap_or("").to_string(), // Note: thumbnails might be an array sometimes, usually string in flat-playlist
|
||||
duration: json["duration"].as_f64(),
|
||||
uploader: json["uploader"].as_str().map(|s| s.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn download_video(
|
||||
app: AppHandle,
|
||||
id: String, // Unique ID for this download task (provided by frontend)
|
||||
url: String,
|
||||
options: DownloadOptions,
|
||||
) -> Result<String> {
|
||||
let ytdlp_path = ytdlp::get_ytdlp_path(&app)?;
|
||||
|
||||
let mut args = Vec::new();
|
||||
args.push(url);
|
||||
|
||||
// Output template
|
||||
let output_template = format!("{}/%(title)s.%(ext)s", options.output_path.trim_end_matches(std::path::MAIN_SEPARATOR));
|
||||
args.push("-o".to_string());
|
||||
args.push(output_template);
|
||||
|
||||
// Formats
|
||||
if options.is_audio_only {
|
||||
args.push("-x".to_string());
|
||||
args.push("--audio-format".to_string());
|
||||
args.push("mp3".to_string()); // Defaulting to mp3 for simplicity
|
||||
} else {
|
||||
let format_arg = if options.quality == "best" {
|
||||
"bestvideo+bestaudio/best".to_string()
|
||||
} else {
|
||||
format!("bestvideo[height<={}]+bestaudio/best[height<={}]", options.quality, options.quality)
|
||||
};
|
||||
args.push("-f".to_string());
|
||||
args.push(format_arg);
|
||||
}
|
||||
|
||||
// Progress output
|
||||
args.push("--newline".to_string()); // Easier parsing
|
||||
|
||||
let mut child = Command::new(ytdlp_path)
|
||||
.args(&args)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()?;
|
||||
|
||||
let stdout = child.stdout.take().ok_or(anyhow!("Failed to open stdout"))?;
|
||||
let mut reader = BufReader::new(stdout);
|
||||
let mut line = String::new();
|
||||
|
||||
// Regex for progress: [download] 42.5% of 10.00MiB at 2.00MiB/s ETA 00:05
|
||||
let re = Regex::new(r"\[download\]\s+(\d+\.?\d*)%").unwrap();
|
||||
|
||||
while reader.read_line(&mut line).await? > 0 {
|
||||
if let Some(caps) = re.captures(&line) {
|
||||
if let Some(pct_match) = caps.get(1) {
|
||||
if let Ok(pct) = pct_match.as_str().parse::<f64>() {
|
||||
// Emit event
|
||||
app.emit("download-progress", ProgressEvent {
|
||||
id: id.clone(),
|
||||
progress: pct,
|
||||
speed: "TODO".to_string(), // Speed parsing is a bit more complex, skipping for MVP or adding regex for it
|
||||
status: "downloading".to_string(),
|
||||
}).ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
line.clear();
|
||||
}
|
||||
|
||||
let status = child.wait().await?;
|
||||
|
||||
if status.success() {
|
||||
app.emit("download-progress", ProgressEvent {
|
||||
id: id.clone(),
|
||||
progress: 100.0,
|
||||
speed: "-".to_string(),
|
||||
status: "finished".to_string(),
|
||||
}).ok();
|
||||
Ok("Download complete".to_string())
|
||||
} else {
|
||||
app.emit("download-progress", ProgressEvent {
|
||||
id: id.clone(),
|
||||
progress: 0.0,
|
||||
speed: "-".to_string(),
|
||||
status: "error".to_string(),
|
||||
}).ok();
|
||||
Err(anyhow!("Download process failed"))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user