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
use crate::constant::*;

use anyhow::{anyhow, Result};
use config_parser2::*;
use librespot_core::config::SessionConfig;
use reqwest::Url;
use serde::{Deserialize, Serialize};
use std::{
    path::{Path, PathBuf},
    sync::OnceLock,
};

static CONFIGS: OnceLock<Configs> = OnceLock::new();

#[derive(Debug)]
pub struct Configs {
    pub app_config: AppConfig,
    pub cache_folder: std::path::PathBuf,
    pub username: String,
    pub password: String
}

impl Configs {
    pub fn new<P, T>(config_folder: P, cache_folder: P, username: T, password: T) -> Result<Self>
    where
        P: AsRef<Path>,
        T: Into<String>
     {
        Ok(Self {
            app_config: AppConfig::new(config_folder)?,
            cache_folder: cache_folder.as_ref().to_path_buf(),
            username: username.into(),
            password: password.into()
        })
    }

    // <P: AsRef<Path>>
    pub fn from_env() -> Result<Self> {
        use std::env::var;
        dotenvy::dotenv().ok();

        let config_path = var("SPOTIFY_CONFIG_PATH").unwrap_or(".config/spotify-player".to_string());
        let cache_path = var("SPOTIFY_CACHE_PATH").unwrap_or(".cache/spotify-player".to_string());
        let username = var("SPOTIFY_USERNAME")?;
        let password = var("SPOTIFY_PASSWORD")?;

        Self::new(config_path, cache_path, username, password)
    } 
}

#[derive(Debug, Deserialize, Serialize, ConfigParse)]
/// Application configurations
pub struct AppConfig {
    pub client_id: String,

    pub client_port: u16,

    // session configs
    pub proxy: Option<String>,
    pub ap_port: Option<u16>,

    // duration configs
    pub app_refresh_duration_in_ms: u64,
    pub playback_refresh_duration_in_ms: u64,

    pub enable_cover_image_cache: bool,

    pub notify_streaming_only: bool,
}


impl Default for AppConfig {
    fn default() -> Self {
        Self {
            // official Spotify web app's client id
            client_id: "65b708073fc0480ea92a077233ca87bd".to_string(),

            client_port: 8080,

            proxy: None,
            ap_port: None,
            app_refresh_duration_in_ms: 32,
            playback_refresh_duration_in_ms: 0,

            enable_cover_image_cache: true,

            notify_streaming_only: false,
        }
    }
}


impl AppConfig {
    pub fn new(path: impl AsRef<Path>) -> Result<Self> {
        let mut config = Self::default();
        if !config.parse_config_file(path.as_ref())? {
            config.write_config_file(path.as_ref())?
        }

        Ok(config)
    }

    // parses configurations from an application config file in `path` folder,
    // then updates the current configurations accordingly.
    // returns false if no config file found and true otherwise
    fn parse_config_file<P: AsRef<Path>>(&mut self, path: P) -> Result<bool> {
        let file_path = path.as_ref().join(APP_CONFIG_FILE);
        match std::fs::read_to_string(file_path) {
            Ok(content) => self
                .parse(toml::from_str::<toml::Value>(&content)?)
                .map(|_| true),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
            Err(error) => Err(error.into()),
        }
    }

    fn write_config_file<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
        toml::to_string_pretty(&self)
            .map_err(From::from)
            .and_then(|content| {
                std::fs::write(path.as_ref().join(APP_CONFIG_FILE), content)
                    .map_err(From::from)
            })
    }

    pub fn session_config(&self) -> SessionConfig {
        let proxy = self
            .proxy
            .as_ref()
            .and_then(|proxy| match Url::parse(proxy) {
                Err(err) => {
                    tracing::warn!("failed to parse proxy url {proxy}: {err:#}");
                    None
                }
                Ok(url) => Some(url),
            });
        SessionConfig {
            proxy,
            ap_port: self.ap_port,
            ..Default::default()
        }
    }
}

/// gets the application's configuration folder path
pub fn get_config_folder_path() -> Result<PathBuf> {
    match dirs_next::home_dir() {
        Some(home) => Ok(format!("./{}", DEFAULT_CONFIG_FOLDER).into()),
        None => Err(anyhow!("cannot find the folder")),
    }
}

/// gets the application's cache folder path
pub fn get_cache_folder_path() -> Result<PathBuf> {
    match dirs_next::home_dir() {
        Some(home) =>  Ok(format!("./{}", DEFAULT_CACHE_FOLDER).into()),
        None => Err(anyhow!("cannot find the folder")),
    }
}


#[inline(always)]
pub fn get_config() -> &'static Configs {
    CONFIGS.get().expect("configs is already initialized")
}
pub fn set_config(configs: Configs) {
    CONFIGS
        .set(configs)
        .expect("configs should be initialized only once")
}