ncm2mp3 0.3.2

Decrypt Netease Cloud Music NCM files to their original audio format (MP3/FLAC/M4A). Rust CLI with tags, cover art, filename templates, per-song folder mode, parallel batching, watch mode, shell completions, and bilingual EN/ZH UI.
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
use std::path::PathBuf;

use anyhow::{anyhow, Result};
use clap::{Arg, ArgAction, ArgMatches, Command};
use clap_complete::Shell;

use crate::i18n::{Lang, Strings};

/// Top-level dispatch: either the default "decrypt" flow (no subcommand),
/// or a specialized mode invoked via subcommand.
pub enum CliCommand {
    Decrypt(Cli),
    Info(InfoArgs),
    Cover(CoverArgs),
    Watch(WatchArgs),
    Completion(Shell),
}

/// Whether to emit ANSI color codes in per-file status lines.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorChoice {
    /// Emit color when stderr is a TTY; skip it when redirected (default).
    Auto,
    /// Always emit color, even if stderr is redirected.
    Always,
    /// Never emit color.
    Never,
}

impl ColorChoice {
    pub fn parse(raw: &str) -> Option<Self> {
        match raw.to_ascii_lowercase().as_str() {
            "auto" => Some(Self::Auto),
            "always" => Some(Self::Always),
            "never" => Some(Self::Never),
            _ => None,
        }
    }
}

/// What to do when the output file already exists.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConflictStrategy {
    /// Leave the existing file alone and count it as skipped (default).
    Skip,
    /// Overwrite the existing file.
    Overwrite,
    /// Append `-1`, `-2`, … to the stem until a free path is found.
    Rename,
}

impl ConflictStrategy {
    /// Parse the string coming from `--on-conflict`.
    pub fn parse(s: &str) -> Option<Self> {
        match s.to_ascii_lowercase().as_str() {
            "skip" => Some(Self::Skip),
            "overwrite" => Some(Self::Overwrite),
            "rename" => Some(Self::Rename),
            _ => None,
        }
    }
}

/// Decrypt-mode arguments, flat struct preserved across the pipeline.
#[derive(Debug, Clone)]
pub struct Cli {
    /// Positional `<INPUT>`. May be `None` when the user passes only
    /// `--from-file <list>`.
    pub input: Option<PathBuf>,
    /// Additional input sources read from a text file, one path per line
    /// (lines starting with `#` and blank lines are ignored).
    pub from_file: Option<PathBuf>,
    pub output: Option<PathBuf>,
    /// When `None`, the pipeline preserves the input file's stem verbatim and
    /// only swaps the extension. A template is only applied when the user
    /// explicitly passes `--template`.
    pub template: Option<String>,
    pub recursive: bool,
    pub format: Vec<String>,
    /// Glob patterns for files to skip during directory collection
    /// (matched against the absolute path as a string, using `globset`).
    pub exclude: Vec<String>,
    /// Optional cap on how many files actually get processed. Useful for
    /// smoke-testing a large library with a handful of files first.
    pub limit: Option<usize>,
    pub no_tag: bool,
    pub folder: bool,
    pub jobs: Option<usize>,
    /// What to do when an output file already exists.
    pub on_conflict: ConflictStrategy,
    pub dry_run: bool,
    pub verbose: u8,
    pub color: ColorChoice,
    /// Explicit override of config file location; when `None`, the default
    /// platform path is consulted.
    pub config_path: Option<PathBuf>,
    /// `--no-config` skips config-file loading entirely.
    pub no_config: bool,
    /// Retained for diagnostics and future locale-aware logic.
    #[allow(dead_code)]
    pub lang: Lang,
}

impl Cli {
    pub fn log_level(&self) -> log::LevelFilter {
        match self.verbose {
            0 => log::LevelFilter::Warn,
            1 => log::LevelFilter::Info,
            _ => log::LevelFilter::Debug,
        }
    }
}

/// `info` subcommand args: inspect headers without decrypting audio.
#[derive(Debug, Clone)]
pub struct InfoArgs {
    pub input: PathBuf,
    pub recursive: bool,
}

/// `cover` subcommand args: extract the embedded cover image without
/// decrypting the audio.
#[derive(Debug, Clone)]
pub struct CoverArgs {
    pub input: PathBuf,
    pub output: Option<PathBuf>,
    pub recursive: bool,
    pub overwrite: bool,
}

/// `watch` subcommand args: watch a directory and auto-decrypt new NCM
/// files as they appear. Reuses most of the decrypt pipeline options.
#[derive(Debug, Clone)]
pub struct WatchArgs {
    /// The directory to watch.
    pub dir: PathBuf,
    pub output: Option<PathBuf>,
    pub template: Option<String>,
    pub format: Vec<String>,
    pub no_tag: bool,
    pub folder: bool,
    pub on_conflict: ConflictStrategy,
}

/// Build the clap `Command` with help text from the chosen translation table.
///
/// We use the builder API instead of `#[derive(Parser)]` because derive
/// attributes require `&'static str` literals, which means the help text is
/// baked in at compile time. The builder lets us swap tables at runtime based
/// on locale detection.
pub fn build_command(s: &'static Strings) -> Command {
    Command::new("ncm2mp3")
        .version(env!("CARGO_PKG_VERSION"))
        .about(s.cli_about)
        // Allow top-level positional INPUT to be skipped when a subcommand is
        // invoked (e.g. `ncm2mp3 info song.ncm` doesn't need top-level INPUT).
        .subcommand_negates_reqs(true)
        // Subcommand prefix matching — `inf` matches `info`, `comp` matches
        // `completion`, etc. Without this, since INPUT is also a positional
        // arg at the top level, clap would silently consume `inf` as INPUT
        // and the user would only see "unexpected argument" or a confusing
        // path-not-found error. With it, prefix typos route to the right
        // subcommand automatically. Substitution typos like `wath` (vs
        // `watch`) still fall through to the explicit suggester in main.rs.
        .infer_subcommands(true)
        .arg(
            Arg::new("input")
                .value_name(s.val_input)
                .help(s.arg_input)
                // INPUT becomes optional when --from-file supplies the list;
                // clap's `required_unless_present` handles "either-or" cleanly.
                .required_unless_present("from-file")
                .value_parser(clap::value_parser!(PathBuf)),
        )
        .arg(
            Arg::new("from-file")
                .long("from-file")
                .value_name(s.val_path)
                .help(s.arg_from_file)
                .value_parser(clap::value_parser!(PathBuf)),
        )
        .arg(
            Arg::new("output")
                .short('o')
                .long("output")
                .value_name(s.val_dir)
                .help(s.arg_output)
                .value_parser(clap::value_parser!(PathBuf)),
        )
        .arg(
            Arg::new("template")
                .short('t')
                .long("template")
                .value_name(s.val_template)
                .help(s.arg_template),
        )
        .arg(
            Arg::new("recursive")
                .short('r')
                .long("recursive")
                .help(s.arg_recursive)
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("format")
                .long("format")
                .value_name(s.val_fmt)
                .value_delimiter(',')
                .help(s.arg_format)
                .action(ArgAction::Append),
        )
        .arg(
            Arg::new("exclude")
                .long("exclude")
                .value_name(s.val_pattern)
                .help(s.arg_exclude)
                .action(ArgAction::Append),
        )
        .arg(
            Arg::new("limit")
                .long("limit")
                .value_name(s.val_n)
                .help(s.arg_limit)
                .value_parser(clap::value_parser!(usize)),
        )
        .arg(
            Arg::new("no-tag")
                .long("no-tag")
                .help(s.arg_no_tag)
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("folder")
                .short('F')
                .long("folder")
                .help(s.arg_folder)
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("jobs")
                .short('j')
                .long("jobs")
                .value_name(s.val_n)
                .help(s.arg_jobs)
                .value_parser(clap::value_parser!(usize)),
        )
        .arg(
            Arg::new("on-conflict")
                .long("on-conflict")
                .value_name(s.val_conflict)
                .help(s.arg_on_conflict)
                .value_parser(["skip", "overwrite", "rename"])
                .conflicts_with("overwrite"),
        )
        .arg(
            Arg::new("overwrite")
                .long("overwrite")
                .help(s.arg_overwrite)
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("config")
                .long("config")
                .value_name(s.val_path)
                .help(s.arg_config)
                .value_parser(clap::value_parser!(PathBuf)),
        )
        .arg(
            Arg::new("no-config")
                .long("no-config")
                .help(s.arg_no_config)
                .action(ArgAction::SetTrue)
                .conflicts_with("config"),
        )
        .arg(
            Arg::new("dry-run")
                .long("dry-run")
                .help(s.arg_dry_run)
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("verbose")
                .short('v')
                .long("verbose")
                .help(s.arg_verbose)
                .action(ArgAction::Count),
        )
        .arg(
            Arg::new("color")
                .long("color")
                .value_name(s.val_color)
                .help(s.arg_color)
                .value_parser(["auto", "always", "never"])
                .default_value("auto"),
        )
        .arg(
            Arg::new("lang")
                .short('L')
                .long("lang")
                .value_name(s.val_lang)
                .help(s.arg_lang)
                .env("NCM2MP3_LANG")
                .value_parser(["en", "zh"]),
        )
        .subcommand(
            Command::new("info")
                .about(s.cmd_info_about)
                .arg(
                    Arg::new("input")
                        .value_name(s.val_input)
                        .help(s.arg_info_input)
                        .required(true)
                        .value_parser(clap::value_parser!(PathBuf)),
                )
                .arg(
                    Arg::new("recursive")
                        .short('r')
                        .long("recursive")
                        .help(s.arg_recursive)
                        .action(ArgAction::SetTrue),
                ),
        )
        .subcommand(
            Command::new("cover")
                .about(s.cmd_cover_about)
                .arg(
                    Arg::new("input")
                        .value_name(s.val_input)
                        .help(s.arg_cover_input)
                        .required(true)
                        .value_parser(clap::value_parser!(PathBuf)),
                )
                .arg(
                    Arg::new("output")
                        .short('o')
                        .long("output")
                        .value_name(s.val_dir)
                        .help(s.arg_output)
                        .value_parser(clap::value_parser!(PathBuf)),
                )
                .arg(
                    Arg::new("recursive")
                        .short('r')
                        .long("recursive")
                        .help(s.arg_recursive)
                        .action(ArgAction::SetTrue),
                )
                .arg(
                    Arg::new("overwrite")
                        .long("overwrite")
                        .help(s.arg_overwrite)
                        .action(ArgAction::SetTrue),
                ),
        )
        .subcommand(
            Command::new("watch")
                .about(s.cmd_watch_about)
                .arg(
                    Arg::new("dir")
                        .value_name(s.val_dir)
                        .help(s.arg_watch_dir)
                        .required(true)
                        .value_parser(clap::value_parser!(PathBuf)),
                )
                .arg(
                    Arg::new("output")
                        .short('o')
                        .long("output")
                        .value_name(s.val_dir)
                        .help(s.arg_output)
                        .value_parser(clap::value_parser!(PathBuf)),
                )
                .arg(
                    Arg::new("template")
                        .short('t')
                        .long("template")
                        .value_name(s.val_template)
                        .help(s.arg_template),
                )
                .arg(
                    Arg::new("format")
                        .long("format")
                        .value_name(s.val_fmt)
                        .value_delimiter(',')
                        .help(s.arg_format)
                        .action(ArgAction::Append),
                )
                .arg(
                    Arg::new("no-tag")
                        .long("no-tag")
                        .help(s.arg_no_tag)
                        .action(ArgAction::SetTrue),
                )
                .arg(
                    Arg::new("folder")
                        .short('F')
                        .long("folder")
                        .help(s.arg_folder)
                        .action(ArgAction::SetTrue),
                )
                .arg(
                    Arg::new("on-conflict")
                        .long("on-conflict")
                        .value_name(s.val_conflict)
                        .help(s.arg_on_conflict)
                        .value_parser(["skip", "overwrite", "rename"]),
                ),
        )
        .subcommand(
            Command::new("completion")
                .about(s.cmd_completion_about)
                .arg(
                    Arg::new("shell")
                        .value_name(s.val_shell)
                        .help(s.arg_completion_shell)
                        .required(true)
                        .value_parser(clap::builder::EnumValueParser::<Shell>::new()),
                ),
        )
}

/// Dispatch parsed matches into the concrete command variant.
pub fn parse(matches: &ArgMatches, lang: Lang) -> Result<CliCommand> {
    match matches.subcommand() {
        Some(("info", sub)) => Ok(CliCommand::Info(InfoArgs {
            input: sub
                .get_one::<PathBuf>("input")
                .cloned()
                .ok_or_else(|| anyhow!("info input is required"))?,
            recursive: sub.get_flag("recursive"),
        })),
        Some(("cover", sub)) => Ok(CliCommand::Cover(CoverArgs {
            input: sub
                .get_one::<PathBuf>("input")
                .cloned()
                .ok_or_else(|| anyhow!("cover input is required"))?,
            output: sub.get_one::<PathBuf>("output").cloned(),
            recursive: sub.get_flag("recursive"),
            overwrite: sub.get_flag("overwrite"),
        })),
        Some(("watch", sub)) => {
            let format = sub
                .get_many::<String>("format")
                .map(|v| v.cloned().collect())
                .unwrap_or_default();
            let on_conflict = sub
                .get_one::<String>("on-conflict")
                .and_then(|s| ConflictStrategy::parse(s))
                .unwrap_or(ConflictStrategy::Skip);
            Ok(CliCommand::Watch(WatchArgs {
                dir: sub
                    .get_one::<PathBuf>("dir")
                    .cloned()
                    .ok_or_else(|| anyhow!("watch directory is required"))?,
                output: sub.get_one::<PathBuf>("output").cloned(),
                template: sub.get_one::<String>("template").cloned(),
                format,
                no_tag: sub.get_flag("no-tag"),
                folder: sub.get_flag("folder"),
                on_conflict,
            }))
        }
        Some(("completion", sub)) => {
            let shell = sub
                .get_one::<Shell>("shell")
                .copied()
                .ok_or_else(|| anyhow!("completion shell is required"))?;
            Ok(CliCommand::Completion(shell))
        }
        _ => Ok(CliCommand::Decrypt(cli_from_matches(matches, lang))),
    }
}

/// Convert matched args into the flat `Cli` struct used by the pipeline.
fn cli_from_matches(matches: &ArgMatches, lang: Lang) -> Cli {
    let format = matches
        .get_many::<String>("format")
        .map(|vals| vals.cloned().collect())
        .unwrap_or_default();

    // Conflict strategy: `--on-conflict` wins when set; otherwise the legacy
    // `--overwrite` flag maps to `Overwrite`; otherwise default `Skip`.
    let on_conflict = matches
        .get_one::<String>("on-conflict")
        .and_then(|s| ConflictStrategy::parse(s))
        .unwrap_or_else(|| {
            if matches.get_flag("overwrite") {
                ConflictStrategy::Overwrite
            } else {
                ConflictStrategy::Skip
            }
        });

    let exclude = matches
        .get_many::<String>("exclude")
        .map(|vals| vals.cloned().collect())
        .unwrap_or_default();

    Cli {
        input: matches.get_one::<PathBuf>("input").cloned(),
        from_file: matches.get_one::<PathBuf>("from-file").cloned(),
        output: matches.get_one::<PathBuf>("output").cloned(),
        template: matches.get_one::<String>("template").cloned(),
        recursive: matches.get_flag("recursive"),
        format,
        exclude,
        limit: matches.get_one::<usize>("limit").copied(),
        no_tag: matches.get_flag("no-tag"),
        folder: matches.get_flag("folder"),
        jobs: matches.get_one::<usize>("jobs").copied(),
        on_conflict,
        dry_run: matches.get_flag("dry-run"),
        verbose: matches.get_count("verbose"),
        color: matches
            .get_one::<String>("color")
            .and_then(|s| ColorChoice::parse(s))
            .unwrap_or(ColorChoice::Auto),
        config_path: matches.get_one::<PathBuf>("config").cloned(),
        no_config: matches.get_flag("no-config"),
        lang,
    }
}

/// Merge a [`FileConfig`] into an existing [`Cli`], respecting the
/// **command line > config file > default** precedence. Only fields that
/// weren't already set on the command line are filled in.
///
/// For clap boolean flags we can't tell "omitted" from "explicitly set to
/// false" — we use [`ArgMatches::value_source`] to distinguish. When a flag
/// is [`clap::parser::ValueSource::DefaultValue`] (i.e. the user did NOT
/// pass it), the config value wins.
pub fn merge_config(cli: &mut Cli, matches: &ArgMatches, config: &crate::config::FileConfig) {
    use clap::parser::ValueSource::CommandLine;

    fn cli_provided(matches: &ArgMatches, id: &str) -> bool {
        matches
            .value_source(id)
            .map(|s| s == CommandLine)
            .unwrap_or(false)
    }

    if !cli_provided(matches, "template") {
        if let Some(t) = &config.template {
            cli.template = Some(t.clone());
        }
    }
    if !cli_provided(matches, "output") {
        if let Some(o) = &config.output {
            cli.output = Some(o.clone());
        }
    }
    if !cli_provided(matches, "jobs") {
        if let Some(j) = config.jobs {
            cli.jobs = Some(j);
        }
    }
    if !cli_provided(matches, "folder") {
        if let Some(true) = config.folder {
            cli.folder = true;
        }
    }
    if !cli_provided(matches, "no-tag") {
        if let Some(true) = config.no_tag {
            cli.no_tag = true;
        }
    }
    if !cli_provided(matches, "recursive") {
        if let Some(true) = config.recursive {
            cli.recursive = true;
        }
    }
    if !cli_provided(matches, "on-conflict") && !cli_provided(matches, "overwrite") {
        if let Some(raw) = &config.on_conflict {
            if let Some(strategy) = ConflictStrategy::parse(raw) {
                cli.on_conflict = strategy;
            }
        }
    }
    if !cli_provided(matches, "format") {
        if let Some(fmts) = &config.format {
            cli.format = fmts.clone();
        }
    }
}