so://phie

verbal

A mobile app for listening to radio stations from around the globe
git clone git://soophie.de/verbal

blob: efb5830ccbd75559d7103e16b35bc0cd825103dd (2661 bytes)[doc][blame][raw]

1use serde::Deserialize;

2use std::fmt::Write;

3use std::fs;

4use std::path::Path;

5use std::path::PathBuf;

6

7use crate::error::Error;

8use crate::Result;

9use crate::ToUrl;

10use crate::APP_NAME;

11

12#[derive(Debug, Clone, Deserialize)]

13pub struct Server {

14 pub hostname: String,

15 pub port: i32,

16 pub cert_path: Option<String>,

17 pub key_path: Option<String>,

18 pub options: Options,

19}

20

21impl Server {

22 pub fn is_tls(&self) -> bool {

23 if !443.eq(&self.port) {

24 return false;

25 }

26 if self.cert_path.is_none() || self.key_path.is_none() {

27 warn!("the port 443 is usually used for TLS only!");

28 return false;

29 }

30 true

31 }

32}

33

34impl ToUrl for Server {

35 fn to_url(&self) -> Result<String> {

36 let mut url = String::new();

37 write!(url, "{}:{}", self.hostname, self.port)?;

38 Ok(url)

39 }

40}

41

42#[derive(Debug, Clone, Deserialize)]

43pub struct Options {

44 pub origin: String,

45}

46

47#[derive(Debug, Clone, Deserialize)]

48pub struct Database {

49 pub hostname: String,

50 pub port: i32,

51 pub username: String,

52 pub password: String,

53 pub database: String,

54}

55

56impl ToUrl for Database {

57 fn to_url(&self) -> Result<String> {

58 let mut url = String::new();

59 write!(

60 url,

61 "postgres://{}:{}@{}:{}/{}?sslmode=disable",

62 self.username, self.password, self.hostname, self.port, self.database,

63 )?;

64 Ok(url)

65 }

66}

67

68#[derive(Debug, Clone, Deserialize)]

69pub struct Config {

70 pub server: Server,

71 pub database: Database,

72}

73

74impl Config {

75 pub fn acquire() -> Result<Self> {

76 let mut config_file = Self::get_global();

77 let local_file = Self::get_local();

78 if local_file.is_some() {

79 config_file = local_file;

80 }

81 match config_file {

82 Some(file) => {

83 let raw = fs::read_to_string(&file)?;

84 let config: Self = toml::from_str(&raw)?;

85 Ok(config)

86 }

87 None => Err(Error::new("unable to determine config file!")),

88 }

89 }

90 fn get_local() -> Option<PathBuf> {

91 let local_file = Path::new("config.toml").to_path_buf();

92 if !local_file.exists() {

93 return None;

94 }

95 Some(local_file)

96 }

97 fn get_global() -> Option<PathBuf> {

98 let mut global_file = match dirs::config_dir() {

99 Some(file) => file,

100 None => return None,

101 };

102 global_file.push(APP_NAME);

103 global_file.push("config.toml");

104 if !global_file.exists() {

105 return None;

106 }

107 Some(global_file)

108 }

109}