buckets_core/
config.rs

1use std::collections::HashMap;
2
3use oiseau::config::{Configuration, DatabaseConfig};
4use pathbufd::PathBufD;
5use serde::{Deserialize, Serialize};
6
7#[derive(Clone, Debug, Serialize, Deserialize)]
8pub struct Config {
9    /// The directory files are stored in (relative to cwd).
10    #[serde(default = "default_directory")]
11    pub directory: String,
12    /// The path to the default image to be served for the given buckets.
13    #[serde(default = "default_bucket_defaults")]
14    pub bucket_defaults: HashMap<String, (String, String)>,
15    /// Database configuration.
16    #[serde(default = "default_database")]
17    pub database: DatabaseConfig,
18    /// Hosts which buckets will refuse to proxy through the image proxy.
19    ///
20    /// It is recommended that this includes the buckets server URL to prevent
21    /// infinite loops.
22    #[serde(default = "default_banned_hosts")]
23    pub banned_hosts: Vec<String>,
24}
25
26fn default_directory() -> String {
27    "buckets".to_string()
28}
29
30fn default_bucket_defaults() -> HashMap<String, (String, String)> {
31    HashMap::new()
32}
33
34fn default_database() -> DatabaseConfig {
35    DatabaseConfig::default()
36}
37
38fn default_banned_hosts() -> Vec<String> {
39    Vec::new()
40}
41
42impl Configuration for Config {
43    fn db_config(&self) -> DatabaseConfig {
44        self.database.to_owned()
45    }
46}
47
48impl Default for Config {
49    fn default() -> Self {
50        Self {
51            directory: default_directory(),
52            bucket_defaults: default_bucket_defaults(),
53            database: default_database(),
54            banned_hosts: default_banned_hosts(),
55        }
56    }
57}
58
59impl Config {
60    /// Read the configuration file.
61    pub fn read() -> Self {
62        toml::from_str(
63            &match std::fs::read_to_string(PathBufD::current().join("app.toml")) {
64                Ok(x) => x,
65                Err(_) => {
66                    let x = Config::default();
67
68                    std::fs::write(
69                        PathBufD::current().join("app.toml"),
70                        &toml::to_string_pretty(&x).expect("failed to serialize config"),
71                    )
72                    .expect("failed to write config");
73
74                    return x;
75                }
76            },
77        )
78        .expect("failed to deserialize config")
79    }
80}