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
use crate::auth::{Credentials, Platform};
use crate::command_access::AccessRights;
use core::fmt;
use dirs_next::config_dir;
use serde::export::fmt::Display;
use serde::export::Formatter;
use serde_json::Error as JsonError;
use std::collections::HashMap;
use std::ffi::OsString;
use std::fs::{create_dir_all, read_dir, read_to_string, remove_dir_all, DirEntry, File};
use std::io::Write;
use std::path::PathBuf;
use std::{error, io};

const ENV_ACTIVE_PROFILE: &str = "BRS_ACTIVE_PROFILE";

#[derive(Debug)]
pub enum ProfileError {
    AlreadyExists(OsString),
    IO(io::Error),
    Json(JsonError),
}

impl From<io::Error> for ProfileError {
    fn from(content: io::Error) -> Self {
        ProfileError::IO(content)
    }
}

impl From<JsonError> for ProfileError {
    fn from(content: JsonError) -> Self {
        ProfileError::Json(content)
    }
}

impl error::Error for ProfileError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            ProfileError::IO(source) => Some(source),
            ProfileError::Json(source) => Some(source),
            ProfileError::AlreadyExists(_) => None,
        }
    }
}

impl Display for ProfileError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            ProfileError::IO(why) => write!(f, "failed to read/write config file '{}'", why),
            ProfileError::Json(why) => write!(f, "invalid config file: {}", why),
            ProfileError::AlreadyExists(name) => write!(
                f,
                "profile named '{}' already exists",
                name.to_str().unwrap()
            ),
        }
    }
}

/// Profile configuration containing configurations for the Bot-RS Core functionality.
///
/// Profile configurations are located at `{{ENV_CONFIG_DIR}}/profiles/{profile-name}`.
///
/// A Profile is only allowed to join the channel its named after.
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
pub struct Profile {
    name: String,
    channels: Vec<String>,
    credentials: HashMap<Platform, Credentials>,
    client_id: String,
    client_secret: Option<String>,
    rights: AccessRights,
}

impl Profile {
    pub fn empty() -> Self {
        Self::new(String::new(), Vec::new(), String::new(), None)
    }

    pub fn new(
        name: String,
        channels: Vec<String>,
        client_id: String,
        client_secret: Option<String>,
    ) -> Self {
        Profile {
            name,
            channels,
            client_id,
            client_secret,
            credentials: HashMap::new(),
            rights: AccessRights::new(),
        }
    }

    pub fn active() -> Option<Self> {
        if let Ok(env_var) = std::env::var(ENV_ACTIVE_PROFILE) {
            if let Ok(profile) = serde_json::from_str(env_var.as_str()) {
                Some(profile)
            } else {
                None
            }
        } else {
            None
        }
    }

    pub fn get_channels(&self) -> &[String] {
        &self.channels
    }

    pub fn get_client_id(&self) -> String {
        self.client_id.clone()
    }

    pub fn get_client_secret(&self) -> Option<String> {
        self.client_secret.clone()
    }

    pub fn add_channels(&mut self, channels: Vec<String>) {
        let mut new_channels = Vec::with_capacity(self.channels.len() + channels.len());
        new_channels.append(&mut self.channels);
        new_channels.extend(channels);
        self.channels = new_channels;
    }

    pub fn from_dir(dir: &DirEntry) -> Result<Self, ProfileError> {
        // Load config file of profile
        let cfg_file = dir.path().join("config.json");
        let content = read_to_string(cfg_file).map_err(ProfileError::from)?;
        let mut profile: Profile = serde_json::from_str(&content).map_err(ProfileError::from)?;
        profile.name = dir
            .file_name()
            .into_string()
            .expect("failed to create string from profile dir name");

        Ok(profile)
    }

    pub fn profile_dir(name: OsString) -> PathBuf {
        Profiles::profiles_dir().join(name)
    }

    pub fn set_active(&self) {
        let ser = serde_json::to_string(self).expect("failed to serialize profile");
        std::env::set_var(ENV_ACTIVE_PROFILE, ser);
    }

    /// Sets the given credentials for the platform. Overwrites existing credentials for the platform.
    pub fn set_credentials(&mut self, platform: Platform, creds: Credentials) {
        self.credentials.insert(platform, creds);
    }

    pub fn get_credentials(&self, platform: &Platform) -> Option<&Credentials> {
        self.credentials.get(platform)
    }

    pub fn rights(&self) -> &AccessRights {
        &self.rights
    }

    pub fn path(&self) -> PathBuf {
        Profiles::profiles_dir().join(&self.name)
    }

    pub fn plugins_path(&self) -> PathBuf {
        self.path().join("plugins")
    }

    pub fn save(&self) -> Result<(), ProfileError> {
        let path = self.path();
        let json = serde_json::to_string_pretty(self).map_err(ProfileError::from)?;
        create_dir_all(&path).expect("failed to create profile directory");
        let mut file = File::create(path.join("config.json")).map_err(ProfileError::from)?;
        file.write(json.as_bytes()).map_err(ProfileError::from)?;
        let plugins_dir = self.plugins_path();
        create_dir_all(&plugins_dir)
            .expect("failed to create plugins dir inside profile directory");
        Ok(())
    }

    pub fn delete(&self) -> Result<(), ProfileError> {
        remove_dir_all(self.path()).map_err(ProfileError::IO)
    }
}

impl Display for Profile {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        writeln!(
            f,
            "Location:\t{}",
            Self::profile_dir(OsString::from(&self.name)).display()
        )?;
        writeln!(f, "Name:\t\t{}", self.name)?;
        if self.credentials.is_empty() {
            write!(f, "Credentials:\tNone")?;
        } else {
            writeln!(f, "Credentials:")?;
            for (platform, creds) in self.credentials.iter() {
                writeln!(f, "\t{:?}: {}", platform, creds)?;
            }
        }
        writeln!(f, "Channels:\t{}", self.channels.join(", "))?;
        if self.rights.is_empty() {
            writeln!(f, "Access Rights:\tOnly Broadcaster")?;
        } else {
            writeln!(f, "Access Rights:")?;
            for filter in self.rights.iter() {
                writeln!(f, "\t{}", filter)?;
            }
        }
        Ok(())
    }
}

#[derive(Debug)]
pub struct Profiles {
    profiles: HashMap<OsString, Profile>,
}

impl Profiles {
    pub fn profiles_dir() -> PathBuf {
        Configs::cfg_dir().join("profiles")
    }

    pub fn load() -> Self {
        let path = Self::profiles_dir();
        create_dir_all(&path).expect("failed to create profile config files");
        let paths = read_dir(&path).expect("failed to read config directory");
        let mut profiles = HashMap::new();

        for path in paths {
            let path = path.expect("failed to get path of configuration subdir");
            if path.file_type().expect("failed to get file-type").is_dir() {
                match Profile::from_dir(&path) {
                    Err(why) => warn!(
                        "failed to load profile config '{}': {}",
                        path.path().display(),
                        why
                    ),
                    Ok(profile) => {
                        profiles.insert(path.file_name(), profile);
                    }
                }
            }
        }

        Profiles { profiles }
    }

    pub fn add(&mut self, profile: Profile) -> Result<(), ProfileError> {
        let osstr = OsString::from(&profile.name);
        if self.profiles.contains_key(&osstr) {
            return Err(ProfileError::AlreadyExists(osstr));
        }
        self.profiles.insert(osstr, profile);
        Ok(())
    }

    pub fn delete<S: AsRef<str>>(&mut self, name: S) -> Result<(), ProfileError> {
        let osstr = OsString::from(name.as_ref());
        if let Some(profile) = self.profiles.remove(&osstr) {
            profile.delete()?;
        }
        Ok(())
    }

    pub fn get<S: AsRef<str>>(&self, profile: S) -> Option<&Profile> {
        let osstr = OsString::from(profile.as_ref());
        self.profiles.get(&osstr)
    }

    pub fn get_mut<S: AsRef<str>>(&mut self, profile: S) -> Option<&mut Profile> {
        let osstr = OsString::from(profile.as_ref());
        self.profiles.get_mut(&osstr)
    }

    pub fn save(&self) -> Result<(), ProfileError> {
        for (_, profile) in self.profiles.iter() {
            profile.save()?;
        }
        Ok(())
    }

    pub fn iter(&self) -> std::collections::hash_map::Iter<OsString, Profile> {
        self.profiles.iter()
    }
}

pub struct Configs;

impl Configs {
    pub fn cfg_dir() -> PathBuf {
        config_dir()
            .expect("missing config directory")
            .join("botrs")
    }

    pub fn log_path() -> PathBuf {
        Self::cfg_dir().join("log")
    }

    pub fn stats_path() -> PathBuf {
        Self::cfg_dir().join("stats")
    }
}