direct_play_nice 0.1.0-alpha.7

CLI program that converts video files to direct-play-compatible formats.
Documentation
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
use anyhow::{anyhow, bail, Context, Result};
use log::{debug, info, warn};
use std::env;
use std::ffi::CString;
use std::path::{Path, PathBuf};

#[cfg(test)]
mod servarr_tests;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IntegrationKind {
    Sonarr,
    Radarr,
}

impl IntegrationKind {
    fn label(self) -> &'static str {
        match self {
            IntegrationKind::Sonarr => "Sonarr",
            IntegrationKind::Radarr => "Radarr",
        }
    }

    fn episode_path_var(self) -> &'static str {
        match self {
            IntegrationKind::Sonarr => "sonarr_episodefile_path",
            IntegrationKind::Radarr => "radarr_moviefile_path",
        }
    }

    fn title_var(self) -> &'static str {
        match self {
            IntegrationKind::Sonarr => "sonarr_series_title",
            IntegrationKind::Radarr => "radarr_movie_title",
        }
    }

    fn is_upgrade_var(self) -> &'static str {
        match self {
            IntegrationKind::Sonarr => "sonarr_isupgrade",
            IntegrationKind::Radarr => "radarr_isupgrade",
        }
    }
}

#[derive(Debug, Clone)]
pub struct ReplacePlan {
    pub kind: IntegrationKind,
    pub event_type: String,
    pub display_name: Option<String>,
    pub is_upgrade: Option<bool>,
    pub input_path: PathBuf,
    pub final_output_path: PathBuf,
    pub temp_output_path: PathBuf,
    pub backup_path: PathBuf,
    pub input_cstring: CString,
    pub temp_output_cstring: CString,
}

impl ReplacePlan {
    pub fn assign_to_args(
        &self,
        input_slot: &mut Option<CString>,
        output_slot: &mut Option<CString>,
    ) {
        if input_slot.is_none() {
            *input_slot = Some(self.input_cstring.clone());
        }
        if output_slot.is_none() {
            *output_slot = Some(self.temp_output_cstring.clone());
        }
    }

    pub fn log_summary(&self) {
        let title = self.display_name.as_deref().unwrap_or_else(|| {
            self.input_path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("<unknown>")
        });
        let final_display = self
            .final_output_path
            .file_name()
            .and_then(|n| n.to_str())
            .map(|s| s.to_owned())
            .unwrap_or_else(|| self.final_output_path.to_string_lossy().into_owned());

        if self.final_output_path == self.input_path {
            info!(
                "{} {} event: converting '{}' in place",
                self.kind.label(),
                self.event_type,
                title
            );
        } else {
            info!(
                "{} {} event: converting '{}' -> '{}'",
                self.kind.label(),
                self.event_type,
                title,
                final_display
            );
        }
        if let Some(upgrade) = self.is_upgrade {
            info!("{} reported upgrade flag: {}", self.kind.label(), upgrade);
        }
    }

    pub fn finalize_success(self) -> Result<PathBuf> {
        use std::fs;

        let had_original = self.input_path.exists();

        // Move the original file aside
        if had_original {
            fs::rename(&self.input_path, &self.backup_path).with_context(|| {
                format!(
                    "{} integration failed to move original file '{}' to backup '{}'",
                    self.kind.label(),
                    self.input_path.display(),
                    self.backup_path.display()
                )
            })?;
        }

        // Promote the converted temp file into place
        if let Err(promote_err) = fs::rename(&self.temp_output_path, &self.final_output_path) {
            if had_original && self.backup_path.exists() && !self.input_path.exists() {
                if let Err(restore_err) = fs::rename(&self.backup_path, &self.input_path) {
                    return Err(promote_err).with_context(|| {
                        format!(
                            "{} integration could not promote '{}' to '{}' and failed to restore backup '{}': {}",
                            self.kind.label(),
                            self.temp_output_path.display(),
                            self.final_output_path.display(),
                            self.input_path.display(),
                            restore_err
                        )
                    });
                }
            }
            return Err(promote_err).with_context(|| {
                format!(
                    "{} integration could not promote '{}' to '{}'",
                    self.kind.label(),
                    self.temp_output_path.display(),
                    self.final_output_path.display()
                )
            });
        }

        match fs::remove_file(&self.backup_path) {
            Ok(_) => {}
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
            Err(err) => {
                warn!(
                    "{} integration left a backup file at '{}': {}",
                    self.kind.label(),
                    self.backup_path.display(),
                    err
                );
            }
        }

        Ok(self.final_output_path)
    }

    pub fn abort_on_failure(&self) -> Result<()> {
        use std::fs;

        if self.temp_output_path.exists() {
            fs::remove_file(&self.temp_output_path).with_context(|| {
                format!(
                    "{} integration failed to remove temporary file '{}'",
                    self.kind.label(),
                    self.temp_output_path.display()
                )
            })?;
        }

        if self.backup_path.exists() && !self.input_path.exists() {
            fs::rename(&self.backup_path, &self.input_path).with_context(|| {
                format!(
                    "{} integration could not restore backup '{}' to '{}'",
                    self.kind.label(),
                    self.backup_path.display(),
                    self.input_path.display()
                )
            })?;
        }

        Ok(())
    }
}

#[derive(Debug, Clone, Copy)]
pub struct ArgsView<'a> {
    pub has_input: bool,
    pub has_output: bool,
    pub desired_extension: &'a str,
    pub desired_suffix: &'a str,
}

#[derive(Debug, Clone)]
pub enum IntegrationPreparation {
    None,
    Skip { reason: String },
    Replace(ReplacePlan),
    Batch(Vec<ReplacePlan>),
}

pub fn prepare_from_env(view: ArgsView<'_>) -> Result<IntegrationPreparation> {
    if let Some(event) = env::var("sonarr_eventtype").ok().filter(|v| !v.is_empty()) {
        return handle_event(IntegrationKind::Sonarr, event, view);
    }

    if let Some(event) = env::var("radarr_eventtype").ok().filter(|v| !v.is_empty()) {
        return handle_event(IntegrationKind::Radarr, event, view);
    }

    Ok(IntegrationPreparation::None)
}

fn handle_event(
    kind: IntegrationKind,
    event_type: String,
    view: ArgsView<'_>,
) -> Result<IntegrationPreparation> {
    match event_type.as_str() {
        "Download" => prepare_download(kind, event_type, view),
        "Test" => Ok(IntegrationPreparation::Skip {
            reason: format!(
                "{} test event detected; exiting without conversion.",
                kind.label()
            ),
        }),
        other => Ok(IntegrationPreparation::Skip {
            reason: format!(
                "{} event '{}' does not trigger conversion; exiting cleanly.",
                kind.label(),
                other
            ),
        }),
    }
}

fn prepare_download(
    kind: IntegrationKind,
    event_type: String,
    view: ArgsView<'_>,
) -> Result<IntegrationPreparation> {
    crate::logging::log_relevant_env(kind);

    if view.has_input && view.has_output {
        // User supplied explicit paths; allow normal CLI behaviour.
        info!(
            "{} Download event detected but CLI input/output were provided; using CLI paths.",
            kind.label()
        );
        return Ok(IntegrationPreparation::None);
    }

    if view.has_input ^ view.has_output {
        bail!(
            "Detected {} Download event but only one of <INPUT_FILE>/<OUTPUT_FILE> was provided. Provide both or rely on integration defaults.",
            kind.label()
        );
    }

    if view.has_input {
        return Ok(IntegrationPreparation::None);
    }

    let input_paths = resolve_media_paths(kind).with_context(|| {
        format!(
            "{} integration requires ${} to be set for Download events.",
            kind.label(),
            kind.episode_path_var()
        )
    })?;

    if input_paths.is_empty() {
        bail!(
            "{} integration did not receive any media file paths.",
            kind.label()
        );
    }

    let effective_suffix = if view.desired_suffix.trim().is_empty() {
        match kind {
            IntegrationKind::Sonarr => ".fixed",
            IntegrationKind::Radarr => "",
        }
    } else {
        view.desired_suffix
    };

    let display_name = get_env_ignore_case(kind.title_var());
    let is_upgrade = get_env_ignore_case(kind.is_upgrade_var()).and_then(parse_boolish);

    let mut plans = Vec::new();

    for input_path in input_paths {
        if !input_path.exists() {
            bail!(
                "{} integration could not find media file at '{}'.",
                kind.label(),
                input_path.display()
            );
        }

        let final_output_path =
            resolve_output_path(&input_path, view.desired_extension, effective_suffix)?;
        let temp_output_path = append_suffix(&final_output_path, ".direct-play-nice.tmp");
        let backup_path = append_suffix(&input_path, ".direct-play-nice.bak");

        let input_cstring = path_to_cstring(&input_path)?;
        let temp_output_cstring = path_to_cstring(&temp_output_path)?;

        let plan = ReplacePlan {
            kind,
            event_type: event_type.clone(),
            display_name: display_name.clone(),
            is_upgrade,
            input_path,
            final_output_path,
            temp_output_path,
            backup_path,
            input_cstring,
            temp_output_cstring,
        };
        plan.log_summary();
        plans.push(plan);
    }

    if plans.len() == 1 {
        Ok(IntegrationPreparation::Replace(plans.remove(0)))
    } else {
        Ok(IntegrationPreparation::Batch(plans))
    }
}

fn resolve_output_path(
    input_path: &Path,
    desired_ext: &str,
    desired_suffix: &str,
) -> Result<PathBuf> {
    let parent = input_path.parent();
    let stem = input_path
        .file_stem()
        .and_then(|s| s.to_str())
        .ok_or_else(|| {
            anyhow!(
                "Input file name is not valid UTF-8: {}",
                input_path.display()
            )
        })?;

    let suffix = normalize_suffix(desired_suffix);

    let final_extension = if desired_ext.eq_ignore_ascii_case("match-input")
        || desired_ext.eq_ignore_ascii_case("same")
    {
        input_path
            .extension()
            .and_then(|ext| ext.to_str())
            .map(|s| s.to_string())
            .unwrap_or_default()
    } else {
        let trimmed = desired_ext.trim().trim_start_matches('.');
        if trimmed.is_empty() {
            bail!(
                "Invalid --servarr-output-extension '{}': must not be empty.",
                desired_ext
            );
        }
        trimmed.to_string()
    };

    let mut filename = String::from(stem);
    if let Some(sfx) = suffix.as_ref() {
        filename.push_str(sfx);
    }
    if !final_extension.is_empty() {
        filename.push('.');
        filename.push_str(&final_extension);
    }

    let new_path = match parent {
        Some(dir) => dir.join(filename),
        None => PathBuf::from(filename),
    };

    Ok(new_path)
}

fn normalize_suffix(raw: &str) -> Option<String> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return None;
    }
    if trimmed.starts_with('.') {
        Some(trimmed.to_string())
    } else {
        Some(format!(".{}", trimmed))
    }
}

fn append_suffix(path: &Path, suffix: &str) -> PathBuf {
    let parent = path.parent();
    let filename = path
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| String::from("file"));

    let new_name = match filename.rfind('.') {
        Some(idx) => {
            let (stem, ext) = filename.split_at(idx);
            format!("{}{}{}", stem, suffix, ext)
        }
        None => format!("{}{}", filename, suffix),
    };

    match parent {
        Some(dir) => dir.join(new_name),
        None => PathBuf::from(new_name),
    }
}

fn resolve_media_paths(kind: IntegrationKind) -> Result<Vec<PathBuf>> {
    let env_snapshot = crate::logging::collect_relevant_env(kind);

    if let Some(paths) = match kind {
        IntegrationKind::Sonarr => {
            get_env_paths(&["sonarr_episodefile_path", "sonarr_episodefile_paths"])
        }
        IntegrationKind::Radarr => {
            get_env_paths(&["radarr_moviefile_path", "radarr_moviefile_paths"])
        }
    } {
        if !paths.is_empty() {
            return Ok(paths.into_iter().map(PathBuf::from).collect());
        }
    }

    match kind {
        IntegrationKind::Sonarr => {
            let series = first_non_empty(&[
                "sonarr_series_path",
                "sonarr_destinationfolder",
                "sonarr_destinationpath",
            ]);
            let relative = get_env_paths(&[
                "sonarr_episodefile_relativepath",
                "sonarr_episodefile_relativepaths",
            ]);
            let source_folder =
                first_non_empty(&["sonarr_episodefile_sourcefolder", "sonarr_sourcefolder"]);
            let source_path =
                get_env_paths(&["sonarr_episodefile_sourcepath", "sonarr_sourcepath"]);

            if let (Some(series), Some(rel_list)) = (series.as_deref(), relative.clone()) {
                let mut joined = Vec::new();
                for rel in rel_list {
                    if !series.trim().is_empty() && !rel.trim().is_empty() {
                        let candidate = Path::new(series).join(&rel);
                        debug!(
                            "Sonarr fallback path resolved via series/relative: {} + {}",
                            series, rel
                        );
                        joined.push(candidate);
                    }
                }
                if !joined.is_empty() {
                    return Ok(joined);
                }
            }

            if let (Some(series), Some(source_list)) = (series.as_deref(), source_path.clone()) {
                let mut joined = Vec::new();
                for source in source_list {
                    if !series.trim().is_empty() && !source.trim().is_empty() {
                        if let Some(file_name) = Path::new(&source).file_name() {
                            let candidate = Path::new(series).join(file_name);
                            debug!(
                                "Sonarr fallback path resolved via series/source file: {} + {:?}",
                                series, file_name
                            );
                            joined.push(candidate);
                        }
                    }
                }
                if !joined.is_empty() {
                    return Ok(joined);
                }
            }

            if let (Some(folder), Some(rel_list)) = (source_folder.as_deref(), relative.clone()) {
                let mut joined = Vec::new();
                for rel in rel_list {
                    if !folder.trim().is_empty() && !rel.trim().is_empty() {
                        let candidate = Path::new(folder).join(&rel);
                        debug!(
                            "Sonarr fallback path resolved via source folder/relative: {} + {}",
                            folder, rel
                        );
                        joined.push(candidate);
                    }
                }
                if !joined.is_empty() {
                    return Ok(joined);
                }
            }

            if let (Some(folder), Some(source_list)) =
                (source_folder.as_deref(), source_path.clone())
            {
                let mut joined = Vec::new();
                for source in source_list {
                    if !folder.trim().is_empty() && !source.trim().is_empty() {
                        if let Some(file_name) = Path::new(&source).file_name() {
                            let candidate = Path::new(folder).join(file_name);
                            debug!(
                                "Sonarr fallback path resolved via source folder/file: {} + {:?}",
                                folder, file_name
                            );
                            joined.push(candidate);
                        }
                    }
                }
                if !joined.is_empty() {
                    return Ok(joined);
                }
            }

            if let Some(source_list) = source_path {
                let mut collected = Vec::new();
                for source in source_list {
                    if !source.trim().is_empty() {
                        debug!("Sonarr fallback path resolved via source path: {}", source);
                        collected.push(PathBuf::from(source));
                    }
                }
                if !collected.is_empty() {
                    return Ok(collected);
                }
            }

            Err(anyhow!(
                "sonarr_episodefile_path and fallback variables are unavailable. Observed env: {}",
                format_env_snapshot(&env_snapshot)
            ))
        }
        IntegrationKind::Radarr => {
            let movie = first_non_empty(&[
                "radarr_movie_path",
                "radarr_destinationfolder",
                "radarr_destinationpath",
            ]);
            let relative = get_env_paths(&[
                "radarr_moviefile_relativepath",
                "radarr_moviefile_relativepaths",
            ]);
            let source_folder =
                first_non_empty(&["radarr_moviefile_sourcefolder", "radarr_sourcefolder"]);
            let source_path = get_env_paths(&["radarr_moviefile_sourcepath", "radarr_sourcepath"]);

            if let (Some(movie), Some(rel_list)) = (movie.as_deref(), relative.clone()) {
                let mut joined = Vec::new();
                for rel in rel_list {
                    if !movie.trim().is_empty() && !rel.trim().is_empty() {
                        let candidate = Path::new(movie).join(&rel);
                        debug!(
                            "Radarr fallback path resolved via movie/relative: {} + {}",
                            movie, rel
                        );
                        joined.push(candidate);
                    }
                }
                if !joined.is_empty() {
                    return Ok(joined);
                }
            }

            if let (Some(movie), Some(source_list)) = (movie.as_deref(), source_path.clone()) {
                let mut joined = Vec::new();
                for source in source_list {
                    if !movie.trim().is_empty() && !source.trim().is_empty() {
                        if let Some(file_name) = Path::new(&source).file_name() {
                            let candidate = Path::new(movie).join(file_name);
                            debug!(
                                "Radarr fallback path resolved via movie/source file: {} + {:?}",
                                movie, file_name
                            );
                            joined.push(candidate);
                        }
                    }
                }
                if !joined.is_empty() {
                    return Ok(joined);
                }
            }

            if let (Some(folder), Some(rel_list)) = (source_folder.as_deref(), relative.clone()) {
                let mut joined = Vec::new();
                for rel in rel_list {
                    if !folder.trim().is_empty() && !rel.trim().is_empty() {
                        let candidate = Path::new(folder).join(&rel);
                        debug!(
                            "Radarr fallback path resolved via source folder/relative: {} + {}",
                            folder, rel
                        );
                        joined.push(candidate);
                    }
                }
                if !joined.is_empty() {
                    return Ok(joined);
                }
            }

            if let (Some(folder), Some(source_list)) =
                (source_folder.as_deref(), source_path.clone())
            {
                let mut joined = Vec::new();
                for source in source_list {
                    if !folder.trim().is_empty() && !source.trim().is_empty() {
                        if let Some(file_name) = Path::new(&source).file_name() {
                            let candidate = Path::new(folder).join(file_name);
                            debug!(
                                "Radarr fallback path resolved via source folder/file: {} + {:?}",
                                folder, file_name
                            );
                            joined.push(candidate);
                        }
                    }
                }
                if !joined.is_empty() {
                    return Ok(joined);
                }
            }

            if let Some(source_list) = source_path {
                let mut collected = Vec::new();
                for source in source_list {
                    if !source.trim().is_empty() {
                        debug!("Radarr fallback path resolved via source path: {}", source);
                        collected.push(PathBuf::from(source));
                    }
                }
                if !collected.is_empty() {
                    return Ok(collected);
                }
            }

            Err(anyhow!(
                "radarr_moviefile_path and fallback variables are unavailable. Observed env: {}",
                format_env_snapshot(&env_snapshot)
            ))
        }
    }
}

fn path_to_cstring(path: &Path) -> Result<CString> {
    let path_str = path
        .to_str()
        .ok_or_else(|| anyhow!("Path contains invalid UTF-8: {}", path.display()))?;
    CString::new(path_str.as_bytes()).context("Failed to convert path to CString")
}

fn parse_boolish(value: String) -> Option<bool> {
    match value.to_ascii_lowercase().as_str() {
        "true" | "1" | "yes" | "y" => Some(true),
        "false" | "0" | "no" | "n" => Some(false),
        _ => None,
    }
}

fn get_env_ignore_case(key: &str) -> Option<String> {
    if let Ok(val) = env::var(key) {
        return Some(val);
    }

    let target = key.to_ascii_lowercase();
    for (k, v) in env::vars() {
        if k.to_ascii_lowercase() == target {
            return Some(v);
        }
    }
    None
}

fn format_env_snapshot(entries: &[(String, String)]) -> String {
    if entries.is_empty() {
        return "<none>".to_string();
    }

    entries
        .iter()
        .map(|(k, v)| format!("{}={}", k, v))
        .collect::<Vec<_>>()
        .join(", ")
}

fn first_non_empty(keys: &[&str]) -> Option<String> {
    for key in keys {
        if let Some(val) = get_env_ignore_case(key) {
            let trimmed = val.trim();
            if !trimmed.is_empty() {
                return Some(trimmed.to_string());
            }
        }
    }
    None
}

fn get_env_paths(keys: &[&str]) -> Option<Vec<String>> {
    for key in keys {
        if let Some(val) = get_env_ignore_case(key) {
            let mut entries = Vec::new();
            for part in val.split('|') {
                let trimmed = part.trim();
                if !trimmed.is_empty() {
                    entries.push(trimmed.to_string());
                }
            }
            if !entries.is_empty() {
                return Some(entries);
            }
        }
    }
    None
}