rlru 0.1.15

Rocket League replay uploader
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
use std::collections::{BTreeMap, HashSet};
use std::fs;
use std::path::Path;
use std::process::Command;
use std::time::Duration;

use anyhow::{bail, Context, Result};
pub use psynet::PlayerPlatform;
use serde::{Deserialize, Deserializer, Serialize};
use url::Url;

use crate::state_file::write_atomically;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
    pub behavior: BehaviorConfig,
    pub accounts: Vec<AccountConfig>,
    #[serde(alias = "storage")]
    pub upload_destinations: Vec<UploadDestinationConfig>,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            behavior: BehaviorConfig::default(),
            accounts: vec![AccountConfig::default()],
            upload_destinations: vec![
                UploadDestinationConfig::rocky(),
                UploadDestinationConfig::ballchasing(),
                UploadDestinationConfig::rocket_sense(),
            ],
        }
    }
}

impl Config {
    pub fn load(path: &Path) -> Result<Self> {
        let content = fs::read_to_string(path)
            .with_context(|| format!("failed to read config {}", path.display()))?;
        let config: Self = toml::from_str(&content)
            .with_context(|| format!("failed to parse TOML config {}", path.display()))?;
        config.validate()?;
        Ok(config)
    }

    pub fn load_or_default(path: &Path) -> Result<Self> {
        if path.exists() {
            Self::load(path)
        } else {
            let config = Self::default();
            config.validate()?;
            Ok(config)
        }
    }

    pub fn to_pretty_toml(&self) -> Result<String> {
        toml::to_string_pretty(self).context("failed to serialize config as TOML")
    }

    pub fn save(&self, path: &Path) -> Result<()> {
        self.validate()?;
        write_atomically(path, self.to_pretty_toml()?)
            .with_context(|| format!("failed to write config {}", path.display()))
    }

    pub fn upload_destination(&self, name: &str) -> Option<&UploadDestinationConfig> {
        self.upload_destinations
            .iter()
            .find(|target| target.name == name)
    }

    pub fn validate(&self) -> Result<()> {
        self.behavior.validate()?;

        if self.accounts.is_empty() {
            bail!("config must define at least one account");
        }

        let mut account_ids = HashSet::new();
        let mut auth_ids = HashSet::new();
        for account in &self.accounts {
            account.validate()?;
            if !account_ids.insert(account.id) {
                bail!("duplicate account id {}", account.id);
            }
            if !auth_ids.insert(account.auth_id()) {
                bail!("duplicate account auth id {}", account.auth_id());
            }
        }

        if self.upload_destinations.is_empty() {
            bail!("config must define at least one upload destination");
        }

        let mut target_names = HashSet::new();
        for target in &self.upload_destinations {
            target.validate()?;
            if !target_names.insert(target.name.as_str()) {
                bail!("duplicate upload destination {:?}", target.name);
            }
        }

        if let Some(selected) = &self.behavior.selected_account {
            if !self
                .accounts
                .iter()
                .any(|account| &account.name == selected)
            {
                bail!("selected account {selected:?} does not exist");
            }
        }

        if let Some(selected) = &self.behavior.selected_upload_destination {
            if !self
                .upload_destinations
                .iter()
                .any(|target| &target.name == selected)
            {
                bail!("selected upload destination {selected:?} does not exist");
            }
        }

        Ok(())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default, deny_unknown_fields)]
pub struct BehaviorConfig {
    pub auto_upload: bool,
    pub exit_in_tray: bool,
    pub start_in_tray: bool,
    pub upload_on_launch: bool,
    pub no_upload_while_connected: bool,
    #[serde(with = "humantime_serde")]
    pub auto_upload_interval: Duration,
    #[serde(with = "humantime_serde")]
    pub auto_upload_jitter_max: Duration,
    pub selected_account: Option<String>,
    #[serde(alias = "selected_storage")]
    pub selected_upload_destination: Option<String>,
    /// Template for the filename uploads are sent with (most destinations show
    /// this as the replay's name). Supports `{PLACEHOLDER}` tokens — see
    /// [`crate::upload_name`]. An empty string keeps the legacy match-id name.
    pub upload_name_template: String,
}

impl Default for BehaviorConfig {
    fn default() -> Self {
        Self {
            auto_upload: true,
            exit_in_tray: true,
            start_in_tray: false,
            upload_on_launch: false,
            no_upload_while_connected: true,
            auto_upload_interval: Duration::from_secs(45 * 60),
            auto_upload_jitter_max: Duration::from_secs(15 * 60),
            selected_account: None,
            selected_upload_destination: None,
            upload_name_template: crate::upload_name::DEFAULT_TEMPLATE.to_string(),
        }
    }
}

impl BehaviorConfig {
    pub fn validate(&self) -> Result<()> {
        if self.auto_upload_interval < Duration::from_secs(60) {
            bail!("auto_upload_interval must be at least 60s");
        }
        if self.auto_upload_jitter_max > self.auto_upload_interval {
            bail!("auto_upload_jitter_max cannot exceed auto_upload_interval");
        }
        if self.upload_name_template.contains(['\n', '\r', '\0']) {
            bail!("upload_name_template cannot contain control characters");
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct AccountConfig {
    pub id: u32,
    pub name: String,
    #[serde(
        default,
        rename = "profile_id",
        skip_serializing_if = "Option::is_none"
    )]
    legacy_profile_id: Option<u32>,
    pub platform: PlayerPlatform,
    #[serde(skip_serializing_if = "is_true")]
    pub sync_enabled: bool,
}

impl Default for AccountConfig {
    fn default() -> Self {
        Self::new(0, "Primary".to_string(), PlayerPlatform::Epic, true)
    }
}

impl AccountConfig {
    pub fn new(id: u32, name: String, platform: PlayerPlatform, sync_enabled: bool) -> Self {
        Self {
            id,
            name,
            legacy_profile_id: None,
            platform,
            sync_enabled,
        }
    }

    pub fn auth_id(&self) -> u32 {
        self.legacy_profile_id.unwrap_or(self.id)
    }

    pub fn legacy_profile_id(&self) -> Option<u32> {
        self.legacy_profile_id
    }

    pub fn validate(&self) -> Result<()> {
        validate_name("account name", &self.name)
    }
}

impl<'de> Deserialize<'de> for AccountConfig {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let input = AccountConfigInput::deserialize(deserializer)?;
        let sync_enabled = input
            .sync_enabled
            .unwrap_or_else(|| !input.unused.unwrap_or(false));

        Ok(Self {
            id: input.id,
            name: input.name,
            legacy_profile_id: input.legacy_profile_id,
            platform: input.platform,
            sync_enabled,
        })
    }
}

#[derive(Deserialize)]
#[serde(default, deny_unknown_fields)]
struct AccountConfigInput {
    id: u32,
    name: String,
    #[serde(rename = "profile_id")]
    legacy_profile_id: Option<u32>,
    platform: PlayerPlatform,
    sync_enabled: Option<bool>,
    unused: Option<bool>,
}

impl Default for AccountConfigInput {
    fn default() -> Self {
        Self {
            id: 0,
            name: "Primary".to_string(),
            legacy_profile_id: None,
            platform: PlayerPlatform::Epic,
            sync_enabled: None,
            unused: None,
        }
    }
}

fn is_true(value: &bool) -> bool {
    *value
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct UploadDestinationConfig {
    pub name: String,
    pub url: Url,
    #[serde(default, skip_serializing, rename = "predefined")]
    _legacy_predefined: IgnoredLegacyBool,
    #[serde(default, skip_serializing, rename = "primary")]
    _legacy_primary: IgnoredLegacyBool,
    pub query: BTreeMap<String, String>,
    pub auth: TargetAuth,
    pub ping: PingConfig,
    pub replay_upload: ReplayUploadConfig,
    pub rank_upload: RankUploadConfig,
}

impl UploadDestinationConfig {
    pub fn rocky() -> Self {
        Self {
            name: "Rocky".to_string(),
            url: Url::parse("https://lexore.ca/rocky/api").expect("valid built-in Rocky URL"),
            _legacy_predefined: IgnoredLegacyBool,
            _legacy_primary: IgnoredLegacyBool,
            query: BTreeMap::new(),
            auth: TargetAuth::None,
            ping: PingConfig {
                enabled: false,
                path: "/".to_string(),
            },
            replay_upload: ReplayUploadConfig {
                enabled: true,
                path: "/upload".to_string(),
                file_field: "file".to_string(),
                success_statuses: vec![201],
                duplicate_statuses: vec![409],
            },
            rank_upload: RankUploadConfig::None,
        }
    }

    pub fn ballchasing() -> Self {
        Self {
            name: "Ballchasing".to_string(),
            url: Url::parse("https://ballchasing.com/api").expect("valid built-in Ballchasing URL"),
            _legacy_predefined: IgnoredLegacyBool,
            _legacy_primary: IgnoredLegacyBool,
            query: BTreeMap::from([("visibility".to_string(), "public".to_string())]),
            auth: TargetAuth::None,
            ping: PingConfig {
                enabled: true,
                path: "/".to_string(),
            },
            replay_upload: ReplayUploadConfig {
                enabled: true,
                path: "/v2/upload".to_string(),
                file_field: "file".to_string(),
                success_statuses: vec![201],
                duplicate_statuses: vec![409],
            },
            rank_upload: RankUploadConfig::Endpoint {
                path: "/v1/mmr".to_string(),
            },
        }
    }

    pub fn rocket_sense() -> Self {
        Self {
            name: "Rocket Sense".to_string(),
            url: Url::parse("https://rocket-sense.duckdns.org/api/v1")
                .expect("valid built-in Rocket Sense URL"),
            _legacy_predefined: IgnoredLegacyBool,
            _legacy_primary: IgnoredLegacyBool,
            query: BTreeMap::new(),
            auth: TargetAuth::BearerEnv {
                variable: "ROCKET_SENSE_TOKEN".to_string(),
            },
            ping: PingConfig {
                enabled: true,
                path: "/health".to_string(),
            },
            replay_upload: ReplayUploadConfig {
                enabled: true,
                path: "/replays".to_string(),
                file_field: "file".to_string(),
                success_statuses: vec![201],
                duplicate_statuses: vec![200, 409],
            },
            rank_upload: rocket_sense_rank_upload(),
        }
    }

    pub fn validate(&self) -> Result<()> {
        validate_name("upload destination name", &self.name)?;
        validate_http_url(&self.url)?;
        self.auth.validate()?;
        self.ping.validate()?;
        self.replay_upload.validate()?;
        self.rank_upload.validate()?;
        Ok(())
    }

    pub fn endpoint_url(&self, path: &str) -> Result<Url> {
        self.build_endpoint_url(path, true)
    }

    /// Like [`Self::endpoint_url`] but without appending the destination's
    /// configured query parameters. Used for the MMR endpoint, which (matching
    /// the BakkesMod uploader) takes no `visibility`-style query parameters.
    pub fn endpoint_url_without_query(&self, path: &str) -> Result<Url> {
        self.build_endpoint_url(path, false)
    }

    fn build_endpoint_url(&self, path: &str, include_query: bool) -> Result<Url> {
        let mut url = self.url.clone();
        let base_path = url.path().trim_end_matches('/');
        let endpoint_path = path.trim_start_matches('/');
        url.set_path(&format!("{base_path}/{endpoint_path}"));
        if include_query && !self.query.is_empty() {
            let mut pairs = url.query_pairs_mut();
            for (key, value) in &self.query {
                pairs.append_pair(key, value);
            }
        }
        Ok(url)
    }
}

impl Default for UploadDestinationConfig {
    fn default() -> Self {
        Self::rocky()
    }
}

impl<'de> Deserialize<'de> for UploadDestinationConfig {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let input = UploadDestinationConfigInput::deserialize(deserializer)?;
        let rank_upload = input
            .rank_upload
            .unwrap_or_else(|| default_rank_upload_for_destination(&input.name, &input.url));

        Ok(Self {
            name: input.name,
            url: input.url,
            _legacy_predefined: input.legacy_predefined,
            _legacy_primary: input.legacy_primary,
            query: input.query,
            auth: input.auth,
            ping: input.ping,
            replay_upload: input.replay_upload,
            rank_upload,
        })
    }
}

#[derive(Deserialize)]
#[serde(default, deny_unknown_fields)]
struct UploadDestinationConfigInput {
    name: String,
    url: Url,
    #[serde(rename = "predefined")]
    legacy_predefined: IgnoredLegacyBool,
    #[serde(rename = "primary")]
    legacy_primary: IgnoredLegacyBool,
    query: BTreeMap<String, String>,
    auth: TargetAuth,
    ping: PingConfig,
    replay_upload: ReplayUploadConfig,
    rank_upload: Option<RankUploadConfig>,
}

impl Default for UploadDestinationConfigInput {
    fn default() -> Self {
        let default = UploadDestinationConfig::default();
        Self {
            name: default.name,
            url: default.url,
            legacy_predefined: IgnoredLegacyBool,
            legacy_primary: IgnoredLegacyBool,
            query: default.query,
            auth: default.auth,
            ping: default.ping,
            replay_upload: default.replay_upload,
            rank_upload: None,
        }
    }
}

fn is_rocket_sense_destination(name: &str, url: &Url) -> bool {
    name == "Rocket Sense"
        && url.as_str().trim_end_matches('/') == "https://rocket-sense.duckdns.org/api/v1"
}

fn is_ballchasing_destination(name: &str, url: &Url) -> bool {
    name == "Ballchasing" && url.as_str().trim_end_matches('/') == "https://ballchasing.com/api"
}

fn default_rank_upload_for_destination(name: &str, url: &Url) -> RankUploadConfig {
    if is_rocket_sense_destination(name, url) {
        rocket_sense_rank_upload()
    } else if is_ballchasing_destination(name, url) {
        RankUploadConfig::Endpoint {
            path: "/v1/mmr".to_string(),
        }
    } else {
        RankUploadConfig::None
    }
}

fn rocket_sense_rank_upload() -> RankUploadConfig {
    RankUploadConfig::Bundled {
        field: "ranks".to_string(),
    }
}

#[derive(Debug, Clone, Copy, Default, Eq)]
struct IgnoredLegacyBool;

impl PartialEq for IgnoredLegacyBool {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl<'de> Deserialize<'de> for IgnoredLegacyBool {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        bool::deserialize(deserializer)?;
        Ok(Self)
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum TargetAuth {
    #[default]
    None,
    AuthorizationHeader {
        value: String,
    },
    Bearer {
        token: String,
    },
    BearerEnv {
        variable: String,
    },
    BearerCommand {
        command: Vec<String>,
    },
}

impl TargetAuth {
    pub fn validate(&self) -> Result<()> {
        match self {
            Self::None => Ok(()),
            Self::AuthorizationHeader { value } => {
                if value.trim().is_empty() {
                    bail!("authorization header value cannot be empty");
                }
                Ok(())
            }
            Self::Bearer { token } => {
                if token.trim().is_empty() {
                    bail!("bearer token cannot be empty");
                }
                Ok(())
            }
            Self::BearerEnv { variable } => {
                validate_env_var_name("bearer token environment variable", variable)
            }
            Self::BearerCommand { command } => validate_token_command(command),
        }
    }

    pub fn header_value(&self) -> Result<Option<String>> {
        match self {
            Self::None => Ok(None),
            Self::AuthorizationHeader { value } => Ok(Some(value.clone())),
            Self::Bearer { token } => Ok(Some(format!("Bearer {token}"))),
            Self::BearerEnv { variable } => {
                let token = std::env::var(variable)
                    .with_context(|| format!("{variable} must be set for bearer auth"))?;
                bearer_header(token, variable)
            }
            Self::BearerCommand { command } => bearer_command_header(command),
        }
    }
}

fn bearer_header(token: impl AsRef<str>, source: &str) -> Result<Option<String>> {
    let token = token.as_ref().trim();
    if token.is_empty() {
        bail!("{source} did not provide a bearer token");
    }
    Ok(Some(format!("Bearer {token}")))
}

fn validate_token_command(command: &[String]) -> Result<()> {
    if command.is_empty() {
        bail!("bearer token command cannot be empty");
    }
    for part in command {
        if part.trim().is_empty() {
            bail!("bearer token command cannot contain empty arguments");
        }
    }
    Ok(())
}

fn bearer_command_header(command: &[String]) -> Result<Option<String>> {
    validate_token_command(command)?;
    let (program, args) = command.split_first().expect("validated non-empty command");
    let output = Command::new(program)
        .args(args)
        .output()
        .with_context(|| format!("failed to run bearer token command {program:?}"))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let stderr = stderr.trim();
        if stderr.is_empty() {
            bail!(
                "bearer token command {program:?} failed with {}",
                output.status
            );
        } else {
            bail!(
                "bearer token command {program:?} failed with {}: {stderr}",
                output.status
            );
        }
    }

    let token = String::from_utf8(output.stdout)
        .with_context(|| format!("bearer token command {program:?} did not output UTF-8"))?;
    bearer_header(token, "bearer token command")
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct PingConfig {
    pub enabled: bool,
    pub path: String,
}

impl Default for PingConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            path: "/".to_string(),
        }
    }
}

impl PingConfig {
    pub fn validate(&self) -> Result<()> {
        validate_endpoint_path("ping.path", &self.path)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct ReplayUploadConfig {
    pub enabled: bool,
    pub path: String,
    pub file_field: String,
    pub success_statuses: Vec<u16>,
    pub duplicate_statuses: Vec<u16>,
}

impl Default for ReplayUploadConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            path: "/upload".to_string(),
            file_field: "file".to_string(),
            success_statuses: vec![201],
            duplicate_statuses: vec![409],
        }
    }
}

impl ReplayUploadConfig {
    pub fn validate(&self) -> Result<()> {
        validate_endpoint_path("replay_upload.path", &self.path)?;
        validate_name("replay_upload.file_field", &self.file_field)?;
        validate_statuses("replay_upload.success_statuses", &self.success_statuses)?;
        validate_statuses("replay_upload.duplicate_statuses", &self.duplicate_statuses)?;
        Ok(())
    }
}

/// How a destination accepts per-match player rank metadata.
///
/// Replay files do not carry ranks, so — mirroring the BakkesMod
/// AutoReplayUploader plugin — the uploader submits them out of band, either as
/// a separate POST to a ballchasing-style MMR endpoint or bundled into the
/// replay upload as a multipart field (the richer Rocket Sense payload). Off by
/// default; the built-in Ballchasing and Rocket Sense destinations enable it.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "mode", rename_all = "snake_case")]
pub enum RankUploadConfig {
    /// No rank metadata is sent.
    #[default]
    None,
    /// Posted as a separate request to a ballchasing-style MMR endpoint, using
    /// the BakkesMod-shaped JSON payload.
    Endpoint { path: String },
    /// Included as a multipart field in the replay upload, using the richer
    /// Rocket Sense rank payload (full before/after skill snapshot).
    Bundled { field: String },
}

impl RankUploadConfig {
    pub fn validate(&self) -> Result<()> {
        match self {
            Self::None => Ok(()),
            Self::Endpoint { path } => validate_endpoint_path("rank_upload.path", path),
            Self::Bundled { field } => validate_name("rank_upload.field", field),
        }
    }
}

fn validate_name(label: &str, value: &str) -> Result<()> {
    if value.trim().is_empty() {
        bail!("{label} cannot be empty");
    }
    if value.contains(['\n', '\r', '\0']) {
        bail!("{label} cannot contain control characters");
    }
    Ok(())
}

fn validate_env_var_name(label: &str, value: &str) -> Result<()> {
    validate_name(label, value)?;
    let mut chars = value.chars();
    let Some(first) = chars.next() else {
        bail!("{label} cannot be empty");
    };
    if !(first == '_' || first.is_ascii_alphabetic()) {
        bail!("{label} must start with an ASCII letter or underscore");
    }
    if !chars.all(|ch| ch == '_' || ch.is_ascii_alphanumeric()) {
        bail!("{label} must contain only ASCII letters, digits, and underscores");
    }
    Ok(())
}

fn validate_http_url(url: &Url) -> Result<()> {
    match url.scheme() {
        "http" | "https" => Ok(()),
        scheme => bail!("upload destination URL must use http or https, got {scheme:?}"),
    }
}

fn validate_endpoint_path(label: &str, value: &str) -> Result<()> {
    if !value.starts_with('/') {
        bail!("{label} must start with /");
    }
    if value.contains(['\n', '\r', '\0']) {
        bail!("{label} cannot contain control characters");
    }
    Ok(())
}

fn validate_statuses(label: &str, values: &[u16]) -> Result<()> {
    if values.is_empty() {
        bail!("{label} cannot be empty");
    }
    for value in values {
        if !(100..=599).contains(value) {
            bail!("{label} contains invalid HTTP status {value}");
        }
    }
    Ok(())
}

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

    #[test]
    fn default_config_round_trips_as_toml() {
        let config = Config::default();
        config.validate().unwrap();

        let toml = config.to_pretty_toml().unwrap();
        let parsed: Config = toml::from_str(&toml).unwrap();

        assert_eq!(parsed, config);
    }

    #[test]
    fn empty_upload_name_template_is_allowed_as_opt_out() {
        let mut config = Config::default();
        config.behavior.upload_name_template = String::new();

        config.validate().unwrap();
    }

    #[test]
    fn rejects_upload_name_template_with_control_characters() {
        let mut config = Config::default();
        config.behavior.upload_name_template = "{PLAYER}\n{MODE}".to_string();

        let err = config.validate().unwrap_err();

        assert!(err.to_string().contains("upload_name_template"));
    }

    #[test]
    fn rejects_unknown_toml_fields() {
        let err = toml::from_str::<Config>("surprise = true").unwrap_err();

        assert!(err.to_string().contains("unknown field"));
    }

    #[test]
    fn rejects_duplicate_upload_destination_names() {
        let mut config = Config::default();
        config
            .upload_destinations
            .push(UploadDestinationConfig::rocky());

        let err = config.validate().unwrap_err();

        assert!(err.to_string().contains("duplicate upload destination"));
    }

    #[test]
    fn accepts_legacy_storage_field_names() {
        let mut config = Config::default();
        config.behavior.selected_upload_destination = Some("Rocket Sense".to_string());
        let toml = config.to_pretty_toml().unwrap();
        let legacy_toml = toml
            .replace("selected_upload_destination", "selected_storage")
            .replace("upload_destinations", "storage");

        let parsed: Config = toml::from_str(&legacy_toml).unwrap();

        assert_eq!(parsed, config);
    }

    #[test]
    fn accepts_legacy_upload_destination_badge_fields_without_reserializing_them() {
        let config = Config::default();
        let toml = config.to_pretty_toml().unwrap();
        let legacy_toml = toml.replacen(
            "query = {}",
            "predefined = true\nprimary = true\nquery = {}",
            1,
        );

        let parsed: Config = toml::from_str(&legacy_toml).unwrap();
        let serialized = parsed.to_pretty_toml().unwrap();

        assert_eq!(parsed, config);
        assert!(!serialized.contains("predefined ="));
        assert!(!serialized.contains("primary ="));
    }

    #[test]
    fn rocket_sense_uses_bundled_rank_upload_when_omitted() {
        let toml = r#"
[[upload_destinations]]
name = "Rocket Sense"
url = "https://rocket-sense.duckdns.org/api/v1"

[upload_destinations.query]

[upload_destinations.auth]
kind = "none"

[upload_destinations.ping]
enabled = true
path = "/health"

[upload_destinations.replay_upload]
enabled = true
path = "/replays"
file_field = "file"
success_statuses = [201]
duplicate_statuses = [200, 409]
"#;

        let config: Config = toml::from_str(toml).unwrap();

        assert_eq!(
            config.upload_destinations[0].rank_upload,
            RankUploadConfig::Bundled {
                field: "ranks".to_string()
            }
        );
    }

    #[test]
    fn ballchasing_uses_endpoint_rank_upload_when_omitted() {
        let toml = r#"
[[upload_destinations]]
name = "Ballchasing"
url = "https://ballchasing.com/api"

[upload_destinations.query]
visibility = "public"

[upload_destinations.auth]
kind = "none"

[upload_destinations.ping]
enabled = true
path = "/"

[upload_destinations.replay_upload]
enabled = true
path = "/v2/upload"
file_field = "file"
success_statuses = [201]
duplicate_statuses = [409]
"#;

        let config: Config = toml::from_str(toml).unwrap();

        assert_eq!(
            config.upload_destinations[0].rank_upload,
            RankUploadConfig::Endpoint {
                path: "/v1/mmr".to_string()
            }
        );
    }

    #[test]
    fn rocket_sense_can_explicitly_disable_rank_upload() {
        let toml = Config::default()
            .to_pretty_toml()
            .unwrap()
            .replace("mode = \"bundled\"\nfield = \"ranks\"", "mode = \"none\"");

        let config: Config = toml::from_str(&toml).unwrap();
        let target = config.upload_destination("Rocket Sense").unwrap();

        assert_eq!(target.rank_upload, RankUploadConfig::None);
    }

    #[test]
    fn custom_destinations_do_not_enable_rank_upload_when_omitted() {
        let toml = r#"
[[upload_destinations]]
name = "Custom"
url = "https://example.com/api"
"#;

        let config: Config = toml::from_str(toml).unwrap();

        assert_eq!(
            config.upload_destinations[0].rank_upload,
            RankUploadConfig::None
        );
    }

    #[test]
    fn default_accounts_do_not_serialize_profile_ids() {
        let toml = Config::default().to_pretty_toml().unwrap();

        assert!(!toml.contains("profile_id"));
    }

    #[test]
    fn accepts_legacy_account_profile_id_as_auth_id() {
        let toml = Config::default().to_pretty_toml().unwrap();
        let legacy_toml = toml.replacen("id = 0", "id = 42\nprofile_id = 7", 1);

        let parsed: Config = toml::from_str(&legacy_toml).unwrap();

        assert_eq!(parsed.accounts[0].id, 42);
        assert_eq!(parsed.accounts[0].auth_id(), 7);
        assert!(parsed.to_pretty_toml().unwrap().contains("profile_id = 7"));
    }

    #[test]
    fn accepts_legacy_unused_account_field_as_sync_disabled() {
        let toml = Config::default().to_pretty_toml().unwrap();
        let legacy_toml = toml.replacen(
            "platform = \"epic\"",
            "platform = \"epic\"\nunused = true",
            1,
        );

        let parsed: Config = toml::from_str(&legacy_toml).unwrap();
        let serialized = parsed.to_pretty_toml().unwrap();

        assert!(!parsed.accounts[0].sync_enabled);
        assert!(serialized.contains("sync_enabled = false"));
        assert!(!serialized.contains("unused ="));
    }

    #[test]
    fn bearer_command_reads_token_from_stdout() {
        let auth = TargetAuth::BearerCommand {
            command: vec!["printf".to_string(), "token-from-command\n".to_string()],
        };

        assert_eq!(
            auth.header_value().unwrap(),
            Some("Bearer token-from-command".to_string())
        );
    }

    #[test]
    fn bearer_command_rejects_empty_stdout() {
        let auth = TargetAuth::BearerCommand {
            command: vec!["true".to_string()],
        };

        assert!(auth
            .header_value()
            .unwrap_err()
            .to_string()
            .contains("did not provide a bearer token"));
    }

    #[test]
    fn endpoint_url_keeps_base_path_and_query() {
        let target = UploadDestinationConfig::ballchasing();

        let url = target.endpoint_url(&target.replay_upload.path).unwrap();

        assert_eq!(
            url.as_str(),
            "https://ballchasing.com/api/v2/upload?visibility=public"
        );
    }

    #[test]
    fn ballchasing_uses_mmr_endpoint_without_query() {
        let target = UploadDestinationConfig::ballchasing();

        let RankUploadConfig::Endpoint { path } = &target.rank_upload else {
            panic!("ballchasing should use an MMR endpoint");
        };
        let url = target.endpoint_url_without_query(path).unwrap();
        assert_eq!(url.as_str(), "https://ballchasing.com/api/v1/mmr");
    }

    #[test]
    fn rocket_sense_bundles_ranks_with_upload() {
        assert_eq!(
            UploadDestinationConfig::rocket_sense().rank_upload,
            RankUploadConfig::Bundled {
                field: "ranks".to_string()
            }
        );
    }

    #[test]
    fn rocky_rank_upload_is_disabled_by_default() {
        assert_eq!(
            UploadDestinationConfig::rocky().rank_upload,
            RankUploadConfig::None
        );
    }

    #[test]
    fn rocket_sense_defaults_to_local_api_upload() {
        let target = UploadDestinationConfig::rocket_sense();

        assert_eq!(
            target
                .endpoint_url(&target.replay_upload.path)
                .unwrap()
                .as_str(),
            "https://rocket-sense.duckdns.org/api/v1/replays"
        );
        assert_eq!(
            target.endpoint_url(&target.ping.path).unwrap().as_str(),
            "https://rocket-sense.duckdns.org/api/v1/health"
        );
        assert_eq!(
            target.auth,
            TargetAuth::BearerEnv {
                variable: "ROCKET_SENSE_TOKEN".to_string()
            }
        );
        assert_eq!(target.replay_upload.duplicate_statuses, vec![200, 409]);
    }
}