Skip to main content

opentalk_client_data_persistence/
opentalk_instance_config.rs

1// SPDX-FileCopyrightText: OpenTalk GmbH <mail@opentalk.eu>
2//
3// SPDX-License-Identifier: EUPL-1.2
4
5use std::collections::BTreeMap;
6
7use serde::{Deserialize, Serialize};
8
9use crate::{OpenTalkAccountConfig, OpenTalkAccountId};
10
11/// Configuration of an OpenTalk instance.
12#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
13pub struct OpenTalkInstanceConfig {
14    /// The id of the default account to use when using the OpenTalk instance.
15    pub default_account: OpenTalkAccountId,
16
17    /// The accounts that are configured for an OpenTalk instance.
18    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
19    pub accounts: BTreeMap<OpenTalkAccountId, OpenTalkAccountConfig>,
20}
21
22impl OpenTalkInstanceConfig {
23    /// Get the default instance if available.
24    pub fn get_default_account(&self) -> Option<(OpenTalkAccountId, OpenTalkAccountConfig)> {
25        self.get_account(&self.default_account)
26            .map(|account| (self.default_account.clone(), account))
27    }
28
29    /// Get an account by its [OpenTalkAccountId].
30    pub fn get_account(&self, account_id: &OpenTalkAccountId) -> Option<OpenTalkAccountConfig> {
31        self.accounts.get(account_id).cloned()
32    }
33
34    /// Get an account config by an optional id, returning the default account if the id is [None].
35    pub fn get_account_with_fallback_to_default(
36        &self,
37        account_id: Option<&OpenTalkAccountId>,
38    ) -> Option<(OpenTalkAccountId, OpenTalkAccountConfig)> {
39        if let Some(account_id) = account_id {
40            let account = self.get_account(account_id)?;
41            Some((account_id.clone(), account))
42        } else {
43            self.get_default_account()
44        }
45    }
46
47    /// Remove an account from the configuration.
48    pub fn remove_account(&mut self, account_id: Option<&OpenTalkAccountId>) {
49        let account_id = account_id.unwrap_or(&self.default_account);
50
51        let _ = self.accounts.remove(account_id);
52    }
53}