goosemusic 1.2.0

A music player with YouTube search, local playback, and OS media controls
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
//! Runtime dependency detection and self-installation.
//!
//! `goosemusic` shells out to external tools. `yt-dlp` (streaming, downloads,
//! search fallback) ships standalone per-OS binaries on its GitHub releases,
//! so it can be downloaded and cached by the app itself. `ytmusicapi` (nicer
//! `YouTube` Music search) is an optional `Python` package installed via `pip`
//! when Python 3 is present; without it the app falls back to `yt-dlp` for
//! search. Python 3 itself can be auto-installed from the
//! `python-build-standalone` project (standalone, relocatable builds that
//! include pip), or found on the system PATH.
//!
//! The pinned versions + SHA-256 maps (see [`YT_DLP_VERSION`],
//! [`PYTHON_VERSION`], etc.) let downloads be verified instead of blindly
//! executing whatever the hosting service provides.

#![allow(clippy::unreadable_literal)]

use std::{fmt::Write, io::Read, path::PathBuf, process::Command, sync::Mutex, time::Duration};

use anyhow::{Context, Result};

/// Pinned `yt-dlp` release. Bump deliberately; the SHA-256 map below must be
/// updated to match the new release's `SHA2-256SUMS`.
pub const YT_DLP_VERSION: &str = "2026.08.19";

/// Pinned python-build-standalone release tag.
pub const PYTHON_PBS_RELEASE: &str = "20260807";

/// Pinned `CPython` version inside the above release.
pub const PYTHON_VERSION: &str = "3.13.15";

/// External tools the app may need. `Python3` is never auto-installed (it's an
/// OS package); the rest the app can fetch itself.
#[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",
        }
    }

    /// Whether the app can download/install this dependency itself.
    pub fn auto_installable(self) -> bool {
        match self {
            DepKind::YtDlp | DepKind::YtMusicApi | DepKind::Python3 => true,
        }
    }

    /// All dependency kinds, for iteration in the Settings / startup dialogs.
    pub fn all() -> &'static [DepKind] {
        &[DepKind::YtDlp, DepKind::YtMusicApi, DepKind::Python3]
    }
}

/// The `yt-dlp` release asset for the current target (standalone binary).
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"
    }
}

/// Expected SHA-256 of [`yt_dlp_asset`] for [`YT_DLP_VERSION`], from the
/// release's `SHA2-256SUMS`.
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",
        _ => "",
    }
}

/// The python-build-standalone `install_only_stripped` archive for the current
/// target platform. These are the smallest archives that include Python, pip,
/// and the standard library.
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"))
    )))]
    {
        ""
    }
}

/// Expected SHA-256 of [`python_asset`] for the pinned release.
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"
        }
        _ => "",
    }
}

/// The cache directory for the standalone Python installation.
fn python_cache_path() -> PathBuf {
    crate::data::cache_path("python").join(PYTHON_VERSION)
}

/// Resolve the Python 3 interpreter to invoke. Resolution order:
///   1. `GOOSEMUSIC_PYTHON` env var override
///   2. Previously downloaded + cached standalone copy
///   3. `python3` / `python` resolved via PATH
///
/// Returns `None` when no Python 3 is available.
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))
    })
}

/// Resolve a system Python (not the managed copy). Used as a fallback when the
/// managed Python lacks a needed package but the system Python has it.
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()
}

/// Check if a specific Python interpreter has ytmusicapi installed.
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 {
    // Check the resolved Python (managed or system) first.
    if python_exe().is_some_and(|py| has_ytmusicapi(&py)) {
        return true;
    }
    // Fall back: check system Python3/Python when the managed copy lacks it.
    ["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)
            }
    })
}

/// The cached download path for the pinned `yt-dlp` build (if present).
fn yt_dlp_cache_path() -> PathBuf {
    crate::data::cache_path("yt-dlp")
        .join(YT_DLP_VERSION)
        .join(yt_dlp_asset())
}

/// Marker file written when the app installs `ytmusicapi` via `pip`, so the
/// Settings view can tell an app-managed install from a system-provided one.
fn yt_music_api_marker() -> PathBuf {
    crate::data::cache_path("ytmusicapi")
}

/// Return the `yt-dlp` executable to use, preferring (in order):
///
///     1. an explicit `GOOSEMUSIC_YT_DLP` override,
///     2. a previously downloaded + cached copy,
///     3. `yt-dlp` resolved via `PATH`.
/// `None` means `yt-dlp` is not available and must be installed.
#[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
}

/// Build a `Command` pre-targeted at the resolved `yt-dlp`, or an error
/// directing the user to the dependency dialog.
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))
}

/// Detect which dependencies are missing, returning them for the startup
/// dialog. Cheap: a couple of short `--version`/`import` probes.
/// Runtime availability of the external tools, cached from the last detection
/// (or updated as the user installs them from the startup dialog). The OS
/// environment is process-global, so this is a global cache read by
/// [`crate::providers::ProviderId::capabilities`] to decide whether a source is
/// searchable / streamable / downloadable right now.
#[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,
});

/// Current external-tool availability (drives per-provider capabilities).
pub fn availability() -> DepAvailability {
    *AVAILABILITY.lock().unwrap()
}

/// Replace the cached availability (called by [`detect_missing`]).
pub fn set_availability(a: DepAvailability) {
    *AVAILABILITY.lock().unwrap() = a;
}

/// Record that `kind` is now present (e.g. after a successful install), updating
/// the cached availability that drives per-provider capabilities.
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);
}

/// Whether `kind` is currently available (on PATH / importable), regardless of
/// whether the app manages its own copy.
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,
    }
}

/// Whether the app has installed its own managed copy of `kind` (as opposed to
/// relying on a system-provided one). For `yt-dlp` this is the cached binary;
/// for `ytmusicapi` it's the app's `pip install` marker file. The app can only
/// remove deps it manages itself, so this doubles as the uninstall guard.
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(),
    }
}

/// Remove the app-managed copy of `kind` (falls back to any system-provided
/// one). Returns an error for kinds the app cannot uninstall.
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);
            // Clear the app-installed marker regardless of the pip outcome.
            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
}

/// Install a single dependency. Auto-installable deps do the work here; calling
/// this with `Python3` returns an error (the dialog disables that row).
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),
    }
}

/// A `Read` adapter that reports download progress (bytes fetched / total)
/// through `cb`, throttled to ~2% steps so the UI isn't flooded with updates.
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(())
}

/// Compact, dependency-free SHA-256 (used to verify the yt-dlp download).
#[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"
        );
    }
}