vdl 0.1.4

A fast, interactive terminal video downloader for YouTube, TikTok, Instagram, Twitter and Spotify
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
//! Manages the private `yt-dlp` and `ffmpeg` binaries used by `vdl`.
//!
//! Sandboxing in this project means the helper binaries live under the configured `bins_dir`
//! instead of the system `PATH`, so `vdl` can update and invoke them without modifying the
//! user's global toolchain.

use std::path::{Path, PathBuf};

use anyhow::{bail, Context, Result};
use tokio::fs;
use yt_dlp::client::deps::{Libraries, LibraryInstaller};

use crate::{config::Config, downloader, tui};

/// Returns `true` when `vdl` is running inside a Termux session on Android.
///
/// # Returns
///
/// Returns `true` when the `TERMUX_VERSION` environment variable is present or when the
/// resolved home directory looks like a Termux-managed path.
pub fn is_termux() -> bool {
    is_termux_with(
        cfg!(target_os = "android"),
        std::env::var("TERMUX_VERSION").ok().as_deref(),
        dirs::home_dir(),
    )
}

/// Applies Termux-specific environment variables before any network work begins.
///
/// # Examples
///
/// ```rust,ignore
/// if sandbox::is_termux() {
///     sandbox::apply_termux_env();
/// }
/// ```
pub fn apply_termux_env() {
    let termux_cert = "/data/data/com.termux/files/usr/etc/tls/cert.pem";
    if Path::new(termux_cert).exists() {
        std::env::set_var("SSL_CERT_FILE", termux_cert);
        std::env::set_var("REQUESTS_CA_BUNDLE", termux_cert);
    }

    let termux_prefix = "/data/data/com.termux/files/usr";
    if Path::new(termux_prefix).exists() {
        let termux_bin = format!("{termux_prefix}/bin");
        let current_path = std::env::var("PATH").unwrap_or_default();
        if !current_path.split(':').any(|segment| segment == termux_bin) {
            let new_path = if current_path.is_empty() {
                termux_bin
            } else {
                format!("{termux_bin}:{current_path}")
            };
            std::env::set_var("PATH", new_path);
        }
    }
}

/// Returns the expanded sandbox directory that stores `yt-dlp` and `ffmpeg`.
///
/// # Arguments
///
/// * `cfg` - Loaded application configuration.
///
/// # Returns
///
/// Returns the fully expanded sandbox directory path.
pub fn bins_dir(cfg: &Config) -> PathBuf {
    cfg.bins_dir_expanded()
}

/// Resolves the platform-specific path to the sandboxed `yt-dlp` executable.
///
/// # Arguments
///
/// * `cfg` - Loaded application configuration.
///
/// # Returns
///
/// Returns the absolute path to the managed `yt-dlp` binary.
pub fn ytdlp_path(cfg: &Config) -> PathBuf {
    bins_dir(cfg).join(executable_name("yt-dlp"))
}

/// Resolves the platform-specific path to the sandboxed `ffmpeg` executable.
///
/// # Arguments
///
/// * `cfg` - Loaded application configuration.
///
/// # Returns
///
/// Returns the absolute path to the managed `ffmpeg` binary.
pub fn ffmpeg_path(cfg: &Config) -> PathBuf {
    bins_dir(cfg).join(executable_name("ffmpeg"))
}

/// Builds the `yt-dlp` dependency descriptor used everywhere in the application.
///
/// # Arguments
///
/// * `cfg` - Loaded application configuration.
///
/// # Returns
///
/// Returns a [`yt_dlp::client::deps::Libraries`] value pointing at the sandboxed binaries.
pub fn libraries(cfg: &Config) -> Libraries {
    Libraries::new(ytdlp_path(cfg), ffmpeg_path(cfg))
}

/// Ensures the sandbox directory exists and downloads missing helper binaries.
///
/// # Arguments
///
/// * `cfg` - Loaded application configuration.
///
/// # Errors
///
/// Returns an error if the sandbox directory cannot be created or if either helper binary
/// cannot be downloaded.
///
/// # Examples
///
/// ```rust,ignore
/// let cfg = Config::load()?;
/// ensure_installed(&cfg).await?;
/// ```
pub async fn ensure_installed(cfg: &Config) -> Result<()> {
    let dir = bins_dir(cfg);
    fs::create_dir_all(&dir)
        .await
        .with_context(|| format!("Failed to create bins directory at {}", dir.display()))?;

    if cfg.termux_mode {
        ensure_installed_termux(cfg).await?;
        ensure_binary_permissions(cfg)?;
        return Ok(());
    }

    let installer = LibraryInstaller::new(dir);

    if !ytdlp_path(cfg).exists() {
        install_ytdlp(&installer, cfg.no_progress)
            .await
            .context("Failed to ensure sandboxed yt-dlp is installed")?;
    }

    if !ffmpeg_path(cfg).exists() {
        install_ffmpeg(&installer, cfg.no_progress)
            .await
            .context("Failed to ensure sandboxed ffmpeg is installed")?;
    }

    ensure_binary_permissions(cfg)?;

    Ok(())
}

/// Updates the sandboxed `yt-dlp` binary and ensures `ffmpeg` is present afterwards.
///
/// # Arguments
///
/// * `cfg` - Loaded application configuration.
///
/// # Errors
///
/// Returns an error if the sandbox cannot be prepared or if the update/download steps fail.
///
/// # Examples
///
/// ```rust,ignore
/// let cfg = Config::load()?;
/// update_binaries(&cfg).await?;
/// ```
pub async fn update_binaries(cfg: &Config) -> Result<()> {
    let dir = bins_dir(cfg);
    fs::create_dir_all(&dir)
        .await
        .with_context(|| format!("Failed to create bins directory at {}", dir.display()))?;

    if cfg.termux_mode {
        let pb = tui::spinner("Updating vdl dependencies...", cfg.no_progress);
        let result = update_binaries_termux(cfg).await;

        match result {
            Ok(()) => {
                tui::spinner_ok(&pb, "yt-dlp updated successfully");
                return Ok(());
            }
            Err(err) => {
                tui::spinner_err(&pb, "Failed to update yt-dlp");
                return Err(err).context("Failed to update yt-dlp");
            }
        }
    }

    let installer = LibraryInstaller::new(dir);

    if !ytdlp_path(cfg).exists() {
        install_ytdlp(&installer, cfg.no_progress)
            .await
            .context("Failed to ensure sandboxed yt-dlp is installed before update")?;
    }

    let pb = tui::spinner("Updating vdl dependencies...", cfg.no_progress);
    let downloader = downloader::build(cfg)
        .await
        .context("Failed to initialise downloader for binary update")?;

    match downloader.update_downloader().await {
        Ok(()) => tui::spinner_ok(&pb, "yt-dlp updated successfully"),
        Err(err) => {
            tui::spinner_err(&pb, "Failed to update yt-dlp");
            return Err(err).context("Failed to update yt-dlp");
        }
    }

    if !ffmpeg_path(cfg).exists() {
        install_ffmpeg(&installer, cfg.no_progress)
            .await
            .context("Failed to ensure sandboxed ffmpeg is installed after update")?;
    }

    ensure_binary_permissions(cfg)?;

    Ok(())
}

fn executable_name(base: &str) -> String {
    if cfg!(target_os = "windows") {
        format!("{base}.exe")
    } else {
        base.to_string()
    }
}

async fn install_ytdlp(installer: &LibraryInstaller, no_progress: bool) -> Result<()> {
    let pb = tui::spinner("Downloading sandboxed yt-dlp...", no_progress);

    match installer.install_youtube(None).await {
        Ok(path) => {
            tui::spinner_ok(&pb, &format!("yt-dlp downloaded to {}", path.display()));
            Ok(())
        }
        Err(err) => {
            tui::spinner_err(&pb, "Failed to download yt-dlp");
            Err(err).context(format!(
                "Failed to install yt-dlp into {}",
                installer.destination.display()
            ))
        }
    }
}

async fn install_ffmpeg(installer: &LibraryInstaller, no_progress: bool) -> Result<()> {
    let pb = tui::spinner("Downloading sandboxed ffmpeg...", no_progress);

    match installer.install_ffmpeg(None).await {
        Ok(path) => {
            tui::spinner_ok(&pb, &format!("ffmpeg downloaded to {}", path.display()));
            Ok(())
        }
        Err(err) => {
            tui::spinner_err(&pb, "Failed to download ffmpeg");
            Err(err).context(format!(
                "Failed to install ffmpeg into {}",
                installer.destination.display()
            ))
        }
    }
}

async fn ensure_installed_termux(cfg: &Config) -> Result<()> {
    ensure_ytdlp_termux(cfg, false).await?;
    ensure_ffmpeg_termux(cfg, false).await?;
    Ok(())
}

async fn update_binaries_termux(cfg: &Config) -> Result<()> {
    ensure_ytdlp_termux(cfg, true).await?;
    ensure_ffmpeg_termux(cfg, true).await?;
    ensure_binary_permissions(cfg)?;
    Ok(())
}

async fn ensure_ytdlp_termux(cfg: &Config, force: bool) -> Result<()> {
    let destination = ytdlp_path(cfg);
    if destination.exists() && !force {
        return Ok(());
    }

    if destination.exists() && force {
        fs::remove_file(&destination)
            .await
            .with_context(|| format!("Failed to remove existing {}", destination.display()))?;
    }

    let pb = tui::spinner("Downloading sandboxed yt-dlp...", cfg.no_progress);
    let result = download_termux_ytdlp(&destination).await;

    match result {
        Ok(()) => {
            tui::spinner_ok(
                &pb,
                &format!("yt-dlp downloaded to {}", destination.display()),
            );
            Ok(())
        }
        Err(err) => {
            tui::spinner_err(&pb, "Failed to download yt-dlp");
            Err(err).context(format!(
                "Failed to install yt-dlp into {}",
                destination.display()
            ))
        }
    }
}

async fn ensure_ffmpeg_termux(cfg: &Config, force: bool) -> Result<()> {
    let destination = ffmpeg_path(cfg);
    if destination.exists() && !force {
        return Ok(());
    }

    let source = find_ffmpeg_on_path().with_context(|| {
        "ffmpeg not found. Install it with:\n  pkg install ffmpeg\nThen run vdl again."
    })?;

    let pb = tui::spinner("Copying system ffmpeg into sandbox...", cfg.no_progress);
    let result = copy_binary_into_sandbox(&source, &destination, force).await;

    match result {
        Ok(()) => {
            tui::spinner_ok(&pb, &format!("ffmpeg copied to {}", destination.display()));
            Ok(())
        }
        Err(err) => {
            tui::spinner_err(&pb, "Failed to prepare ffmpeg");
            Err(err).context(format!(
                "Failed to install ffmpeg into {}",
                destination.display()
            ))
        }
    }
}

async fn copy_binary_into_sandbox(source: &Path, destination: &Path, force: bool) -> Result<()> {
    if destination.exists() && force {
        fs::remove_file(destination)
            .await
            .with_context(|| format!("Failed to remove existing {}", destination.display()))?;
    }

    fs::copy(source, destination).await.with_context(|| {
        format!(
            "Failed to copy {} into {}",
            source.display(),
            destination.display()
        )
    })?;

    Ok(())
}

#[cfg(target_os = "android")]
async fn download_termux_ytdlp(destination: &Path) -> Result<()> {
    let bytes = reqwest::get(termux_ytdlp_url())
        .await
        .context("Failed to reach GitHub releases for yt-dlp")?
        .error_for_status()
        .context("yt-dlp download returned a non-success status")?
        .bytes()
        .await
        .context("Failed to read yt-dlp download body")?;

    fs::write(destination, &bytes)
        .await
        .with_context(|| format!("Failed to write yt-dlp binary to {}", destination.display()))?;

    Ok(())
}

#[cfg(not(target_os = "android"))]
async fn download_termux_ytdlp(_destination: &Path) -> Result<()> {
    bail!("Termux yt-dlp download is only supported on Android targets")
}

#[cfg(any(target_os = "android", test))]
fn termux_ytdlp_url() -> &'static str {
    "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux_aarch64"
}

fn find_ffmpeg_on_path() -> Result<PathBuf> {
    let path = std::env::var_os("PATH").context("PATH was not set")?;

    for directory in std::env::split_paths(&path) {
        let candidate = directory.join(executable_name("ffmpeg"));
        if candidate.is_file() {
            return Ok(candidate);
        }
    }

    bail!("ffmpeg was not found on PATH")
}

fn is_termux_with(
    android_target: bool,
    termux_version: Option<&str>,
    home_dir: Option<PathBuf>,
) -> bool {
    if !android_target {
        return false;
    }

    if termux_version.is_some() {
        return true;
    }

    home_dir
        .map(|home| home.to_string_lossy().contains("com.termux"))
        .unwrap_or(false)
}

fn ensure_binary_permissions(cfg: &Config) -> Result<()> {
    #[cfg(unix)]
    {
        set_executable_permissions_if_present(&ytdlp_path(cfg))?;
        set_executable_permissions_if_present(&ffmpeg_path(cfg))?;
    }

    Ok(())
}

#[cfg(unix)]
fn set_executable_permissions_if_present(path: &Path) -> Result<()> {
    use std::os::unix::fs::PermissionsExt;

    if path.exists() {
        let mut permissions = std::fs::metadata(path)
            .with_context(|| format!("Failed to read permissions for {}", path.display()))?
            .permissions();
        permissions.set_mode(0o755);
        std::fs::set_permissions(path, permissions).with_context(|| {
            format!("Failed to set executable permissions on {}", path.display())
        })?;
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use std::fs::File;

    use super::*;
    use crate::config::{Config, PlatformQuality};

    #[test]
    fn bins_dir_uses_expanded_config_path() {
        let cfg = test_config();

        assert_eq!(bins_dir(&cfg), cfg.bins_dir_expanded());
    }

    #[test]
    fn sandbox_binary_paths_use_platform_filenames() {
        let cfg = test_config();
        let expected_ytdlp = if cfg!(target_os = "windows") {
            "yt-dlp.exe"
        } else {
            "yt-dlp"
        };
        let expected_ffmpeg = if cfg!(target_os = "windows") {
            "ffmpeg.exe"
        } else {
            "ffmpeg"
        };

        assert_eq!(ytdlp_path(&cfg), bins_dir(&cfg).join(expected_ytdlp));
        assert_eq!(ffmpeg_path(&cfg), bins_dir(&cfg).join(expected_ffmpeg));
    }

    #[test]
    fn libraries_are_built_from_sandbox_paths() {
        let cfg = test_config();
        let libs = libraries(&cfg);

        assert_eq!(libs.youtube, ytdlp_path(&cfg));
        assert_eq!(libs.ffmpeg, ffmpeg_path(&cfg));
    }

    #[test]
    fn detects_termux_from_env_or_home_path() {
        assert!(is_termux_with(true, Some("0.118.0"), None));
        assert!(is_termux_with(
            true,
            None,
            Some(PathBuf::from("/data/data/com.termux/files/home"))
        ));
        assert!(!is_termux_with(
            true,
            None,
            Some(PathBuf::from("/home/occ"))
        ));
        assert!(!is_termux_with(
            false,
            Some("0.118.0"),
            Some(PathBuf::from("/data/data/com.termux/files/home"))
        ));
    }

    #[cfg(unix)]
    #[test]
    fn executable_permissions_are_applied_when_binary_exists() {
        use std::os::unix::fs::PermissionsExt;

        let dir = unique_test_dir("chmod");
        std::fs::create_dir_all(&dir).expect("test dir should be created");
        let path = dir.join("yt-dlp");

        File::create(&path).expect("test binary should be created");
        let mut permissions = std::fs::metadata(&path)
            .expect("metadata should be readable")
            .permissions();
        permissions.set_mode(0o644);
        std::fs::set_permissions(&path, permissions).expect("permissions should be set");

        set_executable_permissions_if_present(&path).expect("chmod should succeed");

        let mode = std::fs::metadata(&path)
            .expect("metadata should be readable")
            .permissions()
            .mode()
            & 0o777;
        assert_eq!(mode, 0o755);

        std::fs::remove_dir_all(&dir).expect("test dir cleanup should succeed");
    }

    #[test]
    fn finds_ffmpeg_on_custom_path() {
        let dir = unique_test_dir("ffmpeg");
        std::fs::create_dir_all(&dir).expect("test dir should be created");
        let executable = dir.join(if cfg!(target_os = "windows") {
            "ffmpeg.exe"
        } else {
            "ffmpeg"
        });
        File::create(&executable).expect("ffmpeg test binary should be created");

        let previous_path = std::env::var_os("PATH");
        std::env::set_var("PATH", dir.as_os_str());

        let found = find_ffmpeg_on_path().expect("ffmpeg should be found");
        assert_eq!(found, executable);

        if let Some(previous_path) = previous_path {
            std::env::set_var("PATH", previous_path);
        } else {
            std::env::remove_var("PATH");
        }

        std::fs::remove_dir_all(&dir).expect("test dir cleanup should succeed");
    }

    #[test]
    fn termux_installer_uses_linux_aarch64_binary_url() {
        assert_eq!(
            termux_ytdlp_url(),
            "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux_aarch64"
        );
    }

    fn test_config() -> Config {
        Config {
            download_path: "~/Downloads/vdl".to_string(),
            default_format: "mp4".to_string(),
            default_video_quality: "1080".to_string(),
            platform_quality: PlatformQuality {
                youtube: "1080".to_string(),
                tiktok: "720".to_string(),
                instagram: "720".to_string(),
                twitter: "720".to_string(),
                spotify: "best".to_string(),
            },
            bins_dir: "~/.local/share/vdl/bins".to_string(),
            cookies_file: None,
            cookies_from_browser: None,
            confirm_before_download: true,
            search_results_count: 8,
            termux_mode: false,
            no_progress: false,
        }
    }

    fn unique_test_dir(name: &str) -> PathBuf {
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("system time should be after epoch")
            .as_nanos();

        std::env::temp_dir().join(format!("vdl-sandbox-test-{name}-{nanos}"))
    }
}