youtube-legend-cli 0.3.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
//! Error types and exit codes for the CLI.
//!
//! All public items return [`AppResult<T>`], which is a `Result<T, AppError>`.
//! The [`AppError`] enum carries the exit code, an English display message,
//! and (when applicable) a structured [`NoSubtitleReason`] that callers can
//! branch on without parsing the error string.

use std::process::{ExitCode, Termination};
use thiserror::Error;

/// BSD sysexits.h constants. See `man 3 sysexits` and
/// <https://man.openbsd.org/sysexits>. Mapped from the legacy 2-7
/// scheme to provide interoperability with downstream POSIX tooling
/// that distinguishes exit codes by category.
pub mod sysexits {
    /// Command line usage error (BSD sysexits.h: `EX_USAGE`).
    pub const EX_USAGE: u8 = 64;
    /// Data format error (BSD sysexits.h: `EX_DATAERR`).
    pub const EX_DATAERR: u8 = 65;
    /// Cannot open input (BSD sysexits.h: `EX_NOINPUT`).
    pub const EX_NOINPUT: u8 = 66;
    /// Service unavailable (BSD sysexits.h: `EX_UNAVAILABLE`).
    pub const EX_UNAVAILABLE: u8 = 69;
    /// Internal software error (BSD sysexits.h: `EX_SOFTWARE`).
    pub const EX_SOFTWARE: u8 = 70;
}

/// Top-level error type returned by every public API in this crate.
///
/// The `Display` impl is the user-facing message written to stderr by
/// [`Termination::report`]. It is intentionally in English so downstream
/// consumers can parse exit codes and pipe error fields.
#[doc(alias = "error")]
#[doc(alias = "Error")]
#[doc(alias = "cli_error")]
#[doc(alias = "exit code")]
#[doc(alias = "sysexits")]
#[doc(alias = "BSD")]
#[doc(alias = "error type")]
#[doc(alias = "thiserror")]
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum AppError {
    /// The CLI was invoked with an unsupported combination of flags.
    #[error("invalid usage: {0}")]
    InvalidUsage(String),

    /// A user-supplied input string was rejected by validation.
    #[error("invalid input: {0}")]
    InvalidInput(String),

    /// stdin was empty or contained only whitespace.
    #[error("stdin is empty")]
    StdinEmpty,

    /// A URL was syntactically valid but not a recognized `YouTube` URL.
    #[error("invalid url: {0}")]
    InvalidUrl(String),

    /// Subtitle lookup succeeded but the video has no subtitle that matches
    /// the request. The inner reason captures *why*.
    #[error("no subtitle: {0}")]
    NoSubtitle(NoSubtitleReason),

    /// Both providers in the chain returned transient errors.
    #[error("providers unavailable")]
    ProviderUnavailable,

    /// Upstream answered HTTP 429. Carries the parsed `Retry-After`
    /// delta-seconds when the provider sent one (EC-021).
    #[error("rate limited by provider (HTTP 429)")]
    RateLimited {
        /// Parsed `Retry-After` value in seconds, when present.
        retry_after_secs: Option<u64>,
    },

    /// An HTTP request exceeded the configured timeout.
    #[error("timeout: {0}")]
    Timeout(String),

    /// Wrapped [`std::io::Error`].
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),

    /// Wrapped [`reqwest::Error`].
    #[error("http error: {0}")]
    Http(#[from] reqwest::Error),

    /// Wrapped [`url::ParseError`].
    #[error("url parse error: {0}")]
    UrlParse(#[from] url::ParseError),

    /// Wrapped [`serde_json::Error`].
    #[error("serialization error: {0}")]
    Serde(#[from] serde_json::Error),

    /// A cryptographic primitive failed (PBKDF2, AES, etc.).
    #[error("crypto error: {0}")]
    Crypto(String),

    /// Decoded subtitle exceeded the 50 MiB in-memory safety cap.
    #[error("subtitle exceeds limit: {0} bytes")]
    SubtitleTooLarge(usize),

    /// Catch-all for internal invariant violations. Indicates a bug.
    #[error("internal error: {0}")]
    Internal(String),

    /// The watch-page HTML did not contain the `ytInitialPlayerResponse`
    /// JavaScript variable. Surfaces a structurally broken `YouTube` page
    /// (anti-bot interstitial, age gate, or layout change) without
    /// silently treating it as a missing subtitle.
    #[error("player response missing: {0}")]
    PlayerResponseMissing(String),

    /// The watch-page response body exceeded the configured `DoS` guard
    /// before `serde_json` was allowed to allocate. The size is
    /// recorded so operators can tune the limit via configuration.
    #[error("player response too large: {bytes} bytes exceeds {limit}")]
    PlayerResponseTooLarge {
        /// Observed body size in bytes (from `Content-Length` or actual read).
        bytes: usize,
        /// Configured cap, in bytes.
        limit: usize,
    },

    /// The `playerCaptionsTracklistRenderer` block was present but
    /// contained zero usable tracks. Differs from a language miss:
    /// this means the video has no captions at all.
    #[error("caption track not found")]
    CaptionTrackNotFound,

    /// The `playabilityStatus.status` field was anything other than
    /// `OK` (e.g. `LOGIN_REQUIRED`, `ERROR`, `CONTENT_CHECK_REQUIRED`).
    /// Carries the raw status string for diagnosis.
    #[error("playability status denied: {0}")]
    PlayabilityStatusDenied(String),

    /// A BCP-47 language tag from a `CaptionTrack` failed to parse.
    /// Surfaces a malformed upstream payload without panicking.
    #[error("language parse error: {0}")]
    LanguageParseError(String),

    /// The `player.js` decipher routine could not produce a valid
    /// plaintext signature. This happens when the regex fails to
    /// locate the operation table, when the operations vector is
    /// empty after extraction, or when a `&sig=` query parameter is
    /// shorter than the expected number of operations.
    #[error("signature decipher failed: {0}")]
    SignatureDecipherFailed(String),

    /// The `YouTube` `timedtext` endpoint returned an error that the
    /// provider could not classify (non-JSON body, HTTP status
    /// outside the known mapping, or body that fails to parse as
    /// Srv3/JSON3). This variant is distinct from `Http` (transport
    /// failure before reaching the upstream) and from
    /// `ProviderUnavailable` (chain exhausted without a structured
    /// reason): the request reached the upstream but the response
    /// could not be turned into a `SubtitleInfo`.
    #[error("timedtext upstream error: {0}")]
    TimedtextUpstreamError(String),
}

/// Structured reason why a video has no matching subtitle.
///
/// Returned via [`NoSubtitleReason::from_status`] when the upstream provider
/// answers with one of the recognized HTTP status codes, or constructed
/// directly by providers that discover the absence in the response body.
#[derive(Debug, Clone, Copy, Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum NoSubtitleReason {
    /// Video is private, members-only, or age-restricted (HTTP 403).
    #[error("video is private or age-restricted (HTTP 403)")]
    PrivateOrAgeRestricted,

    /// Video does not exist (HTTP 404).
    #[error("video not found (HTTP 404)")]
    NotFound,

    /// Video was removed by the author (HTTP 410).
    #[error("video removed by author (HTTP 410)")]
    Gone,

    /// Video is unavailable for legal reasons (HTTP 451).
    #[error("video unavailable for legal reasons (HTTP 451)")]
    UnavailableForLegalReasons,

    /// The video exists but no captions have been published.
    #[error("no captions published for this video")]
    NotPublished,

    /// Captions exist but not in the requested language.
    #[error("requested language is unavailable")]
    LanguageUnavailable,
}

impl NoSubtitleReason {
    /// Map an HTTP status code to a known reason, or `None` if the status
    /// does not correspond to any of the structured cases.
    pub fn from_status(status: u16) -> Option<Self> {
        match status {
            403 => Some(Self::PrivateOrAgeRestricted),
            404 => Some(Self::NotFound),
            410 => Some(Self::Gone),
            451 => Some(Self::UnavailableForLegalReasons),
            _ => None,
        }
    }
}

impl AppError {
    /// Process exit code for this error. See the README exit-code table.
    pub fn exit_code(&self) -> u8 {
        use sysexits::*;
        match self {
            AppError::InvalidUsage(_) | AppError::InvalidInput(_) | AppError::StdinEmpty => {
                EX_USAGE
            }
            AppError::InvalidUrl(_) | AppError::UrlParse(_) => EX_DATAERR,
            AppError::NoSubtitle(_) => EX_NOINPUT,
            AppError::ProviderUnavailable | AppError::RateLimited { .. } => EX_UNAVAILABLE,
            AppError::Timeout(_)
            | AppError::Io(_)
            | AppError::Http(_)
            | AppError::Serde(_)
            | AppError::Crypto(_)
            | AppError::SubtitleTooLarge(_)
            | AppError::Internal(_)
            | AppError::PlayerResponseMissing(_)
            | AppError::PlayerResponseTooLarge { .. }
            | AppError::CaptionTrackNotFound
            | AppError::PlayabilityStatusDenied(_)
            | AppError::LanguageParseError(_)
            | AppError::SignatureDecipherFailed(_)
            | AppError::TimedtextUpstreamError(_) => EX_SOFTWARE,
        }
    }

    /// If this is [`AppError::NoSubtitle`], return the inner reason.
    /// Otherwise, return [`NoSubtitleReason::NotPublished`] as a neutral
    /// default so callers can always branch on the reason.
    pub fn reason(&self) -> NoSubtitleReason {
        if let AppError::NoSubtitle(r) = self {
            *r
        } else {
            NoSubtitleReason::NotPublished
        }
    }
}

impl Termination for AppError {
    fn report(self) -> ExitCode {
        tracing::error!(target: "user_error", code = self.exit_code(), "{}", self);
        ExitCode::from(self.exit_code())
    }
}

impl From<AppError> for ExitCode {
    fn from(err: AppError) -> Self {
        ExitCode::from(err.exit_code())
    }
}

/// Convenience alias for `Result<T, AppError>`.
pub type AppResult<T> = Result<T, AppError>;

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

    #[test]
    fn no_subtitle_reason_from_status() {
        assert_eq!(
            NoSubtitleReason::from_status(403),
            Some(NoSubtitleReason::PrivateOrAgeRestricted)
        );
        assert_eq!(
            NoSubtitleReason::from_status(404),
            Some(NoSubtitleReason::NotFound)
        );
        assert_eq!(
            NoSubtitleReason::from_status(410),
            Some(NoSubtitleReason::Gone)
        );
        assert_eq!(
            NoSubtitleReason::from_status(451),
            Some(NoSubtitleReason::UnavailableForLegalReasons)
        );
        assert_eq!(NoSubtitleReason::from_status(500), None);
    }

    #[test]
    fn no_subtitle_exit_code_is_66() {
        let err = AppError::NoSubtitle(NoSubtitleReason::NotPublished);
        assert_eq!(err.exit_code(), 66);
    }

    #[test]
    fn stdin_empty_exit_code_is_64() {
        assert_eq!(AppError::StdinEmpty.exit_code(), 64);
    }

    #[test]
    fn subtitle_too_large_exit_code_is_70() {
        assert_eq!(AppError::SubtitleTooLarge(60_000_000).exit_code(), 70);
    }

    #[test]
    fn timeout_exit_code_is_70() {
        assert_eq!(AppError::Timeout("after 30s".to_string()).exit_code(), 70);
    }

    #[test]
    fn provider_unavailable_exit_code_is_69() {
        assert_eq!(AppError::ProviderUnavailable.exit_code(), 69);
    }

    #[test]
    fn rate_limited_exit_code_is_69() {
        let err = AppError::RateLimited {
            retry_after_secs: Some(60),
        };
        assert_eq!(err.exit_code(), 69);
    }

    #[test]
    fn invalid_url_exit_code_is_65() {
        assert_eq!(AppError::InvalidUrl("bad".to_string()).exit_code(), 65);
    }

    #[test]
    fn internal_error_exit_code_is_70() {
        assert_eq!(AppError::Internal("oops".to_string()).exit_code(), 70);
    }

    #[test]
    fn player_response_missing_exit_code_is_70() {
        let err = AppError::PlayerResponseMissing("watch?v=abc".to_string());
        assert_eq!(err.exit_code(), 70);
    }

    #[test]
    fn player_response_too_large_exit_code_is_70() {
        let err = AppError::PlayerResponseTooLarge {
            bytes: 11_000_000,
            limit: 10_000_000,
        };
        assert_eq!(err.exit_code(), 70);
    }

    #[test]
    fn caption_track_not_found_exit_code_is_70() {
        assert_eq!(AppError::CaptionTrackNotFound.exit_code(), 70);
    }

    #[test]
    fn playability_status_denied_exit_code_is_70() {
        let err = AppError::PlayabilityStatusDenied("LOGIN_REQUIRED".to_string());
        assert_eq!(err.exit_code(), 70);
    }

    #[test]
    fn language_parse_error_exit_code_is_70() {
        let err = AppError::LanguageParseError("not-bcp47".to_string());
        assert_eq!(err.exit_code(), 70);
    }

    #[test]
    fn signature_decipher_failed_exit_code_is_70() {
        let err = AppError::SignatureDecipherFailed("op table empty".to_string());
        assert_eq!(err.exit_code(), 70);
    }

    #[test]
    fn timedtext_upstream_error_exit_code_is_70() {
        let err = AppError::TimedtextUpstreamError("unexpected EOF".to_string());
        assert_eq!(err.exit_code(), 70);
    }

    #[test]
    fn timedtext_upstream_error_display_includes_payload() {
        let err = AppError::TimedtextUpstreamError("http 503 from timedtext".to_string());
        let msg = err.to_string();
        assert!(msg.contains("timedtext"), "missing variant name in {msg}");
        assert!(
            msg.contains("http 503 from timedtext"),
            "missing payload in {msg}"
        );
    }

    #[test]
    fn timedtext_upstream_error_is_distinct_from_http_and_provider_unavailable() {
        // Compile-time check: TimedtextUpstreamError is a separate
        // variant from Http, Timeout, and ProviderUnavailable. The
        // pattern match below must NOT match those alternatives.
        let err = AppError::TimedtextUpstreamError("bad json".to_string());
        assert!(!matches!(err, AppError::Http(_)));
        assert!(!matches!(err, AppError::Timeout(_)));
        assert!(!matches!(err, AppError::ProviderUnavailable));
        assert!(!matches!(err, AppError::Serde(_)));
    }

    #[test]
    fn all_exit_codes_are_in_sysexits_range() {
        let errs = vec![
            AppError::InvalidUsage("x".into()),
            AppError::InvalidInput("x".into()),
            AppError::StdinEmpty,
            AppError::InvalidUrl("x".into()),
            AppError::UrlParse(url::ParseError::EmptyHost),
            AppError::NoSubtitle(NoSubtitleReason::NotPublished),
            AppError::ProviderUnavailable,
            AppError::RateLimited {
                retry_after_secs: None,
            },
            AppError::Timeout("x".into()),
            AppError::Internal("x".into()),
            AppError::PlayerResponseMissing("x".into()),
            AppError::PlayerResponseTooLarge { bytes: 1, limit: 1 },
            AppError::CaptionTrackNotFound,
            AppError::PlayabilityStatusDenied("x".into()),
            AppError::LanguageParseError("x".into()),
            AppError::TimedtextUpstreamError("x".into()),
        ];
        for e in errs {
            let code = e.exit_code();
            assert!(
                (64..=78).contains(&code),
                "exit code {code} out of sysexits range 64-78 for {e:?}"
            );
        }
    }

    #[test]
    fn reason_helper_returns_inner_reason() {
        let err = AppError::NoSubtitle(NoSubtitleReason::NotFound);
        assert_eq!(err.reason(), NoSubtitleReason::NotFound);
    }

    #[test]
    fn reason_helper_defaults_to_not_published() {
        let err = AppError::Timeout("x".to_string());
        assert_eq!(err.reason(), NoSubtitleReason::NotPublished);
    }

    #[test]
    fn no_subtitle_reason_messages_are_human_readable() {
        assert!(NoSubtitleReason::PrivateOrAgeRestricted
            .to_string()
            .contains("403"));
        assert!(NoSubtitleReason::UnavailableForLegalReasons
            .to_string()
            .contains("451"));
    }
}