1use crate::error::SettingsError;
2use crate::schema::SettingsSchema;
3use chrono::Utc;
4use serde::{Deserialize, Serialize};
5use sha2::Digest;
6
7#[derive(Serialize, Deserialize, Clone, Debug)]
9pub struct SettingsBundle<T> {
10 pub format_version: u32,
11 pub schema_version: u32,
12 pub app_id: String,
13 pub exported_at: i64,
14 #[serde(default, skip_serializing_if = "Option::is_none")]
15 pub device_info: Option<DeviceInfo>,
16 pub settings: T,
17 pub settings_raw: String,
18 pub checksum: String,
19}
20
21#[derive(Serialize, Deserialize, Clone, Debug, Default)]
23pub struct DeviceInfo {
24 pub platform: String,
25 pub os_version: String,
26 pub app_version: String,
27 #[serde(default, skip_serializing_if = "Option::is_none")]
28 pub device_model: Option<String>,
29 #[serde(default, skip_serializing_if = "Option::is_none")]
30 pub locale: Option<String>,
31}
32
33#[derive(Clone, Debug)]
35pub struct ImportOptions {
36 pub validate_app_id: bool,
37 pub validate_checksum: bool,
38 pub merge_mode: MergeMode,
39}
40
41impl Default for ImportOptions {
42 fn default() -> Self {
43 Self {
44 validate_app_id: true,
45 validate_checksum: true,
46 merge_mode: MergeMode::Overwrite,
47 }
48 }
49}
50
51#[derive(Clone, Debug, PartialEq)]
53pub enum MergeMode {
54 Overwrite,
55 KeepExisting,
56 UpdateOnly,
57}
58
59#[derive(Clone, Debug, PartialEq)]
61pub enum BackupIssue {
62 ParseError(String),
63 AppIdMismatch { expected: String, actual: String },
64 VersionTooNew { actual: u32, supported: u32 },
65}
66
67#[derive(Clone, Debug)]
69pub struct BackupValidationResult {
70 pub is_valid: bool,
71 pub settings_count: usize,
72 pub schema_version: u32,
73 pub exported_at: i64,
74 pub issues: Vec<BackupIssue>,
75 pub device_info: Option<DeviceInfo>,
76}
77
78pub struct SettingsBackupManager {
80 app_id: String,
81 schema_version: u32,
82 device_info_provider: Option<Box<dyn Fn() -> DeviceInfo + Send + Sync>>,
83}
84
85impl SettingsBackupManager {
86 pub fn new(app_id: impl Into<String>, schema_version: u32) -> Self {
87 Self {
88 app_id: app_id.into(),
89 schema_version,
90 device_info_provider: None,
91 }
92 }
93
94 pub fn with_device_info(
96 mut self,
97 provider: impl Fn() -> DeviceInfo + Send + Sync + 'static,
98 ) -> Self {
99 self.device_info_provider = Some(Box::new(provider));
100 self
101 }
102
103 pub fn export<T: SettingsSchema>(&self, settings: &T) -> Result<String, SettingsError> {
105 let settings_raw = serde_json::to_string(settings)?;
106 let checksum = hex::encode(sha2::Sha256::digest(settings_raw.as_bytes()));
107
108 let bundle = SettingsBundle {
109 format_version: 2,
110 schema_version: self.schema_version,
111 app_id: self.app_id.clone(),
112 exported_at: Utc::now().timestamp_millis(),
113 device_info: self.device_info_provider.as_ref().map(|p| p()),
114 settings: settings.clone(),
115 settings_raw,
116 checksum,
117 };
118
119 serde_json::to_string_pretty(&bundle).map_err(SettingsError::Serialization)
120 }
121
122 pub fn import<T: SettingsSchema>(
124 &self,
125 json_str: &str,
126 options: &ImportOptions,
127 ) -> Result<T, SettingsError> {
128 let bundle: SettingsBundle<T> =
129 serde_json::from_str(json_str).map_err(|e| SettingsError::ParseError(e.to_string()))?;
130
131 if options.validate_app_id && bundle.app_id != self.app_id {
132 return Err(SettingsError::AppMismatch {
133 expected: self.app_id.clone(),
134 actual: bundle.app_id,
135 });
136 }
137
138 if bundle.schema_version > self.schema_version {
139 return Err(SettingsError::VersionTooNew {
140 actual: bundle.schema_version,
141 supported: self.schema_version,
142 });
143 }
144
145 if options.validate_checksum {
146 let expected = hex::encode(sha2::Sha256::digest(bundle.settings_raw.as_bytes()));
147 if bundle.checksum != expected {
148 return Err(SettingsError::ChecksumMismatch);
149 }
150 }
151
152 Ok(bundle.settings)
153 }
154
155 pub fn validate(&self, json_str: &str) -> BackupValidationResult {
157 let parse_result: Result<SettingsBundle<serde_json::Value>, _> =
158 serde_json::from_str(json_str);
159
160 match parse_result {
161 Err(e) => BackupValidationResult {
162 is_valid: false,
163 settings_count: 0,
164 schema_version: 0,
165 exported_at: 0,
166 issues: vec![BackupIssue::ParseError(e.to_string())],
167 device_info: None,
168 },
169 Ok(bundle) => {
170 let mut issues = Vec::new();
171
172 if bundle.app_id != self.app_id {
173 issues.push(BackupIssue::AppIdMismatch {
174 expected: self.app_id.clone(),
175 actual: bundle.app_id,
176 });
177 }
178
179 if bundle.schema_version > self.schema_version {
180 issues.push(BackupIssue::VersionTooNew {
181 actual: bundle.schema_version,
182 supported: self.schema_version,
183 });
184 }
185
186 let settings_count = bundle.settings.as_object().map(|o| o.len()).unwrap_or(0);
187
188 BackupValidationResult {
189 is_valid: issues.is_empty(),
190 settings_count,
191 schema_version: bundle.schema_version,
192 exported_at: bundle.exported_at,
193 issues,
194 device_info: bundle.device_info,
195 }
196 }
197 }
198 }
199}
200
201#[cfg(test)]
202mod tests {
203 use super::*;
204
205 #[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
206 struct TestSettings {
207 dark_mode: bool,
208 font_size: f32,
209 }
210
211 impl SettingsSchema for TestSettings {
212 fn schema_version(&self) -> u32 {
213 1
214 }
215 fn app_id(&self) -> &'static str {
216 "test_app"
217 }
218 fn fields(&self) -> Vec<crate::field::FieldMeta> {
219 vec![]
220 }
221 fn get_field_value(&self, name: &str) -> Result<serde_json::Value, SettingsError> {
222 match name {
223 "dark_mode" => Ok(serde_json::json!(self.dark_mode)),
224 "font_size" => Ok(serde_json::json!(self.font_size)),
225 _ => Err(SettingsError::UnknownField(name.into())),
226 }
227 }
228 fn set_field_value(
229 &mut self,
230 name: &str,
231 value: serde_json::Value,
232 ) -> Result<(), SettingsError> {
233 match name {
234 "dark_mode" => {
235 self.dark_mode = serde_json::from_value(value)?;
236 Ok(())
237 }
238 "font_size" => {
239 self.font_size = serde_json::from_value(value)?;
240 Ok(())
241 }
242 _ => Err(SettingsError::UnknownField(name.into())),
243 }
244 }
245 }
246
247 #[test]
248 fn test_export_import_roundtrip() {
249 let manager = SettingsBackupManager::new("test_app", 1);
250 let settings = TestSettings {
251 dark_mode: true,
252 font_size: 24.0,
253 };
254 let exported = manager.export(&settings).unwrap();
255 let imported: TestSettings = manager
256 .import(&exported, &ImportOptions::default())
257 .unwrap();
258 assert_eq!(settings, imported);
259 }
260
261 #[test]
262 fn test_app_id_mismatch() {
263 let manager = SettingsBackupManager::new("test_app", 1);
264 let other_manager = SettingsBackupManager::new("other_app", 1);
265 let settings = TestSettings::default();
266 let exported = other_manager.export(&settings).unwrap();
267 let result: Result<TestSettings, _> = manager.import(&exported, &ImportOptions::default());
268 assert!(matches!(result, Err(SettingsError::AppMismatch { .. })));
269 }
270
271 #[test]
272 fn test_validate_typed_issues() {
273 let manager = SettingsBackupManager::new("test_app", 1);
274 let exported = manager.export(&TestSettings::default()).unwrap();
275 let result = manager.validate(&exported);
276 assert!(result.is_valid);
277 assert!(result.issues.is_empty());
278 }
279
280 #[test]
281 fn test_validate_mismatch() {
282 let other = SettingsBackupManager::new("other_app", 1);
283 let exported = other.export(&TestSettings::default()).unwrap();
284 let manager = SettingsBackupManager::new("test_app", 1);
285 let result = manager.validate(&exported);
286 assert!(!result.is_valid);
287 assert!(matches!(
288 &result.issues[0],
289 BackupIssue::AppIdMismatch { .. }
290 ));
291 }
292}