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
use crate::serde_helpers::option_pipe_separated_to_vec;
use crate::{MediaContainer, PlexApiError};
use std::collections::HashMap;
use thiserror::Error;

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(all(test, feature = "test_new_attributes"), serde(deny_unknown_fields))]
#[serde(rename_all = "camelCase")]
pub struct SettingsMediaContainer {
    #[serde(
        rename = "Setting",
        deserialize_with = "deserialize_settings_as_hashmap"
    )]
    settings: HashMap<String, Setting>,
    #[serde(flatten)]
    media_container: MediaContainer,
    #[serde(skip)]
    updated: HashMap<String, Setting>,
}

impl SettingsMediaContainer {
    pub fn get(&self, name: &str) -> crate::Result<&Setting> {
        if self.updated.contains_key(name) {
            Ok(&self.updated[name])
        } else if self.settings.contains_key(name) {
            Ok(&self.settings[name])
        } else {
            Err(PlexApiError::UnknownSettingRequested {
                key: String::from(name),
                known: self
                    .settings
                    .keys()
                    .map(String::from)
                    .collect::<Vec<String>>()
                    .join(", "),
            })
        }
    }

    pub fn set(&mut self, name: &str, value: SettingValue) -> crate::Result<()> {
        match self.settings.get(name) {
            Some(current_value) => {
                let mut new_value = current_value.clone();
                if let Err(e) = new_value.set(value) {
                    Err(e)
                } else {
                    self.updated.insert(String::from(name), new_value);
                    Ok(())
                }
            }
            None => Err(PlexApiError::UnknownSettingRequested {
                key: String::from(name),
                known: self
                    .settings
                    .keys()
                    .map(String::from)
                    .collect::<Vec<String>>()
                    .join(", "),
            }),
        }
    }

    pub fn get_changed(&self) -> &HashMap<String, Setting> {
        &self.updated
    }
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(all(test, feature = "test_new_attributes"), serde(deny_unknown_fields))]
pub(crate) struct SettingsMediaContainerOuter {
    #[serde(rename = "MediaContainer")]
    media_container: SettingsMediaContainer,
}

impl From<SettingsMediaContainerOuter> for SettingsMediaContainer {
    fn from(mc: SettingsMediaContainerOuter) -> Self {
        mc.media_container
    }
}

// TODO: enable `serde(deny_unknown_fields)`
#[derive(Debug, Deserialize, Clone)]
pub struct Setting {
    id: String,
    label: String,
    summary: String,
    hidden: bool,
    advanced: bool,
    group: String,
    #[serde(flatten)]
    payload: Payload,
}

impl Setting {
    fn set(&mut self, new_value: SettingValue) -> crate::Result<()> {
        self.payload.set(new_value)
    }

    pub fn get_id(&self) -> &str {
        &self.id
    }

    pub fn get_value(&self) -> SettingValue {
        SettingValue::from(&self.payload)
    }
}

#[derive(Error, Debug)]
pub enum SettingParsingError {
    #[error("Provided string incorrectly formatted")]
    IncorrectFormat,
    #[error("Unable to convert provided key to integer: {source}")]
    UnableToParseInt {
        #[from]
        source: std::num::ParseIntError,
    },
}

#[derive(Debug, Clone)]
pub struct SettingEnumValueString(String, String);

impl std::str::FromStr for SettingEnumValueString {
    type Err = SettingParsingError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let value: Vec<_> = s.split(':').collect();

        match value.len() {
            1 => Ok(SettingEnumValueString(String::from(s), String::from(s))),
            2 => Ok(SettingEnumValueString(
                String::from(value[0]),
                String::from(value[1]),
            )),
            _ => Err(SettingParsingError::IncorrectFormat),
        }
    }
}

#[derive(Debug, Clone)]
pub struct SettingEnumValueInt(i32, String);

impl std::str::FromStr for SettingEnumValueInt {
    type Err = SettingParsingError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let value: Vec<_> = s.split(':').collect();

        match value.len() {
            1 => Ok(SettingEnumValueInt(
                String::from(s).parse()?,
                String::from(s),
            )),
            2 => Ok(SettingEnumValueInt(
                value[0].parse()?,
                String::from(value[1]),
            )),
            _ => Err(SettingParsingError::IncorrectFormat),
        }
    }
}

#[derive(Debug, Deserialize, Clone)]
#[serde(tag = "type", rename_all = "lowercase")]
pub(crate) enum Payload {
    Bool {
        default: bool,
        value: bool,
    },
    Int {
        default: i32,
        value: i32,
        #[serde(
            rename = "enumValues",
            deserialize_with = "option_pipe_separated_to_vec",
            default
        )]
        enum_values: Option<Vec<SettingEnumValueInt>>,
    },
    Text {
        default: String,
        value: String,
        #[serde(
            rename = "enumValues",
            deserialize_with = "option_pipe_separated_to_vec",
            default
        )]
        enum_values: Option<Vec<SettingEnumValueString>>,
    },
    Double {
        // TODO: use f64, current problem that `TranscoderH264MinimumCRF` stored as string in JSON
        default: String,
        value: String,
    },
}

impl Payload {
    fn set(&mut self, new_value: SettingValue) -> crate::Result<()> {
        match self {
            Payload::Bool {
                value: ref mut current_value,
                ..
            } => match new_value {
                SettingValue::Bool(value) => {
                    *current_value = value;
                    Ok(())
                }
                _ => Err(PlexApiError::ExpectedSettingValueBool {
                    provided: new_value,
                }),
            },
            Payload::Int {
                value: ref mut current_value,
                ..
            } => match new_value {
                SettingValue::Int(value) => {
                    *current_value = value;
                    Ok(())
                }
                _ => Err(PlexApiError::ExpectedSettingValueInt {
                    provided: new_value,
                }),
            },
            Payload::Text {
                value: ref mut current_value,
                ..
            } => match new_value {
                SettingValue::Text(value) => {
                    *current_value = value;
                    Ok(())
                }
                _ => Err(PlexApiError::ExpectedSettingValueText {
                    provided: new_value,
                }),
            },
            Payload::Double {
                value: ref mut current_value,
                ..
            } => match new_value {
                SettingValue::Double(value) => {
                    *current_value = value.to_string();
                    Ok(())
                }
                _ => Err(PlexApiError::ExpectedSettingValueDouble {
                    provided: new_value,
                }),
            },
        }
    }
}

#[derive(Debug)]
pub enum SettingValue {
    Bool(bool),
    Int(i32),
    Text(String),
    Double(f64),
}

impl From<bool> for SettingValue {
    fn from(v: bool) -> Self {
        SettingValue::Bool(v)
    }
}

impl From<i32> for SettingValue {
    fn from(v: i32) -> Self {
        SettingValue::Int(v)
    }
}

impl From<String> for SettingValue {
    fn from(v: String) -> Self {
        SettingValue::Text(v)
    }
}

impl From<&str> for SettingValue {
    fn from(v: &str) -> Self {
        SettingValue::Text(String::from(v))
    }
}

impl From<f64> for SettingValue {
    fn from(v: f64) -> Self {
        SettingValue::Double(v)
    }
}

impl From<&Payload> for SettingValue {
    fn from(v: &Payload) -> Self {
        match v {
            Payload::Bool { value, .. } => SettingValue::Bool(*value),
            Payload::Int { value, .. } => SettingValue::Int(*value),
            Payload::Text { value, .. } => SettingValue::Text(value.to_string()),
            Payload::Double { value, .. } => SettingValue::Double(value.parse().unwrap()),
        }
    }
}

impl ToString for SettingValue {
    fn to_string(&self) -> String {
        match self {
            SettingValue::Bool(v) => v.to_string(),
            SettingValue::Int(v) => v.to_string(),
            SettingValue::Text(v) => v.to_string(),
            SettingValue::Double(v) => v.to_string(),
        }
    }
}

pub fn deserialize_settings_as_hashmap<'de, D>(
    deserializer: D,
) -> Result<HashMap<String, Setting>, D::Error>
where
    D: serde::de::Deserializer<'de>,
{
    use serde::Deserialize;

    let mut map = HashMap::new();
    for item in Vec::<Setting>::deserialize(deserializer)? {
        map.insert((&item.id).to_string(), item);
    }
    Ok(map)
}