youtube-legend-cli 0.4.0

Non-interactive Rust CLI that downloads YouTube subtitles through third-party providers, using a native Unix stdin/stdout interface.
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
//! TTL-keyed local file cache for fetched subtitles.
//!
//! The `cache_path` / `read_cache` / `write_cache` helpers keep their
//! public signatures so callers outside this module are unaffected.
//!
//! GAP-AUD-2026-051: subtitle bodies are cached alongside a sidecar
//! `*.hint` file that records the [`crate::provider::SubtitleFormat`]
//! discriminator (`srt` or `noteey-transcript`). The cache hit path
//! in `commands::extract` consults the sidecar to pick the right
//! parser — without it, noteey-style bodies cached on disk would be
//! re-parsed as `Srt`, leaking `MM:SS` timestamps into the output.

#![allow(dead_code)]

use crate::error::{AppError, AppResult};
use crate::provider::SubtitleFormat;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

/// Compiled default TTL, in hours.
///
/// This is the single source of the value: `--cache-ttl` declares it as
/// its `default_value_t`, so the flag and the cache can no longer drift
/// apart. Until 2026-08-31 the two carried the literal `24`
/// independently and were kept in step by hand.
pub const DEFAULT_TTL_HOURS: u64 = 24;

/// Seconds in an hour, named because the TTL is expressed in hours at
/// every surface and in seconds at every [`Duration`].
///
/// The bare literal `3600` appeared in this module and in `src/cli.rs`,
/// which is the same duplication as the default above seen from the
/// unit side.
pub const SECONDS_PER_HOUR: u64 = 3600;

/// Converts a TTL expressed in hours into a [`Duration`].
///
/// Every caller that holds an hour count goes through here, so the
/// conversion exists once.
pub fn ttl_from_hours(hours: u64) -> Duration {
    Duration::from_secs(hours * SECONDS_PER_HOUR)
}

/// Configuration key that segments the platform cache directory.
///
/// It replaces the author environment variable this module used to
/// read. An environment variable is not configuration in this
/// product, and the old fallback folded the entire value of `HOME` into
/// the path: a segment that varied with the user name on macOS and that
/// does not exist at all on Windows.
const CACHE_QUALIFIER_KEY: &str = "cache.qualifier";
/// Suffix of the staging file used by the atomic write path. The file
/// is created next to its final destination — the rename that promotes
/// it is only atomic within a single filesystem.
const TMP_SUFFIX: &str = ".tmp";

/// Per-process counter that keeps two concurrent writes of the same
/// cache entry from sharing a staging file.
static TMP_SEQ: AtomicU64 = AtomicU64::new(0);

/// Build the absolute cache file path for a `(video_id, language, format)`
/// triple under the user's cache directory, creating the parent
/// directory if necessary.
///
/// # Errors
///
/// - \[`crate::error::AppError::InvalidInput`\] when any of the components is empty or
///   the TTL is zero.
/// - [`AppError::Internal`] when the platform's project directory cannot
///   be determined.
/// - [`AppError::Io`] when the parent directory cannot be created.
#[tracing::instrument(level = "debug", err, skip(video_id, lang, format), fields(video_id, lang, format, ttl_secs = ttl.as_secs()))]
pub fn cache_path(video_id: &str, lang: &str, format: &str, ttl: Duration) -> AppResult<PathBuf> {
    if video_id.is_empty() || lang.is_empty() || format.is_empty() {
        return Err(AppError::InvalidInput(
            "cache_path requires non-empty video_id, lang, and format".to_string(),
        ));
    }
    if ttl.is_zero() {
        return Err(AppError::InvalidInput(
            "cache_path requires a non-zero ttl".to_string(),
        ));
    }

    let dir = cache_root()?
        .join("subtitles")
        .join(sanitize(video_id)?)
        .join(sanitize(lang)?);

    std::fs::create_dir_all(&dir)
        .map_err(|e| AppError::Io(std::io::Error::other(format!("creating cache dir: {e}"))))?;

    Ok(dir.join(format!("{}.bin", sanitize(format)?)))
}

/// Root directory of the subtitle cache, before the per-entry segments.
///
/// The platform directories come from [`crate::config::project_dirs`],
/// which is the single authorised source. The cache, the configuration
/// and the session jar therefore cannot drift apart on macOS and
/// Windows, where the qualifier and the organisation become part of the
/// path.
///
/// The directory is only derived here, never created: creation belongs
/// to [`cache_path`], which owns the full per-entry path.
///
/// # Errors
///
/// - [`AppError::Internal`] when the platform exposes no project
///   directories.
fn cache_root() -> AppResult<PathBuf> {
    let proj = crate::config::project_dirs()
        .ok_or_else(|| AppError::Internal("could not determine cache directory".to_string()))?;
    Ok(qualified_root(
        proj.cache_dir(),
        configured_qualifier().as_deref(),
    ))
}

/// The operator-supplied `cache.qualifier`, or `None` when it is unset
/// or blank. An absent key means the cache lands directly under the
/// platform cache directory.
fn configured_qualifier() -> Option<String> {
    let value = crate::config::tuning_string(CACHE_QUALIFIER_KEY)?;
    let trimmed = value.trim();
    (!trimmed.is_empty()).then(|| trimmed.to_string())
}

/// Append the optional qualifier segment to `root`.
///
/// The value is sanitised before it reaches the path. A configured value
/// can carry a path separator exactly as an environment variable could,
/// and an unsanitised segment is a directory traversal.
fn qualified_root(root: &Path, qualifier: Option<&str>) -> PathBuf {
    match qualifier.map(sanitize_qualifier) {
        Some(segment) if !segment.is_empty() => root.join(segment),
        _ => root.to_path_buf(),
    }
}

fn sanitize_qualifier(input: &str) -> String {
    input
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.' {
                c
            } else {
                '_'
            }
        })
        .collect()
}

fn sanitize(input: &str) -> AppResult<String> {
    if input
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.')
    {
        Ok(input.to_string())
    } else {
        Err(AppError::InvalidInput(format!(
            "invalid path component: {input}"
        )))
    }
}

/// Read a cached entry if it exists and is still fresh.
///
/// Returns `Ok(None)` when the file does not exist or is older than `ttl`
/// (in which case the stale file is also removed).
///
/// # Errors
///
/// - [`AppError::Io`] on any filesystem or metadata read failure.
#[tracing::instrument(level = "debug", err, skip(path), fields(path = %path.display(), ttl_secs = ttl.as_secs()))]
pub async fn read_cache(path: &PathBuf, ttl: Duration) -> AppResult<Option<Vec<u8>>> {
    // A single `metadata` call answers both "does it exist?" and "how
    // old is it?" — the previous `path.exists()` guard stat-ed the
    // same file a second time on every cache hit.
    let metadata = match tokio::fs::metadata(path).await {
        Ok(m) => m,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(AppError::Io(e)),
    };
    let modified = metadata
        .modified()
        .map_err(|e| AppError::Io(std::io::Error::other(e.to_string())))?;
    let elapsed = modified
        .duration_since(UNIX_EPOCH)
        .map_err(|e| AppError::Io(std::io::Error::other(e.to_string())))?;
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_err(|e| AppError::Io(std::io::Error::other(e.to_string())))?;

    if now.saturating_sub(elapsed) > ttl {
        let _ = tokio::fs::remove_file(path).await;
        return Ok(None);
    }

    let bytes = tokio::fs::read(path).await.map_err(AppError::Io)?;
    Ok(Some(bytes))
}

/// GAP-AUD-2026-051: read a cached entry plus its format hint. The
/// hint lives in a sidecar file `<path>.hint` next to the cached
/// body. When the sidecar is missing or unreadable the function
/// conservatively reports [`SubtitleFormat::Srt`] — operators upgrading
/// from a v0.3.0 cache (which never wrote the sidecar) will continue to
/// receive SRT bodies until the entry expires and is rewritten.
///
/// A hit still costs two reads, one per file: the body and the hint
/// live in separate files by design, and [`read_cache`] is public and
/// must keep returning the raw body, so the discriminator cannot be
/// folded into the body without breaking both the on-disk format and
/// that contract. What was removed is the redundant `exists()` stat
/// inside [`read_cache`], so a hit is now one `metadata` plus the two
/// reads instead of two stats plus two reads.
///
/// # Errors
///
/// - [`AppError::Io`] on any filesystem or metadata read failure.
#[tracing::instrument(level = "debug", err, skip(path), fields(path = %path.display(), ttl_secs = ttl.as_secs()))]
pub async fn read_cache_with_hint(
    path: &PathBuf,
    ttl: Duration,
) -> AppResult<Option<(Vec<u8>, SubtitleFormat)>> {
    let bytes = match read_cache(path, ttl).await? {
        Some(b) => b,
        None => return Ok(None),
    };
    let hint_path = hint_path_for(path);
    let hint = match tokio::fs::read(&hint_path).await {
        Ok(s) => match std::str::from_utf8(&s) {
            Ok(s) => parse_hint(s).unwrap_or(SubtitleFormat::Srt),
            Err(_) => SubtitleFormat::Srt,
        },
        Err(_) => SubtitleFormat::Srt,
    };
    Ok(Some((bytes, hint)))
}

/// Persist `content` to `path`, creating the parent directory if needed.
///
/// # Errors
///
/// - [`AppError::Io`] on any filesystem write failure.
#[tracing::instrument(level = "debug", err, skip(path, content), fields(path = %path.display(), bytes = content.len()))]
pub async fn write_cache(path: &Path, content: &[u8]) -> AppResult<()> {
    write_atomic(path, content).await
}

/// Write `content` to `path` atomically: stage it in a sibling
/// temporary file, then `rename` it into place. A reader therefore
/// observes either the previous entry or the complete new one, never
/// a half-written body. The staging file is removed on failure so an
/// interrupted write leaves no debris behind.
///
/// # Errors
///
/// - [`AppError::Io`] on any filesystem write, rename, or
///   directory-creation failure.
async fn write_atomic(path: &Path, content: &[u8]) -> AppResult<()> {
    if let Some(parent) = path.parent() {
        tokio::fs::create_dir_all(parent)
            .await
            .map_err(AppError::Io)?;
    }
    let tmp = temp_path_for(path);
    if let Err(e) = tokio::fs::write(&tmp, content).await {
        let _ = tokio::fs::remove_file(&tmp).await;
        return Err(AppError::Io(e));
    }
    if let Err(e) = tokio::fs::rename(&tmp, path).await {
        let _ = tokio::fs::remove_file(&tmp).await;
        return Err(AppError::Io(e));
    }
    Ok(())
}

/// Build the staging path for an atomic write. The name carries the
/// process id and a per-process sequence number so two writers of the
/// same entry never share a staging file.
fn temp_path_for(path: &Path) -> PathBuf {
    let pid = std::process::id();
    let seq = TMP_SEQ.fetch_add(1, Ordering::Relaxed);
    let mut s = path.as_os_str().to_owned();
    s.push(format!(".{pid}.{seq}{TMP_SUFFIX}"));
    PathBuf::from(s)
}

/// GAP-AUD-2026-051: persist `content` plus its `format_hint` sidecar.
/// The hint is stored as a UTF-8 string (`srt` or `noteey-transcript`)
/// in a sibling file `<path>.hint`. The next read via
/// [`read_cache_with_hint`] recovers the discriminator so the cache
/// hit path can pick the right parser.
///
/// # Errors
///
/// - [`AppError::Io`] on any filesystem write failure.
#[tracing::instrument(level = "debug", err, skip(path, content, format_hint), fields(path = %path.display(), bytes = content.len()))]
pub async fn write_cache_with_hint(
    path: &Path,
    content: &[u8],
    format_hint: SubtitleFormat,
) -> AppResult<()> {
    // Order matters: the sidecar is committed first and the body
    // last. Readers gate on the body (`read_cache` returns `None`
    // while it is absent), so a fresh body always has its hint
    // already in place. Both writes are individually atomic, so an
    // interruption can only leave the pre-existing pair or the new
    // pair visible — never a body without its matching hint.
    let hint_path = hint_path_for(path);
    write_atomic(&hint_path, format_hint.as_str().as_bytes()).await?;
    write_atomic(path, content).await?;
    Ok(())
}

fn hint_path_for(path: &Path) -> PathBuf {
    let mut s = path.as_os_str().to_owned();
    s.push(".hint");
    PathBuf::from(s)
}

fn parse_hint(s: &str) -> Option<SubtitleFormat> {
    match s.trim() {
        "srt" => Some(SubtitleFormat::Srt),
        "noteey-transcript" => Some(SubtitleFormat::NoteeyTranscript),
        _ => None,
    }
}

/// Remove a cache entry if it exists. A missing entry is not an error.
///
/// # Errors
///
/// - [`AppError::Io`] on filesystem remove failure.
#[tracing::instrument(level = "debug", err, skip(path), fields(path = %path.display()))]
pub async fn invalidate_cache(path: &PathBuf) -> AppResult<()> {
    if path.exists() {
        tokio::fs::remove_file(path).await.map_err(AppError::Io)?;
    }
    Ok(())
}

/// Default TTL, used when the user does not pass `--cache-ttl`.
#[tracing::instrument(level = "debug")]
pub fn default_ttl() -> Duration {
    ttl_from_hours(DEFAULT_TTL_HOURS)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default_ttl_is_24_hours() {
        assert_eq!(default_ttl(), Duration::from_secs(24 * 3600));
    }

    /// Without `cache.qualifier` the cache sits directly under the
    /// platform cache directory.
    #[test]
    fn unconfigured_qualifier_adds_no_segment() {
        let root = Path::new("base").join("cache");
        assert_eq!(qualified_root(&root, None), root);
    }

    /// With `cache.qualifier` set the segment appears in the path.
    #[test]
    fn configured_qualifier_adds_one_segment() {
        let root = Path::new("base").join("cache");
        assert_eq!(qualified_root(&root, Some("acme")), root.join("acme"));
    }

    /// A configured value is sanitised like any other untrusted input,
    /// so a separator or a space cannot escape the cache directory.
    #[test]
    fn configured_qualifier_cannot_traverse_directories() {
        let root = Path::new("base").join("cache");
        assert_eq!(
            qualified_root(&root, Some("../etc a")),
            root.join(".._etc_a")
        );
    }

    /// The configuration directory, the cache root and the session jar
    /// all descend from the one [`crate::config::project_dirs`].
    ///
    /// On Linux the XDG rules ignore the qualifier and the organisation,
    /// so divergent argument triples collapse and this assertion is only
    /// a smoke check. On macOS and Windows the triple is part of the
    /// path, and this is the test that fails when a call site builds its
    /// own `ProjectDirs` again.
    ///
    /// Nothing here touches the disk: `cache_root` derives the path
    /// without creating it, so the user's real cache is left alone.
    #[test]
    fn config_cache_and_session_share_one_project_dirs() {
        let Some(dirs) = crate::config::project_dirs() else {
            return;
        };
        assert_eq!(
            crate::config::config_dir().expect("config dir resolves"),
            dirs.config_dir()
        );
        assert!(
            cache_root()
                .expect("cache root resolves")
                .starts_with(dirs.cache_dir()),
            "the cache must live under the shared cache directory"
        );
        assert!(
            crate::net::session::CookieJar::default_path()
                .expect("session path resolves")
                .starts_with(dirs.data_dir()),
            "the session jar must live under the shared data directory"
        );
    }

    #[test]
    fn qualifier_sanitizes_invalid_chars() {
        let s = sanitize_qualifier("hello world/foo");
        assert_eq!(s, "hello_world_foo");
    }

    #[test]
    fn cache_path_rejects_zero_ttl() {
        let res = cache_path("vid12345678", "en", "txt", Duration::ZERO);
        assert!(matches!(res, Err(AppError::InvalidInput(_))));
    }

    #[test]
    fn cache_path_rejects_empty_components() {
        let res = cache_path("", "en", "txt", default_ttl());
        assert!(matches!(res, Err(AppError::InvalidInput(_))));
    }

    #[test]
    fn sanitize_accepts_safe_chars() {
        assert_eq!(sanitize("video_123-abc.txt").unwrap(), "video_123-abc.txt");
    }

    #[test]
    fn sanitize_rejects_unsafe_chars() {
        assert!(sanitize("../etc/passwd").is_err());
        assert!(sanitize("with space").is_err());
    }

    /// Build a private scratch directory for the write-path tests.
    /// `tempfile` is not a dependency of this crate, so the directory
    /// is derived from the process id plus a sequence number — the
    /// same scheme the staging files use.
    fn scratch_dir(tag: &str) -> PathBuf {
        let pid = std::process::id();
        let seq = TMP_SEQ.fetch_add(1, Ordering::Relaxed);
        let dir = std::env::temp_dir().join(format!("ylc-cache-test-{tag}-{pid}-{seq}"));
        std::fs::create_dir_all(&dir).expect("scratch dir is creatable");
        dir
    }

    fn leftover_staging_files(dir: &Path) -> Vec<PathBuf> {
        let Ok(entries) = std::fs::read_dir(dir) else {
            return Vec::new();
        };
        entries
            .filter_map(Result::ok)
            .map(|e| e.path())
            .filter(|p| p.to_string_lossy().ends_with(TMP_SUFFIX))
            .collect()
    }

    #[tokio::test]
    async fn atomic_write_round_trips_and_leaves_no_staging_file() {
        let dir = scratch_dir("atomic");
        let path = dir.join("body.bin");
        write_cache(&path, b"hello").await.expect("write succeeds");
        let read = read_cache(&path, default_ttl())
            .await
            .expect("read succeeds");
        assert_eq!(read.as_deref(), Some(&b"hello"[..]));
        assert!(
            leftover_staging_files(&dir).is_empty(),
            "atomic write must not leave staging files behind"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[tokio::test]
    async fn atomic_write_replaces_previous_body_in_full() {
        let dir = scratch_dir("replace");
        let path = dir.join("body.bin");
        write_cache(&path, b"first-and-longer")
            .await
            .expect("first write succeeds");
        write_cache(&path, b"second")
            .await
            .expect("rewrite succeeds");
        let read = read_cache(&path, default_ttl())
            .await
            .expect("read succeeds");
        assert_eq!(read.as_deref(), Some(&b"second"[..]));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[tokio::test]
    async fn hint_sidecar_round_trips_and_body_is_committed_last() {
        let dir = scratch_dir("hint");
        let path = dir.join("body.bin");
        write_cache_with_hint(&path, b"cue", SubtitleFormat::NoteeyTranscript)
            .await
            .expect("write succeeds");
        // The body is renamed into place after the hint, so whenever
        // the body is visible the hint must already exist.
        assert!(hint_path_for(&path).exists(), "hint must exist with body");
        let (bytes, hint) = read_cache_with_hint(&path, default_ttl())
            .await
            .expect("read succeeds")
            .expect("entry is fresh");
        assert_eq!(bytes, b"cue");
        assert!(matches!(hint, SubtitleFormat::NoteeyTranscript));
        assert!(
            leftover_staging_files(&dir).is_empty(),
            "atomic write must not leave staging files behind"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[tokio::test]
    async fn read_cache_reports_missing_entry_as_none() {
        let dir = scratch_dir("missing");
        let path = dir.join("absent.bin");
        let read = read_cache(&path, default_ttl())
            .await
            .expect("missing entry is not an error");
        assert!(read.is_none());
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[tokio::test]
    async fn missing_hint_falls_back_to_srt() {
        let dir = scratch_dir("nohint");
        let path = dir.join("body.bin");
        write_cache(&path, b"legacy").await.expect("write succeeds");
        let (bytes, hint) = read_cache_with_hint(&path, default_ttl())
            .await
            .expect("read succeeds")
            .expect("entry is fresh");
        assert_eq!(bytes, b"legacy");
        assert!(matches!(hint, SubtitleFormat::Srt));
        let _ = std::fs::remove_dir_all(&dir);
    }
}