opentalk_controller_settings/
lib.rs

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
// SPDX-FileCopyrightText: OpenTalk GmbH <mail@opentalk.eu>
//
// SPDX-License-Identifier: EUPL-1.2

//! Contains the application settings.
//!
//! The application settings are set with a TOML config file. Settings specified in the config file
//! can be overwritten by environment variables. To do so, set an environment variable
//! with the prefix `OPENTALK_CTRL_` followed by the field names you want to set. Nested fields are separated by two underscores `__`.
//! ```sh
//! OPENTALK_CTRL_<field>__<field-of-field>...
//! ```
//!
//! # Example
//!
//! set the `database.url` field:
//! ```sh
//! OPENTALK_CTRL_DATABASE__URL=postgres://postgres:password123@localhost:5432/opentalk
//! ```
//!
//! So the field 'database.max_connections' would resolve to:
//! ```sh
//! OPENTALK_CTRL_DATABASE__MAX_CONNECTIONS=5
//! ```
//!
//! # Note
//!
//! Fields set via environment variables do not affect the underlying config file.
//!
//! # Implementation Details:
//!
//! Setting categories, in which all properties implement a default value, should also implement the [`Default`] trait.

use std::{
    collections::{BTreeSet, HashMap},
    convert::TryFrom,
    path::PathBuf,
    sync::Arc,
    time::Duration,
};

use arc_swap::ArcSwap;
use config::{Config, Environment, File, FileFormat};
use openidconnect::{ClientId, ClientSecret};
use opentalk_types_common::{features::ModuleFeatureId, users::Language};
use rustc_hash::FxHashSet;
use serde::{Deserialize, Deserializer};
use snafu::{ResultExt, Snafu};
use url::Url;

#[derive(Debug, Snafu)]
pub enum SettingsError {
    #[snafu(display("Failed to read data as config: {}", source), context(false))]
    BuildConfig { source: config::ConfigError },

    #[snafu(display("Failed to apply configuration from {} or environment", file_name))]
    DeserializeConfig {
        file_name: String,
        #[snafu(source(from(serde_path_to_error::Error<config::ConfigError>, Box::new)))]
        source: Box<serde_path_to_error::Error<config::ConfigError>>,
    },

    #[snafu(display("Given base URL is not a base: {}", url))]
    NotBaseUrl { url: Url },

    #[snafu(display("Inconsistent configuration for OIDC and user search, check [keycloak], [endpoints], [oidc] and [user_search] sections"))]
    InconsistentOidcAndUserSearchConfig,
}

type Result<T, E = SettingsError> = std::result::Result<T, E>;

pub type SharedSettings = Arc<ArcSwap<Settings>>;

#[derive(Debug, Clone, Deserialize)]
pub struct Settings {
    pub database: Database,
    #[serde(default)]
    pub keycloak: Option<Keycloak>,
    #[serde(default)]
    pub oidc: Option<Oidc>,
    #[serde(default)]
    pub user_search: Option<UserSearch>,
    pub http: Http,
    #[serde(default)]
    pub turn: Option<Turn>,
    #[serde(default)]
    pub stun: Option<Stun>,
    #[serde(default)]
    pub redis: Option<RedisConfig>,
    #[serde(default)]
    pub rabbit_mq: RabbitMqConfig,
    #[serde(default)]
    pub logging: Logging,
    #[serde(default)]
    pub authz: Authz,
    #[serde(default)]
    pub avatar: Avatar,
    #[serde(default)]
    pub metrics: Metrics,

    #[serde(default)]
    pub etcd: Option<Etcd>,

    #[serde(default)]
    pub etherpad: Option<Etherpad>,

    #[serde(default)]
    pub spacedeck: Option<Spacedeck>,

    #[serde(default)]
    pub reports: Option<Reports>,

    #[serde(default)]
    pub shared_folder: Option<SharedFolder>,

    #[serde(default)]
    pub call_in: Option<CallIn>,

    #[serde(default)]
    pub defaults: Defaults,

    #[serde(default)]
    pub endpoints: Endpoints,

    pub minio: MinIO,

    #[serde(default)]
    pub tenants: Tenants,

    #[serde(default)]
    pub tariffs: Tariffs,

    pub livekit: LiveKitSettings,

    #[serde(flatten)]
    pub extensions: HashMap<String, config::Value>,
}

#[derive(Debug, Clone)]
struct WarningSource<T: Clone>(T);

impl<T> config::Source for WarningSource<T>
where
    T: config::Source + Send + Sync + Clone + 'static,
{
    fn clone_into_box(&self) -> Box<dyn config::Source + Send + Sync> {
        Box::new((*self).clone())
    }

    fn collect(&self) -> Result<config::Map<String, config::Value>, config::ConfigError> {
        let values = self.0.collect()?;
        if !values.is_empty() {
            use owo_colors::OwoColorize as _;

            anstream::eprintln!(
                "{}: The following environment variables have been deprecated and \
                will not work in a future release. Please change them as suggested below:",
                "DEPRECATION WARNING".yellow().bold(),
            );

            for key in values.keys() {
                let env_var = key.replace('.', "__").to_uppercase();
                anstream::eprintln!(
                    "{}: rename environment variable {} to {}",
                    "DEPRECATION WARNING".yellow().bold(),
                    format!("K3K_CTRL_{}", env_var).yellow(),
                    format!("OPENTALK_CTRL_{}", env_var).green().bold(),
                );
            }
        }

        Ok(values)
    }
}

/// OIDC and user search configuration
#[derive(Debug, Clone, Deserialize)]
pub struct OidcAndUserSearchConfiguration {
    pub oidc: OidcConfiguration,
    pub user_search: UserSearchConfiguration,
}

/// OIDC configuration
#[derive(Debug, Clone, Deserialize)]
pub struct OidcConfiguration {
    pub frontend: FrontendOidcConfiguration,
    pub controller: ControllerOidcConfiguration,
}

/// OIDC configuration for frontend
#[derive(Debug, Clone, Deserialize)]
pub struct FrontendOidcConfiguration {
    pub auth_base_url: Url,
    pub client_id: ClientId,
}

/// OIDC configuration for controller
#[derive(Debug, Clone, Deserialize)]
pub struct ControllerOidcConfiguration {
    pub auth_base_url: Url,
    pub client_id: ClientId,
    pub client_secret: ClientSecret,
}

/// User search configuration
#[derive(Debug, Clone, Deserialize)]
pub struct UserSearchConfiguration {
    pub backend: UserSearchBackend,
    pub api_base_url: Url,
    pub client_id: ClientId,
    pub client_secret: ClientSecret,
    pub external_id_user_attribute_name: Option<String>,
    pub users_find_behavior: UsersFindBehavior,
}

impl Settings {
    /// internal url builder
    fn build_url<I>(base_url: Url, path_segments: I) -> Result<Url>
    where
        I: IntoIterator,
        I::Item: AsRef<str>,
    {
        let err_url = base_url.clone();
        let mut url = base_url;
        url.path_segments_mut()
            .map_err(|_| SettingsError::NotBaseUrl { url: err_url })?
            .extend(path_segments);
        Ok(url)
    }

    /// Builds the effective OIDC and user search configuration, either from the deprecated `[keycloak]` section
    /// and some deprecated `[endpoints]` settings or from the new `[oidc]` and `[user_search]` sections.
    pub fn build_oidc_and_user_search_configuration(
        &self,
    ) -> Result<OidcAndUserSearchConfiguration> {
        let keycloak = self.keycloak.clone();
        let disable_users_find = self.endpoints.disable_users_find;
        let users_find_use_kc = self.endpoints.users_find_use_kc;
        let oidc = self.oidc.clone();
        let user_search = self.user_search.clone();

        match (
            keycloak,
            disable_users_find,
            users_find_use_kc,
            oidc,
            user_search,
        ) {
            // Only the new OIDC and user search configuration is present
            (None, None, None, Some(oidc), Some(user_search)) => {
                Self::build_new_oidc_and_user_search_configuration(oidc, user_search)
            }
            // Only the legacy OIDC and user search configuration is present
            (Some(keycloak), _, _, None, None) => {
                Self::build_legacy_oidc_and_user_search_configuration(
                    &keycloak,
                    disable_users_find,
                    users_find_use_kc,
                )?
            }
            // The OIDC and user search configuration is inconsistent
            _ => Err(SettingsError::InconsistentOidcAndUserSearchConfig),
        }
    }

    /// Builds the effective OIDC and user search configuration from the new `[oidc]` and `[user_search]` sections.
    fn build_new_oidc_and_user_search_configuration(
        oidc: Oidc,
        user_search: UserSearch,
    ) -> Result<OidcAndUserSearchConfiguration, SettingsError> {
        // Frontend-specific OIDC configuration
        let frontend_auth_base_url = oidc.frontend.authority.unwrap_or(oidc.authority.clone());
        let frontend_client_id = oidc.frontend.client_id.clone();

        // Controller-specific OIDC configuration
        let controller_auth_base_url = oidc.controller.authority.unwrap_or(oidc.authority);
        let controller_client_id = oidc.controller.client_id.clone();
        let controller_client_secret = oidc.controller.client_secret.clone();

        // User search configuration
        let backend = user_search.backend;
        let api_base_url = user_search.api_base_url;
        let user_search_client_id = user_search
            .client_id
            .unwrap_or(controller_client_id.clone());
        let user_search_client_secret = user_search
            .client_secret
            .unwrap_or(controller_client_secret.clone());
        let external_id_user_attribute_name = user_search.external_id_user_attribute_name.clone();
        let users_find_behavior = user_search.users_find_behavior;

        // Assemble the entire effective OIDC and user search configuration
        let frontend = FrontendOidcConfiguration {
            auth_base_url: frontend_auth_base_url,
            client_id: frontend_client_id,
        };
        let controller = ControllerOidcConfiguration {
            auth_base_url: controller_auth_base_url,
            client_id: controller_client_id,
            client_secret: controller_client_secret.clone(),
        };
        let oidc = OidcConfiguration {
            frontend,
            controller,
        };
        let api = UserSearchConfiguration {
            backend,
            api_base_url,
            client_id: user_search_client_id,
            client_secret: user_search_client_secret,
            external_id_user_attribute_name,
            users_find_behavior,
        };
        Ok(OidcAndUserSearchConfiguration {
            oidc,
            user_search: api,
        })
    }

    /// Builds the effective OIDC and user search configuration from the deprecated `[keycloak]` section
    /// and some deprecated `[endpoints]` settings.
    fn build_legacy_oidc_and_user_search_configuration(
        keycloak: &Keycloak,
        disable_users_find: Option<bool>,
        users_find_use_kc: Option<bool>,
    ) -> Result<Result<OidcAndUserSearchConfiguration, SettingsError>, SettingsError> {
        log::warn!(
                    "You are using deprecated OIDC and user search settings. See docs for [oidc] and [user_search] configuration sections."
                );

        // Collect legacy OIDC and user search settings
        let backend = UserSearchBackend::KeycloakWebapi;
        let api_base_url = Self::build_url(
            keycloak.base_url.clone(),
            ["admin", "realms", &keycloak.realm],
        )?;
        let auth_base_url =
            Self::build_url(keycloak.base_url.clone(), ["realms", &keycloak.realm])?;
        let client_id = keycloak.client_id.clone();
        let client_secret = keycloak.client_secret.clone();
        let external_id_user_attribute_name = keycloak.external_id_user_attribute_name.clone();
        let users_find_behavior = match (
            disable_users_find.unwrap_or_default(),
            users_find_use_kc.unwrap_or_default(),
        ) {
            (true, _) => UsersFindBehavior::Disabled,
            (false, false) => UsersFindBehavior::FromDatabase,
            (false, true) => UsersFindBehavior::FromUserSearchBackend,
        };

        // Assemble the entire effective OIDC and user search configuration
        let frontend = FrontendOidcConfiguration {
            auth_base_url: auth_base_url.clone(),
            client_id: client_id.clone(),
        };
        let controller = ControllerOidcConfiguration {
            auth_base_url,
            client_id: client_id.clone(),
            client_secret: client_secret.clone().clone(),
        };
        let oidc = OidcConfiguration {
            frontend,
            controller,
        };
        let api = UserSearchConfiguration {
            backend,
            api_base_url,
            client_id,
            client_secret,
            external_id_user_attribute_name,
            users_find_behavior,
        };
        Ok(Ok(OidcAndUserSearchConfiguration {
            oidc,
            user_search: api,
        }))
    }

    /// Creates a new Settings instance from the provided TOML file.
    /// Specific fields can be set or overwritten with environment variables (See struct level docs for more details).
    pub fn load(file_name: &str) -> Result<Self> {
        let config = Config::builder()
            .add_source(File::new(file_name, FileFormat::Toml))
            .add_source(WarningSource(
                Environment::with_prefix("K3K_CTRL")
                    .prefix_separator("_")
                    .separator("__"),
            ))
            .add_source(
                Environment::with_prefix("OPENTALK_CTRL")
                    .prefix_separator("_")
                    .separator("__"),
            )
            .build()?;

        let this: Self =
            serde_path_to_error::deserialize(config).context(DeserializeConfigSnafu {
                file_name: file_name.to_owned(),
            })?;

        Ok(this)
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct Database {
    pub url: String,
    #[serde(default = "default_max_connections")]
    pub max_connections: u32,
}

fn default_max_connections() -> u32 {
    100
}

/// Settings for Keycloak
#[derive(Debug, Clone, Deserialize)]
pub struct Keycloak {
    pub base_url: Url,
    pub realm: String,
    pub client_id: ClientId,
    pub client_secret: ClientSecret,
    pub external_id_user_attribute_name: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct Oidc {
    pub authority: Url,
    pub frontend: OidcFrontend,
    pub controller: OidcController,
}

#[derive(Debug, Clone, Deserialize)]
pub struct OidcFrontend {
    pub authority: Option<Url>,
    pub client_id: ClientId,
}

#[derive(Debug, Clone, Deserialize)]
pub struct OidcController {
    pub authority: Option<Url>,
    pub client_id: ClientId,
    pub client_secret: ClientSecret,
}

#[derive(Debug, Clone, Deserialize)]
pub struct UserSearch {
    #[serde(flatten)]
    pub backend: UserSearchBackend,
    pub api_base_url: Url,
    pub client_id: Option<ClientId>,
    pub client_secret: Option<ClientSecret>,
    pub external_id_user_attribute_name: Option<String>,
    #[serde(flatten)]
    pub users_find_behavior: UsersFindBehavior,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case", tag = "backend")]
pub enum UserSearchBackend {
    KeycloakWebapi,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case", tag = "users_find_behavior")]
pub enum UsersFindBehavior {
    Disabled,
    FromDatabase,
    FromUserSearchBackend,
}

#[derive(Debug, Clone, Deserialize)]
pub struct Http {
    #[serde(default = "default_http_port")]
    pub port: u16,
    #[serde(default)]
    pub tls: Option<HttpTls>,
}

impl Default for Http {
    fn default() -> Self {
        Self {
            port: default_http_port(),
            tls: None,
        }
    }
}

const fn default_http_port() -> u16 {
    11311
}

#[derive(Debug, Clone, Deserialize)]
pub struct HttpTls {
    pub certificate: PathBuf,
    pub private_key: PathBuf,
}

#[derive(Default, Debug, Clone, Deserialize)]
pub struct Logging {
    pub default_directives: Option<Vec<String>>,

    pub otlp_tracing_endpoint: Option<String>,

    pub service_name: Option<String>,

    pub service_namespace: Option<String>,

    pub service_instance_id: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct Turn {
    /// How long should a credential pair be valid, in seconds
    #[serde(
        deserialize_with = "duration_from_secs",
        default = "default_turn_credential_lifetime"
    )]
    pub lifetime: Duration,
    /// List of configured TURN servers.
    pub servers: Vec<TurnServer>,
}

impl Default for Turn {
    fn default() -> Self {
        Self {
            lifetime: default_turn_credential_lifetime(),
            servers: vec![],
        }
    }
}

fn default_turn_credential_lifetime() -> Duration {
    Duration::from_secs(60)
}

#[derive(Debug, Clone, Deserialize)]
pub struct TurnServer {
    // TURN URIs for this TURN server following rfc7065
    pub uris: Vec<String>,
    pub pre_shared_key: String,
}

#[derive(Clone, Debug, Deserialize)]
pub struct Stun {
    // STUN URIs for this TURN server following rfc7065
    pub uris: Vec<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct RedisConfig {
    #[serde(default = "redis_default_url")]
    pub url: url::Url,
}

impl Default for RedisConfig {
    fn default() -> Self {
        Self {
            url: redis_default_url(),
        }
    }
}

fn redis_default_url() -> url::Url {
    url::Url::try_from("redis://localhost:6379/").expect("Invalid default redis URL")
}

#[derive(Debug, Clone, Deserialize)]
pub struct RabbitMqConfig {
    #[serde(default = "rabbitmq_default_url")]
    pub url: String,
    #[serde(default = "rabbitmq_default_min_connections")]
    pub min_connections: u32,
    #[serde(default = "rabbitmq_default_max_channels")]
    pub max_channels_per_connection: u32,
    /// Mail sending is disabled when this is None
    #[serde(default)]
    pub mail_task_queue: Option<String>,

    /// Recording is disabled if this isn't set
    #[serde(default)]
    pub recording_task_queue: Option<String>,
}

impl Default for RabbitMqConfig {
    fn default() -> Self {
        Self {
            url: rabbitmq_default_url(),
            min_connections: rabbitmq_default_min_connections(),
            max_channels_per_connection: rabbitmq_default_max_channels(),
            mail_task_queue: None,
            recording_task_queue: None,
        }
    }
}

fn rabbitmq_default_url() -> String {
    "amqp://guest:guest@localhost:5672".to_owned()
}

fn rabbitmq_default_min_connections() -> u32 {
    10
}

fn rabbitmq_default_max_channels() -> u32 {
    100
}

#[derive(Clone, Debug, Deserialize)]
pub struct Authz {
    #[serde(default = "authz_default_synchronize_controller")]
    pub synchronize_controllers: bool,
}

impl Default for Authz {
    fn default() -> Self {
        Self {
            synchronize_controllers: authz_default_synchronize_controller(),
        }
    }
}

fn authz_default_synchronize_controller() -> bool {
    true
}

#[derive(Clone, Debug, Deserialize)]
pub struct Etcd {
    pub urls: Vec<url::Url>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct Etherpad {
    pub url: url::Url,
    pub api_key: String,
}

#[derive(Clone, Debug, Deserialize)]
pub struct Spacedeck {
    pub url: url::Url,
    pub api_key: String,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct Reports {
    pub url: url::Url,
    #[serde(default)]
    pub template: ReportsTemplate,
}

#[derive(Clone, Debug, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ReportsTemplate {
    /// Use the Template included with the application.
    #[default]
    BuiltIn,

    /// Use the Template provided by the user configuration.
    Inline(String),
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[serde(tag = "provider", rename_all = "snake_case")]
pub enum SharedFolder {
    Nextcloud {
        url: url::Url,
        username: String,
        password: String,
        #[serde(default)]
        directory: String,
        #[serde(default)]
        expiry: Option<u64>,
    },
}

fn duration_from_secs<'de, D>(deserializer: D) -> Result<Duration, D::Error>
where
    D: Deserializer<'de>,
{
    let duration: u64 = Deserialize::deserialize(deserializer)?;

    Ok(Duration::from_secs(duration))
}

#[derive(Clone, Debug, Deserialize)]
pub struct Avatar {
    #[serde(default = "default_libravatar_url")]
    pub libravatar_url: String,
}

impl Default for Avatar {
    fn default() -> Self {
        Self {
            libravatar_url: default_libravatar_url(),
        }
    }
}

fn default_libravatar_url() -> String {
    "https://seccdn.libravatar.org/avatar/".into()
}

#[derive(Clone, Debug, Deserialize)]
pub struct CallIn {
    pub tel: String,
    pub enable_phone_mapping: bool,
    pub default_country_code: phonenumber::country::Id,
}

#[derive(Clone, Default, Debug, Deserialize)]
pub struct Defaults {
    #[serde(default = "default_user_language")]
    pub user_language: Language,
    #[serde(default)]
    pub screen_share_requires_permission: bool,
    #[serde(default)]
    pub disabled_features: BTreeSet<ModuleFeatureId>,
}

fn default_user_language() -> Language {
    "en-US".parse().expect("valid language")
}

#[derive(Clone, Default, Debug, Deserialize)]
pub struct Endpoints {
    pub disable_users_find: Option<bool>,
    pub users_find_use_kc: Option<bool>,
    #[serde(default)]
    pub event_invite_external_email_address: bool,
    #[serde(default)]
    pub disallow_custom_display_name: bool,
    #[serde(default)]
    pub disable_openapi: bool,
}

#[derive(Clone, Debug, Deserialize)]
pub struct MinIO {
    pub uri: String,
    pub bucket: String,
    pub access_key: String,
    pub secret_key: String,
}

#[derive(Debug, Default, Clone, Deserialize)]
pub struct Metrics {
    pub allowlist: Vec<cidr::IpInet>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "snake_case", tag = "assignment")]
pub enum TenantAssignment {
    Static {
        static_tenant_id: String,
    },
    ByExternalTenantId {
        #[serde(default = "default_external_tenant_id_user_attribute_name")]
        external_tenant_id_user_attribute_name: String,
    },
}

fn default_external_tenant_id_user_attribute_name() -> String {
    "tenant_id".to_owned()
}

impl Default for TenantAssignment {
    fn default() -> Self {
        Self::Static {
            static_tenant_id: String::from("OpenTalkDefaultTenant"),
        }
    }
}

#[derive(Default, Debug, Clone, Deserialize)]
pub struct Tenants {
    #[serde(default, flatten)]
    pub assignment: TenantAssignment,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "snake_case", tag = "assignment")]
pub enum TariffAssignment {
    Static { static_tariff_name: String },
    ByExternalTariffId,
}

impl Default for TariffAssignment {
    fn default() -> Self {
        Self::Static {
            static_tariff_name: String::from("OpenTalkDefaultTariff"),
        }
    }
}

#[derive(Default, Debug, Clone, Deserialize)]
pub struct TariffStatusMapping {
    pub downgraded_tariff_name: String,
    pub default: FxHashSet<String>,
    pub paid: FxHashSet<String>,
    pub downgraded: FxHashSet<String>,
}

#[derive(Default, Debug, Clone, Deserialize)]
pub struct Tariffs {
    #[serde(default, flatten)]
    pub assignment: TariffAssignment,

    #[serde(default)]
    pub status_mapping: Option<TariffStatusMapping>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct LiveKitSettings {
    pub api_key: String,
    pub api_secret: String,
    pub public_url: String,

    // for backwards compatibility
    #[serde(alias = "url")]
    pub service_url: String,
}

#[cfg(test)]
mod tests {
    use std::env;

    use pretty_assertions::assert_eq;
    use serde_json::json;

    use super::*;

    #[test]
    fn settings_env_vars_overwrite_config() -> Result<()> {
        // Sanity check
        let settings = Settings::load("../../extra/example.toml")?;

        assert_eq!(
            settings.database.url,
            "postgres://postgres:password123@localhost:5432/opentalk"
        );
        assert_eq!(settings.http.port, 11311u16);

        // Set environment variables to overwrite default config file
        let env_db_url = "postgres://envtest:password@localhost:5432/opentalk".to_string();
        let env_http_port: u16 = 8000;
        let screen_share_requires_permission = true;
        env::set_var("OPENTALK_CTRL_DATABASE__URL", &env_db_url);
        env::set_var("OPENTALK_CTRL_HTTP__PORT", env_http_port.to_string());
        env::set_var(
            "OPENTALK_CTRL_DEFAULTS__SCREEN_SHARE_REQUIRES_PERMISSION",
            screen_share_requires_permission.to_string(),
        );

        let settings = Settings::load("../../extra/example.toml")?;

        assert_eq!(settings.database.url, env_db_url);
        assert_eq!(settings.http.port, env_http_port);
        assert_eq!(
            settings.defaults.screen_share_requires_permission,
            screen_share_requires_permission
        );

        Ok(())
    }

    #[test]
    fn shared_folder_provider_nextcloud() {
        let shared_folder = SharedFolder::Nextcloud {
            url: "https://nextcloud.example.org/".parse().unwrap(),
            username: "exampleuser".to_string(),
            password: "v3rys3cr3t".to_string(),
            directory: "meetings/opentalk".to_string(),
            expiry: Some(34),
        };
        let json = json!({
            "provider": "nextcloud",
            "url": "https://nextcloud.example.org/",
            "username": "exampleuser",
            "password": "v3rys3cr3t",
            "directory": "meetings/opentalk",
            "expiry": 34,
        });

        assert_eq!(
            serde_json::from_value::<SharedFolder>(json).unwrap(),
            shared_folder
        );
    }

    #[test]
    fn meeting_report_settings() {
        let toml_settings: Reports = toml::from_str(
            r#"
        url = "http://localhost"
        "#,
        )
        .unwrap();
        assert_eq!(
            toml_settings,
            Reports {
                url: "http://localhost".parse().unwrap(),
                template: ReportsTemplate::BuiltIn
            }
        );

        let toml_settings: Reports = toml::from_str(
            r#"
        url = "http://localhost"
        template.inline = "lorem ipsum"
        "#,
        )
        .unwrap();
        assert_eq!(
            toml_settings,
            Reports {
                url: "http://localhost".parse().unwrap(),
                template: ReportsTemplate::Inline("lorem ipsum".to_string())
            }
        );
    }
}