| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
use std::path::PathBuf; |
| 7 |
|
| 8 |
use serde::{Deserialize, Serialize}; |
| 9 |
use tauri::{AppHandle, Manager}; |
| 10 |
use tracing::instrument; |
| 11 |
|
| 12 |
use super::ApiError; |
| 13 |
|
| 14 |
const PREFERENCES_FILE: &str = "preferences.json"; |
| 15 |
|
| 16 |
#[derive(Debug, Clone, Serialize, Deserialize)] |
| 17 |
#[serde(rename_all = "camelCase")] |
| 18 |
pub struct Preferences { |
| 19 |
pub update_check_on_launch: bool, |
| 20 |
} |
| 21 |
|
| 22 |
impl Default for Preferences { |
| 23 |
fn default() -> Self { |
| 24 |
Self { update_check_on_launch: true } |
| 25 |
} |
| 26 |
} |
| 27 |
|
| 28 |
fn preferences_path(app: &AppHandle) -> Result<PathBuf, ApiError> { |
| 29 |
let dir = app.path().app_config_dir() |
| 30 |
.map_err(|e| ApiError::internal(format!("Resolve app config dir: {e}")))?; |
| 31 |
std::fs::create_dir_all(&dir) |
| 32 |
.map_err(|e| ApiError::internal(format!("Create app config dir: {e}")))?; |
| 33 |
Ok(dir.join(PREFERENCES_FILE)) |
| 34 |
} |
| 35 |
|
| 36 |
pub fn load(app: &AppHandle) -> Preferences { |
| 37 |
let Ok(path) = preferences_path(app) else { return Preferences::default(); }; |
| 38 |
let Ok(bytes) = std::fs::read(&path) else { return Preferences::default(); }; |
| 39 |
serde_json::from_slice(&bytes).unwrap_or_default() |
| 40 |
} |
| 41 |
|
| 42 |
fn save(app: &AppHandle, prefs: &Preferences) -> Result<(), ApiError> { |
| 43 |
let path = preferences_path(app)?; |
| 44 |
let json = serde_json::to_vec_pretty(prefs) |
| 45 |
.map_err(|e| ApiError::internal(format!("Serialize preferences: {e}")))?; |
| 46 |
std::fs::write(&path, json) |
| 47 |
.map_err(|e| ApiError::internal(format!("Write preferences: {e}")))?; |
| 48 |
Ok(()) |
| 49 |
} |
| 50 |
|
| 51 |
#[tauri::command] |
| 52 |
#[instrument(skip_all)] |
| 53 |
pub fn get_preferences(app: AppHandle) -> Result<Preferences, ApiError> { |
| 54 |
Ok(load(&app)) |
| 55 |
} |
| 56 |
|
| 57 |
#[tauri::command] |
| 58 |
#[instrument(skip_all)] |
| 59 |
pub fn set_update_check_on_launch(app: AppHandle, enabled: bool) -> Result<(), ApiError> { |
| 60 |
let mut prefs = load(&app); |
| 61 |
prefs.update_check_on_launch = enabled; |
| 62 |
save(&app, &prefs) |
| 63 |
} |
| 64 |
|