use crate::common::errors::MyError;
use std::process::{Command, Stdio};
use tempfile::{self, TempPath};
pub fn get_streaming_url(url: &str, browser: &str) -> Result<String, MyError> {
if Command::new("yt-dlp").output().is_err() {
return Err(MyError::Application(
"yt-dlp is not installed.
To view YouTube videos Please install it and try again.
See https://github.com/yt-dlp/yt-dlp/wiki/Installation"
.to_string(),
));
};
let output = Command::new("yt-dlp")
.arg("-g")
.arg("-f")
.arg("best")
.arg("--cookies-from-browser")
.arg(browser)
.arg(url)
.output()
.map_err(|e| MyError::Application(format!("Failed to run yt-dlp: {}", e)))?;
if output.status.success() {
let url = String::from_utf8_lossy(&output.stdout).trim().to_string();
if url.is_empty() {
Err(MyError::Application(
"yt-dlp returned empty URL".to_string(),
))
} else {
let first_url = url.lines().next().unwrap_or(&url).to_string();
Ok(first_url)
}
} else {
Err(MyError::Application(format!(
"yt-dlp failed to extract URL: {}",
String::from_utf8_lossy(&output.stderr)
)))
}
}
pub fn download_video(url: &str, browser: &str) -> Result<TempPath, MyError> {
if Command::new("yt-dlp").output().is_err() {
return Err(MyError::Application(
"yt-dlp is not installed.
To view YouTube videos Please install it and try again.
See https://github.com/yt-dlp/yt-dlp/wiki/Installation"
.to_string(),
));
};
let temp_file = tempfile::Builder::new()
.prefix("my_temp_file_")
.suffix(".webm")
.tempfile()?;
let mut cmd = Command::new("yt-dlp");
cmd.arg(url)
.arg("--cookies-from-browser") .arg(browser) .arg("-o")
.arg("-")
.stdout(Stdio::from(temp_file.as_file().try_clone()?));
let child = cmd
.spawn()
.map_err(|e| MyError::Application(e.to_string()))?;
let output = child
.wait_with_output()
.map_err(|e| MyError::Application(e.to_string()))?;
if output.status.success() {
temp_file
.as_file()
.sync_all()
.map_err(|e| MyError::Application(e.to_string()))?;
let temp_file_path = temp_file.into_temp_path();
Ok(temp_file_path)
} else {
Err(MyError::Application(format!(
"Error downloading video: {:?}",
output.stderr
)))
}
}