#![allow(clippy::unreadable_literal)]
use std::{fmt::Write, io::Read, path::PathBuf, process::Command, sync::Mutex, time::Duration};
use anyhow::{Context, Result};
pub const YT_DLP_VERSION: &str = "2026.08.19";
pub const PYTHON_PBS_RELEASE: &str = "20260807";
pub const PYTHON_VERSION: &str = "3.13.15";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DepKind {
YtDlp,
YtMusicApi,
Python3,
}
impl DepKind {
pub fn name(self) -> &'static str {
match self {
DepKind::YtDlp => "yt-dlp",
DepKind::YtMusicApi => "ytmusicapi",
DepKind::Python3 => "Python 3",
}
}
pub fn auto_installable(self) -> bool {
match self {
DepKind::YtDlp | DepKind::YtMusicApi | DepKind::Python3 => true,
}
}
pub fn all() -> &'static [DepKind] {
&[DepKind::YtDlp, DepKind::YtMusicApi, DepKind::Python3]
}
}
fn yt_dlp_asset() -> &'static str {
#[cfg(all(target_os = "linux", target_arch = "aarch64"))]
{
"yt-dlp_linux_aarch64"
}
#[cfg(all(target_os = "linux", not(target_arch = "aarch64")))]
{
"yt-dlp_linux"
}
#[cfg(all(target_os = "windows", target_arch = "aarch64"))]
{
"yt-dlp_arm64.exe"
}
#[cfg(all(target_os = "windows", not(target_arch = "aarch64")))]
{
"yt-dlp.exe"
}
#[cfg(target_os = "macos")]
{
"yt-dlp_macos"
}
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
{
"yt-dlp"
}
}
fn yt_dlp_expected_sha256(asset: &str) -> &'static str {
match asset {
"yt-dlp_linux" => "58162f9bfdc27458ea47bfcb311cf47028f17d8154a8bf7d689861d46399230a",
"yt-dlp_linux_aarch64" => {
"b16e4dab368a816cd05d477d698a605a6ae87ccee1c8ffd38fa21d7254141fcc"
}
"yt-dlp_macos" => "0f192b7ec147ab6288885d6351d9ab67367640029b4377576ef46dd79cf7b202",
"yt-dlp.exe" => "66674953fe251b89f4d08c5f0e35e0728679bd67ab3d7d05c0562af101dd3e7a",
"yt-dlp_arm64.exe" => "05b438997bafc3affdfda9d041353c9d73e04dc842207254b655b0887c4445b0",
_ => "",
}
}
fn python_asset() -> &'static str {
#[cfg(all(target_os = "linux", target_arch = "aarch64"))]
{
"cpython-3.13.15+20260807-aarch64-unknown-linux-gnu-install_only_stripped.tar.gz"
}
#[cfg(all(target_os = "linux", not(target_arch = "aarch64")))]
{
"cpython-3.13.15+20260807-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz"
}
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
{
"cpython-3.13.15+20260807-aarch64-apple-darwin-install_only_stripped.tar.gz"
}
#[cfg(all(target_os = "macos", not(target_arch = "aarch64")))]
{
"cpython-3.13.15+20260807-x86_64-apple-darwin-install_only_stripped.tar.gz"
}
#[cfg(all(target_os = "windows", not(target_arch = "aarch64")))]
{
"cpython-3.13.15+20260807-x86_64-pc-windows-msvc-install_only_stripped.tar.gz"
}
#[cfg(not(any(
all(target_os = "linux"),
all(target_os = "macos"),
all(target_os = "windows", not(target_arch = "aarch64"))
)))]
{
""
}
}
fn python_expected_sha256(asset: &str) -> &'static str {
match asset {
"cpython-3.13.15+20260807-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz" => {
"faae10a9faa9bec06da009ac69326cc1d9691dc138fec6a1b69159dff1781f35"
}
"cpython-3.13.15+20260807-aarch64-unknown-linux-gnu-install_only_stripped.tar.gz" => {
"1dfc9565c26f8892a33202b5966bdf9ff45c56a57b06e8fa65fecf05030afe5b"
}
"cpython-3.13.15+20260807-x86_64-apple-darwin-install_only_stripped.tar.gz" => {
"187eed2282e9c3a5b6b14953d564ee25a9f35cf2c209c9fa292186ee48b0e4a1"
}
"cpython-3.13.15+20260807-aarch64-apple-darwin-install_only_stripped.tar.gz" => {
"dbadb0ffe46f8bace50daaf8a0c5fc6903c003690776da9eb5269e33c856bb53"
}
"cpython-3.13.15+20260807-x86_64-pc-windows-msvc-install_only_stripped.tar.gz" => {
"44bf9ae71f4b45e3ba3104ae331c6eff3f7002593c26fd12453eb9310c4f259a"
}
_ => "",
}
}
fn python_cache_path() -> PathBuf {
crate::data::cache_path("python").join(PYTHON_VERSION)
}
pub(crate) fn python_exe() -> Option<PathBuf> {
if let Ok(p) = std::env::var("GOOSEMUSIC_PYTHON") {
let path = PathBuf::from(&p);
if path.exists() {
return Some(path);
}
}
let cached = python_cache_path();
let bin_dir = cached.join("python").join("bin");
let python_bin = {
#[cfg(target_os = "windows")]
{
cached.join("python").join("python.exe")
}
#[cfg(not(target_os = "windows"))]
{
bin_dir.join("python3")
}
};
if python_bin.exists() {
return Some(python_bin);
}
["python3", "python"].into_iter().find_map(|exe| {
Command::new(exe)
.arg("--version")
.output()
.ok()
.filter(|o| o.status.success())
.map(|_| PathBuf::from(exe))
})
}
pub(crate) fn system_python_exe() -> Option<PathBuf> {
["python3", "python"].into_iter().find_map(|exe| {
Command::new(exe)
.arg("--version")
.output()
.ok()
.filter(|o| o.status.success())
.map(|_| PathBuf::from(exe))
})
}
pub(crate) fn python3_present() -> bool {
python_exe().is_some()
}
fn has_ytmusicapi(py: &PathBuf) -> bool {
Command::new(py)
.args(["-c", "import ytmusicapi"])
.output()
.is_ok_and(|o| o.status.success())
}
fn ytmusicapi_present() -> bool {
if python_exe().is_some_and(|py| has_ytmusicapi(&py)) {
return true;
}
["python3", "python"].into_iter().any(|exe| {
Command::new(exe)
.arg("--version")
.output()
.is_ok_and(|o| o.status.success())
&& {
let path = PathBuf::from(exe);
has_ytmusicapi(&path)
}
})
}
fn yt_dlp_cache_path() -> PathBuf {
crate::data::cache_path("yt-dlp")
.join(YT_DLP_VERSION)
.join(yt_dlp_asset())
}
fn yt_music_api_marker() -> PathBuf {
crate::data::cache_path("ytmusicapi")
}
#[allow(clippy::unnecessary_map_or)]
pub fn resolve_yt_dlp() -> Option<PathBuf> {
if let Ok(p) = std::env::var("GOOSEMUSIC_YT_DLP") {
let p = PathBuf::from(p);
if p.exists() {
return Some(p);
}
}
let cached = yt_dlp_cache_path();
if cached.exists() {
return Some(cached);
}
if Command::new("yt-dlp")
.arg("--version")
.output()
.map_or(false, |o| o.status.success())
{
return Some(PathBuf::from("yt-dlp"));
}
None
}
pub fn yt_dlp_command() -> Result<Command> {
let path = resolve_yt_dlp().context(
"yt-dlp not found. Install it from the Dependencies dialog, or place yt-dlp on PATH.",
)?;
Ok(Command::new(path))
}
#[derive(Debug, Clone, Copy, Default)]
pub struct DepAvailability {
pub yt_dlp: bool,
pub ytmusicapi: bool,
pub python3: bool,
}
static AVAILABILITY: Mutex<DepAvailability> = Mutex::new(DepAvailability {
yt_dlp: false,
ytmusicapi: false,
python3: false,
});
pub fn availability() -> DepAvailability {
*AVAILABILITY.lock().unwrap()
}
pub fn set_availability(a: DepAvailability) {
*AVAILABILITY.lock().unwrap() = a;
}
pub fn set_available(kind: DepKind) {
let mut a = availability();
match kind {
DepKind::YtDlp => a.yt_dlp = true,
DepKind::YtMusicApi => a.ytmusicapi = true,
DepKind::Python3 => a.python3 = true,
}
set_availability(a);
}
pub fn is_available(kind: DepKind) -> bool {
let a = availability();
match kind {
DepKind::YtDlp => a.yt_dlp,
DepKind::YtMusicApi => a.ytmusicapi,
DepKind::Python3 => a.python3,
}
}
pub fn installed_via_app(kind: DepKind) -> bool {
match kind {
DepKind::YtDlp => yt_dlp_cache_path().exists(),
DepKind::YtMusicApi => yt_music_api_marker().exists(),
DepKind::Python3 => python_cache_path().exists(),
}
}
pub fn uninstall(kind: DepKind) -> Result<()> {
match kind {
DepKind::YtDlp => {
let dir = crate::data::cache_path("yt-dlp");
if dir.exists() {
std::fs::remove_dir_all(&dir)
.with_context(|| format!("Failed to remove {}", dir.display()))?;
}
let mut a = availability();
a.yt_dlp = resolve_yt_dlp().is_some();
set_availability(a);
Ok(())
}
DepKind::YtMusicApi => {
let py = python_exe().ok_or_else(|| {
anyhow::anyhow!("Python 3 not found; install it to manage ytmusicapi.")
})?;
let output = crate::providers::run_command_with_timeout(
Command::new(&py).args(["-m", "pip", "uninstall", "-y", "ytmusicapi"]),
Duration::from_mins(5),
)
.context("Failed to run pip uninstall")?;
let python3 = python3_present();
let still_present = python3 && ytmusicapi_present();
let mut a = availability();
a.python3 = python3;
a.ytmusicapi = still_present;
set_availability(a);
let _ = std::fs::remove_file(yt_music_api_marker());
if !output.status.success() && still_present {
anyhow::bail!(
"pip uninstall ytmusicapi failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
Ok(())
}
DepKind::Python3 => {
let dir = python_cache_path();
if dir.exists() {
std::fs::remove_dir_all(&dir)
.with_context(|| format!("Failed to remove {}", dir.display()))?;
}
let mut a = availability();
a.python3 = python3_present();
set_availability(a);
Ok(())
}
}
}
pub fn detect_missing() -> Vec<DepKind> {
let yt_dlp = resolve_yt_dlp().is_some();
let python3 = python3_present();
let ytmusicapi = python3 && ytmusicapi_present();
set_availability(DepAvailability {
yt_dlp,
ytmusicapi,
python3,
});
let mut missing = Vec::new();
if !yt_dlp {
missing.push(DepKind::YtDlp);
}
if !python3 {
missing.push(DepKind::Python3);
}
if !ytmusicapi {
missing.push(DepKind::YtMusicApi);
}
missing
}
pub fn install(kind: DepKind, progress: impl Fn(u64, u64) + 'static) -> Result<()> {
match kind {
DepKind::YtDlp => install_yt_dlp(progress),
DepKind::YtMusicApi => install_ytmusicapi(),
DepKind::Python3 => install_python(progress),
}
}
struct ProgressReader<R> {
inner: R,
downloaded: u64,
total: u64,
last_sent: u64,
cb: Box<dyn Fn(u64, u64)>,
}
impl<R: std::io::Read> std::io::Read for ProgressReader<R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let n = self.inner.read(buf)?;
if n > 0 {
self.downloaded += n as u64;
let step = if self.total == 0 {
1 << 16
} else {
(self.total / 50).max(1)
};
if self.downloaded - self.last_sent >= step || self.downloaded >= self.total {
self.last_sent = self.downloaded;
(self.cb)(self.downloaded, self.total);
}
}
Ok(n)
}
}
fn install_yt_dlp(progress: impl Fn(u64, u64) + 'static) -> Result<()> {
let asset = yt_dlp_asset();
let url =
format!("https://github.com/yt-dlp/yt-dlp/releases/download/{YT_DLP_VERSION}/{asset}");
let resp = ureq::get(&url)
.call()
.with_context(|| format!("Failed to download {url}"))?;
let total = resp
.headers()
.get("content-length")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
.unwrap_or(0);
let mut body = resp.into_body();
let reader = body.as_reader();
let mut reader = ProgressReader {
inner: reader,
downloaded: 0,
total,
last_sent: 0,
cb: Box::new(progress),
};
let mut bytes = Vec::new();
reader
.read_to_end(&mut bytes)
.context("Failed to read yt-dlp download")?;
let expected = yt_dlp_expected_sha256(asset);
if expected.is_empty() {
anyhow::bail!("No pinned SHA-256 for asset {asset}; cannot verify download.");
}
if sha256(&bytes) != expected {
anyhow::bail!("yt-dlp checksum mismatch — download may be corrupted or tampered.");
}
let dir = crate::data::cache_path("yt-dlp").join(YT_DLP_VERSION);
std::fs::create_dir_all(&dir).with_context(|| format!("Failed to create {}", dir.display()))?;
let path = dir.join(asset);
let tmp = dir.join(format!("{asset}.part"));
std::fs::write(&tmp, &bytes).context("Failed to write yt-dlp")?;
#[cfg(unix)]
std::fs::set_permissions(&tmp, std::os::unix::fs::PermissionsExt::from_mode(0o755))
.context("Failed to mark yt-dlp executable")?;
std::fs::rename(&tmp, &path).context("Failed to install yt-dlp")?;
set_available(DepKind::YtDlp);
Ok(())
}
fn install_python(progress: impl Fn(u64, u64) + 'static) -> Result<()> {
let asset = python_asset();
if asset.is_empty() {
anyhow::bail!("No standalone Python build available for this platform.");
}
let url = format!(
"https://github.com/astral-sh/python-build-standalone/releases/download/{PYTHON_PBS_RELEASE}/{asset}"
);
let resp = ureq::get(&url)
.call()
.with_context(|| format!("Failed to download {url}"))?;
let total = resp
.headers()
.get("content-length")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
.unwrap_or(0);
let mut body = resp.into_body();
let reader = body.as_reader();
let mut reader = ProgressReader {
inner: reader,
downloaded: 0,
total,
last_sent: 0,
cb: Box::new(progress),
};
let mut bytes = Vec::new();
reader
.read_to_end(&mut bytes)
.context("Failed to read Python download")?;
let expected = python_expected_sha256(asset);
if expected.is_empty() {
anyhow::bail!("No pinned SHA-256 for asset {asset}; cannot verify download.");
}
if sha256(&bytes) != expected {
anyhow::bail!("Python checksum mismatch — download may be corrupted or tampered.");
}
let dir = python_cache_path();
std::fs::create_dir_all(&dir).with_context(|| format!("Failed to create {}", dir.display()))?;
let cursor = std::io::Cursor::new(bytes);
let gz = flate2::read::GzDecoder::new(cursor);
let mut archive = tar::Archive::new(gz);
archive
.unpack(&dir)
.context("Failed to extract Python archive")?;
let python_bin = {
#[cfg(target_os = "windows")]
{
dir.join("python").join("python.exe")
}
#[cfg(not(target_os = "windows"))]
{
dir.join("python").join("bin").join("python3")
}
};
if !python_bin.exists() {
anyhow::bail!(
"Python archive extracted but binary not found at {}",
python_bin.display()
);
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let bin_dir = dir.join("python").join("bin");
for entry in std::fs::read_dir(&bin_dir)
.with_context(|| format!("Failed to read {}", bin_dir.display()))?
{
let entry = entry?;
if entry.file_type()?.is_file() {
std::fs::set_permissions(entry.path(), PermissionsExt::from_mode(0o755))?;
}
}
}
set_available(DepKind::Python3);
Ok(())
}
fn install_ytmusicapi() -> Result<()> {
let py = python_exe()
.ok_or_else(|| anyhow::anyhow!("Python 3 not found; install it to use pip."))?;
let output = crate::providers::run_command_with_timeout(
Command::new(&py).args(["-m", "pip", "install", "ytmusicapi"]),
Duration::from_mins(5),
)
.context("Failed to run pip")?;
if !output.status.success() {
anyhow::bail!(
"pip install ytmusicapi failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
set_available(DepKind::YtMusicApi);
let marker = yt_music_api_marker();
if let Some(parent) = marker.parent() {
let _ = std::fs::create_dir_all(parent);
}
let _ = std::fs::write(&marker, b"");
Ok(())
}
#[allow(clippy::many_single_char_names)]
pub(crate) fn sha256(data: &[u8]) -> String {
#[allow(clippy::unreadable_literal)]
const K: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
0xc67178f2,
];
let mut h: [u32; 8] = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
0x5be0cd19,
];
let bit_len = (data.len() as u64).wrapping_mul(8);
let mut msg = data.to_vec();
msg.push(0x80);
while msg.len() % 64 != 56 {
msg.push(0);
}
msg.extend_from_slice(&bit_len.to_be_bytes());
for chunk in msg.chunks_exact(64) {
let mut w = [0u32; 64];
for i in 0..16 {
w[i] = u32::from_be_bytes([
chunk[4 * i],
chunk[4 * i + 1],
chunk[4 * i + 2],
chunk[4 * i + 3],
]);
}
for i in 16..64 {
let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16]
.wrapping_add(s0)
.wrapping_add(w[i - 7])
.wrapping_add(s1);
}
let (mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh) =
(h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7]);
for i in 0..64 {
let big_s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
let ch = (e & f) ^ ((!e) & g);
let t1 = hh
.wrapping_add(big_s1)
.wrapping_add(ch)
.wrapping_add(K[i])
.wrapping_add(w[i]);
let big_s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
let maj = (a & b) ^ (a & c) ^ (b & c);
let t2 = big_s0.wrapping_add(maj);
hh = g;
g = f;
f = e;
e = d.wrapping_add(t1);
d = c;
c = b;
b = a;
a = t1.wrapping_add(t2);
}
h[0] = h[0].wrapping_add(a);
h[1] = h[1].wrapping_add(b);
h[2] = h[2].wrapping_add(c);
h[3] = h[3].wrapping_add(d);
h[4] = h[4].wrapping_add(e);
h[5] = h[5].wrapping_add(f);
h[6] = h[6].wrapping_add(g);
h[7] = h[7].wrapping_add(hh);
}
let mut out = String::with_capacity(64);
for x in h {
let _ = write!(out, "{x:08x}");
}
out
}
#[cfg(test)]
mod tests {
use super::sha256;
#[test]
fn sha256_known_vectors() {
assert_eq!(
sha256(b"abc"),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
assert_eq!(
sha256(b""),
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
assert_eq!(
sha256(b"The quick brown fox jumps over the lazy dog"),
"d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"
);
}
}