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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
use crate::{AuthenticatedApi, Error, Color};
use serde::{Deserialize, Serialize};
use url::Url;

/// Settings API methods
pub struct SettingsApi<'a> {
    pub(crate) api: &'a AuthenticatedApi,
}

/// Structure to query multiple settings, see
/// [get_multiple](SettingsApi::get_multiple)
pub struct SettingsBuilder<'api> {
    settings: Vec<String>,
    api: &'api SettingsApi<'api>,
}

impl<'api> SettingsBuilder<'api> {
    #[inline]
    pub fn get(mut self, setting: impl Setting) -> Self {
        self.settings.push(setting.name());
        self
    }
    pub async fn query(self) -> Result<Vec<SettingValue>, Error> {
        let api = self.api;
        api.query_settings(self).await
    }
}

impl<'a> SettingsApi<'a> {

    /// Fetch one setting
    /// Notes
    ///  - If the setting is not defined, it will default to null
    ///  - Accessing an undefined setting in the client scope will not create it
    #[inline]
    pub fn get(&self) -> SettingsFetcher {
        SettingsFetcher { api: self.api }
    }
    /// Notes
    ///  - If you reset a setting in the client scope, it will be deleted and no longer appear in the list action
    ///  - If the setting does not exist, the value will be null
    #[inline]
    pub fn reset(&self) -> SettingReset {
        SettingReset { api: self.api }
    }
    /// Fetch multiple settings
    /// Notes
    ///  - If the setting is not defined, it will default to null
    ///  - Accessing an undefined setting in the client scope will not create it
    #[inline]
    pub fn get_multiple(&self) -> SettingsBuilder<'_> {
        SettingsBuilder {
            api: self,
            settings: Vec::new(),
        }
    }
    /// Fetch all the settings
    pub async fn get_all(&self) -> Result<AllSettings, crate::Error> {
        Ok(self.api.passwords_get("1.0/settings/list", ()).await?)
    }

    /// Set the value of a writable setting
    pub async fn set(
        &self,
        settings: Settings,
    ) -> Result<Vec<SettingValue>, Error> {
        let settings: Settings =
            self.api.passwords_post("1.0/settings/set", settings).await?;
        Ok(settings.to_values())
    }
    /// Set the value of a client setting
    /// Note
    ///  - If the size limitations of the client scope are exceeded, an error will be returned
    pub async fn set_client<D: Serialize + serde::de::DeserializeOwned>(
        &self,
        name: ClientSettings,
        value: D,
    ) -> Result<D, Error> {
        type ClientData<D> = std::collections::HashMap<String, D>;
        let mut data = ClientData::new();
        data.insert(name.name.clone(), value);
        let mut data: ClientData<D> = self.api.passwords_post("1.0/settings/set", data).await?;
        Ok(data
            .remove(&name.name)
            .expect("server did not set client setting"))
    }

    async fn query_settings(
        &self,
        settings: SettingsBuilder<'_>,
    ) -> Result<Vec<SettingValue>, Error> {
        let data: Settings = self.api
            .passwords_post("1.0/settings/get", settings.settings)
            .await?;
        Ok(data.to_values())
    }

}

/// Fetch a single setting
pub struct SettingsFetcher<'api> {
    pub(crate) api: &'api AuthenticatedApi,
}
pub struct SettingReset<'api> {
    pub(crate) api: &'api AuthenticatedApi,
}

/// Represent a way to map the settings enums to nextcloud passwords
/// setting names
pub trait Setting: super::private::Sealed {
    fn name(&self) -> String;
}
/// What settings are writable by the API
pub trait WritableSetting: Setting {}

#[derive(thiserror::Error, Debug)]
pub enum ParseError {
    #[error("could not parse a number")]
    Number(#[from] std::num::ParseIntError),

    #[error("could not parse a boolean")]
    Boolean(#[from] std::str::ParseBoolError),
}

macro_rules! settings {
    (@dollar[$dol:tt] User = $user:ident($valued_user:ident), Server = $server:ident($valued_server:ident) {
        $(User:$user_variant:ident ($user_type:ty), $user_field:ident => $user_setting:expr),*,
        $(Server:$server_variant:ident ($server_type:ty), $server_field:ident => $server_setting:expr),*,
    }) => {

        /// The names of all the settings
        pub const SETTINGS_NAMES: &'static [&'static str] = &[
            $($user_setting,)*
            $($server_setting,)*
        ];
        /// The names of user settings
        pub const USER_SETTING_NAMES: &'static [&'static str] = &[
            $($user_setting,)*
        ];
        /// The name of server settings
        pub const SERVER_SETTING_NAMES: &'static [&'static str] = &[
            $($server_setting,)*
        ];

        /// takes a macro with the signature `callback!($variant_name:ident; $type:ty; $field_name:ident; $setting_string:expr => $(arg:tt)*)`
        /// and expands it for each of the settings (client not included).
        ///
        /// You need to prefix by expr if an expr is generated, and item if an item is generated
        /// example call: `macro_on_settings!(callback(...args))`. Notice that there is no `!`
        #[macro_export]
        macro_rules! macro_on_settings {
            ($dol callback:ident ($dol ($dol args:tt)*)) => {
                $(
                    $dol callback!($user_variant; $user_type; $user_field; $user_setting => $dol ($dol args)*);
                )*
                $(
                    $dol callback!($server_variant; $server_type; $server_field; $server_setting => $dol ($dol args)*);
                )*
            };
        }
        /// Check the definition of [macro_on_settings]
        #[macro_export]
        macro_rules! macro_on_user_settings {
            ($dol callback:ident ($dol ($dol args:tt)*)) => {
                $(
                    $dol callback!($user_variant; $user_type; $user_field; $user_setting => $dol ($dol args)*);
                )*
            };
        }
        /// Check the definition of [macro_on_settings]
        #[macro_export]
        macro_rules! macro_on_server_settings {
            ($dol callback:ident ($dol ($dol args:tt)*)) => {
                $(
                    $dol callback!($user_variant; $user_type; $user_field; $user_setting => $dol ($dol args)*);
                )*
            };
        }

        /// User Setting names
        #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash)]
        pub enum $user {
            $($user_variant,)*
        }

        impl std::str::FromStr for $user {
            type Err = &'static str;

            fn from_str(s: &str) -> Result<Self, Self::Err> {
                match s {
                    $(
                        $user_setting => Ok(Self::$user_variant),
                    )*
                        _ => Err("Unknown variant"),
                }
            }
        }

        impl<'api> SettingReset<'api> {
            $(
                pub async fn $user_field(&self) -> Result<$user_type, crate::Error> {
                    let data: Settings = self.api.passwords_post("1.0/settings/reset", vec![$user_setting]).await?;
                    Ok(data.$user_field.expect("server did not provide the asked setting"))
                }
            )*

        }

        impl<'api> SettingsFetcher<'api> {
            $(
                pub async fn $user_field(&self) -> Result<$user_type, crate::Error> {
                    let data: Settings = self.api.passwords_post("1.0/settings/get", vec![$user_setting]).await?;
                    Ok(data.$user_field.expect("server did not provide the asked setting"))
                }
            )*
            $(
                pub async fn $server_field(&self) -> Result<$server_type, crate::Error> {
                    let data: Settings = self.api.passwords_post("1.0/settings/get", vec![$server_setting]).await?;
                    Ok(data.$server_field.expect("server did not provide the asked setting"))
                }
            )*
            /// Note
            ///  - The client scope allows keys with up to 48 characters, excluding client.
            ///  - The client scope allows values with a maximum length of 128 characters
            ///  - The client scope is shared between all clients
            pub async fn client_setting<D: serde::de::DeserializeOwned>(&self, client_setting: ClientSettings) -> Result<Option<D>, crate::Error> {
                let mut data: std::collections::HashMap<String, Option<D>> = self.api.passwords_post("1.0/settings/get", vec![client_setting.name()]).await?;
                Ok(data.remove(&client_setting.name()).flatten())
            }
            /// Fetch setting (expected SettingVariant::Client) from it's name
            pub async fn from_variant(&self, variant: SettingVariant) -> Result<SettingValue, crate::Error> {
                match variant {
                    SettingVariant::Client => Err(crate::Error::InvalidSetting),
                    variant => {
                        let data: Settings = self.api.passwords_post("1.0/settings/get", vec![variant.name()]).await?;
                        Ok(data.to_values().pop().unwrap())
                    }
                }
            }
        }


        /// User Setting Values
        #[derive(Serialize, Deserialize, Debug)]
        pub enum $valued_user {
            $($user_variant($user_type),)*
        }

        impl $valued_user {
            /// Return the name of the setting
            pub fn kind(&self) -> $user {
                match self {
                    $(
                        Self::$user_variant(_) => $user::$user_variant,
                    )*
                }
            }
            $(
                /// Coerce the value of the setting to this setting
                pub fn $user_field(self) -> Result<$user_type, Self> {
                    match self {
                        Self::$user_variant(v) => Ok(v),
                        _ => Err(self),
                    }
                }
            )*
            pub fn from_variant(variant: $user, value: &str) -> Result<Self, ParseError> {
                match variant {
                    $(
                        $user::$user_variant => Ok($valued_user::$user_variant(value.parse()?)),
                    )*
                }
            }
        }

        impl Setting for $user {
            fn name(&self) -> String {
                match self {
                    $(Self::$user_variant => $user_setting,)*
                }.into()
            }
        }

        /// Server Setting Names
        #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash)]
        pub enum $server {
            $($server_variant,)*
        }

        impl std::str::FromStr for $server {
            type Err = &'static str;

            fn from_str(s: &str) -> Result<Self, Self::Err> {
                match s {
                    $(
                        $server_setting => Ok(Self::$server_variant),
                    )*
                        _ => Err("Unknown variant"),
                }
            }
        }

        /// Server Setting Values
        #[derive(Serialize, Deserialize, Debug)]
        pub enum $valued_server {
            $($server_variant($server_type),)*
        }
        impl $valued_server {
            /// Return the name of the setting
            pub fn kind(&self) -> $server {
                match self {
                    $(
                        Self::$server_variant(_) => $server::$server_variant,
                    )*
                }
            }
            $(
                /// Coerce the value of the setting to this setting
                pub fn $server_field(self) -> Result<$server_type, Self> {
                    match self {
                        Self::$server_variant(v) => Ok(v),
                        _ => Err(self),
                    }
                }
            )*
        }

        impl Setting for $server {
            fn name(&self) -> String {
                match self {
                    $(Self::$server_variant => $server_setting,)*
                }.into()
            }
        }

        /// The value of a Setting
        #[derive(Serialize, Deserialize, Debug)]
        pub enum SettingValue {
            $(
                $user_variant($user_type),
            )*
            $(
                $server_variant($server_type),
            )*
            Client { name: String, value: String }
        }
        /// Setting name
        #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Hash)]
        pub enum SettingVariant {
            $(
                $user_variant,
            )*
            $(
                $server_variant,
            )*
            Client,
        }
        impl SettingVariant {
            pub(crate) fn name(&self) -> &'static str {
                match self {
                    $(
                        Self::$user_variant => $user_setting,
                    )*
                    $(
                        Self::$server_variant => $server_setting,
                    )*
                    Self::Client => panic!("client has no name"),
                }
            }
        }
        impl std::str::FromStr for SettingVariant {
            type Err = &'static str;

            fn from_str(s: &str) -> Result<Self, Self::Err> {
                match s {
                    $(
                        $user_setting => Ok(Self::$user_variant),
                    )*
                    $(
                        $server_setting => Ok(Self::$server_variant),
                    )*
                        _ => Err("Unknown variant"),
                }
            }
        }

        impl From<$user> for SettingVariant {
            fn from(value: $user) -> Self {
                match value {
                    $(
                        $user::$user_variant => SettingVariant::$user_variant,
                    )*
                }
            }
        }
        impl From<$server> for SettingVariant {
            fn from(value: $server) -> Self {
                match value {
                    $(
                        $server::$server_variant => SettingVariant::$server_variant,
                    )*
                }
            }
        }

        impl From<$valued_user> for SettingValue {
            fn from(value: $valued_user) -> Self {
                match value {
                    $(
                        $valued_user::$user_variant(v) => SettingValue::$user_variant(v),
                    )*
                }
            }
        }
        impl From<$valued_server> for SettingValue {
            fn from(value: $valued_server) -> Self {
                match value {
                    $(
                        $valued_server::$server_variant(v) => SettingValue::$server_variant(v),
                    )*
                }
            }
        }

        #[derive(Serialize, Deserialize, Default, Debug)]
        /// Set the values of settings
        pub struct Settings {
            $(
                #[serde(skip_serializing_if = "Option::is_none", rename = $user_setting)]
                $user_field: Option<$user_type>,
            )*
            $(
                #[serde(skip_serializing_if = "Option::is_none", rename = $server_setting)]
                $server_field: Option<$server_type>,
            )*
        }

        #[derive(Serialize, Deserialize, Debug)]
        /// The value of all settings
        pub struct AllSettings {
            $(
                #[serde(rename = $user_setting)]
                $user_field: $user_type,
            )*
            $(
                #[serde(rename = $server_setting)]
                $server_field: $server_type,
            )*
        }

        impl Settings {
            pub(crate) fn to_values(self) -> Vec<SettingValue> {
                let mut settings = Vec::new();
                $(
                    if let Some(value) = self.$user_field {
                        settings.push($valued_user::$user_variant(value).into())
                    }
                )*
                $(
                    if let Some(value) = self.$server_field {
                        settings.push($valued_server::$server_variant(value).into())
                    }
                )*
                settings
            }
            /// Empty settings
            pub fn new() -> Self {
                Default::default()
            }
            $(
                /// Assign a value to this setting
                pub fn $user_field(mut self, value: $user_type) -> Self {
                    self.$user_field = Some(value);
                    self
                }
            )*
            pub fn set_user_value(mut self, setting: $valued_user) -> Self {
                match setting {
                    $(
                        $valued_user::$user_variant(v) => self.$user_field = Some(v),
                    )*
                }
                self
            }
        }
    };

    ( $($input:tt)*) => {
        settings!{
            @dollar[$] $($input)*
        }
    };
}

settings! {
    User = UserSettings(UserSettingValue), Server = ServerSettings(ServerSettingValue) {
        User: PasswordStrength(i8), password_strength => "user.password.generator.strength",
        User: PasswordContainsNumber(bool), password_contains_numbers => "user.password.generator.numbers",
        User: PasswordContainsSpecial(bool), password_contains_special => "user.password.generator.special",
        User: CheckForDuplicates(bool), check_for_duplicates => "user.password.security.duplicates",
        User: CheckForOldPasswords(i64), check_for_old_passwords => "user.password.security.age",
        User: NotifySecurityByMail(bool), notify_security_by_mail => "user.mail.security",
        User: NotifySharesByMail(bool), notify_shares_by_mail => "user.mail.shares",
        User: NotifySecurityByNotification(bool), notify_security_by_notification => "user.notification.security",
        User: NotifySharesByNotification(bool), notify_shares_by_notification => "user.notification.shares",
        User: NotifyErrorsByNotification(bool), notifiy_errors_by_notification => "user.notification.errors",
        User: ServerSideEncryption(i8), server_side_encryption => "user.encryption.sse",
        User: ClientSideEncryption(i8), client_side_encryption => "user.encryption.cse",
        User: SessionLifetime(u64), session_lifetime => "user.session.lifetime",
        Server: Version(String), version => "server.version",
        Server: BaseUrl(Url), base_url => "server.baseUrl",
        Server: BaseUrlWebDav(Url), base_url_web_dav => "server.baseUrl.webdav",
        Server: Sharing(bool), sharing => "server.sharing.enabled",
        Server: Resharing(bool), resharing => "server.sharing.resharing",
        Server: AutoComplete(bool), autocomplete => "server.sharing.autocomplete",
        Server: SharingTypes(Vec<String>), sharing_types => "server.sharing.types",
        Server: PrimaryColor(Color), primary_color => "server.theme.color.primary",
        Server: TextColor(Color), text_color => "server.theme.color.text",
        Server: BackgroundColor(Color), background_color => "server.theme.color.background",
        Server: BackgroundTheme(Url), background_theme => "server.theme.background",
        Server: Logo(Url), logo => "server.theme.logo",
        Server: Label(String), label => "server.theme.label",
        Server: AppIcon(Url), app_icon => "server.theme.app.icon",
        Server: FolderIcon(Url), folder_icon => "server.theme.folder.icon",
        //Server: ManualUrl(Url), manual_url => "server.manual.url",
    }
}
impl WritableSetting for UserSettings {}

impl Setting for ClientSettings {
    fn name(&self) -> String {
        format!("client.{}", self.name)
    }
}

/// An arbitrary client setting
pub struct ClientSettings {
    pub name: String,
}