BlueGit

timfa posprint

Files

posprint / src / config.rs

config.rs

config.rs 7.2 KiB Download Raw
1//! Persisted app preferences (trusted URL origins, default page width).
2
3use std::fs;
4use std::path::PathBuf;
5
6use serde::{Deserialize, Serialize};
7
8const CONFIG_VERSION: u32 = 1;
9
10#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
11pub struct AppConfig {
12 #[serde(default = "default_config_version")]
13 pub version: u32,
14 /// Default paper width for **New** documents (mm).
15 #[serde(default = "default_page_width_mm")]
16 pub default_page_width_mm: f32,
17 /// Hostnames allowed to use `noconfirm=1` without asking again.
18 #[serde(default)]
19 pub trusted_origins: Vec<String>,
20 /// Last printer that printed successfully (`serial:…`, `winspool:…`, `usb:vid:pid`, or `manual:…`).
21 #[serde(default)]
22 pub last_printer_key: Option<String>,
23}
24
25fn default_config_version() -> u32 {
26 CONFIG_VERSION
27}
28
29fn default_page_width_mm() -> f32 {
30 80.0
31}
32
33impl Default for AppConfig {
34 fn default() -> Self {
35 Self {
36 version: CONFIG_VERSION,
37 default_page_width_mm: default_page_width_mm(),
38 trusted_origins: Vec::new(),
39 last_printer_key: None,
40 }
41 }
42}
43
44impl AppConfig {
45 pub fn load() -> Self {
46 Self::load_from_path(&config_path())
47 }
48
49 pub fn load_from_path(path: &std::path::Path) -> Self {
50 match fs::read_to_string(path) {
51 Ok(text) => match serde_json::from_str::<AppConfig>(&text) {
52 Ok(mut cfg) => {
53 cfg.normalize();
54 cfg
55 }
56 Err(_) => Self::default(),
57 },
58 Err(_) => Self::default(),
59 }
60 }
61
62 pub fn save(&self) -> Result<(), String> {
63 self.save_to_path(&config_path())
64 }
65
66 pub fn save_to_path(&self, path: &std::path::Path) -> Result<(), String> {
67 if let Some(parent) = path.parent() {
68 fs::create_dir_all(parent).map_err(|e| e.to_string())?;
69 }
70 let mut cfg = self.clone();
71 cfg.normalize();
72 let json = serde_json::to_string_pretty(&cfg).map_err(|e| e.to_string())?;
73 fs::write(path, json).map_err(|e| e.to_string())
74 }
75
76 pub fn is_trusted(&self, origin: &str) -> bool {
77 let Some(host) = normalize_origin(origin) else {
78 return false;
79 };
80 self.trusted_origins.iter().any(|o| o == &host)
81 }
82
83 pub fn trust_origin(&mut self, origin: &str) -> bool {
84 let Some(host) = normalize_origin(origin) else {
85 return false;
86 };
87 if !self.trusted_origins.iter().any(|o| o == &host) {
88 self.trusted_origins.push(host);
89 self.trusted_origins.sort();
90 }
91 true
92 }
93
94 pub fn revoke_origin(&mut self, origin: &str) {
95 let Some(host) = normalize_origin(origin) else {
96 return;
97 };
98 self.trusted_origins.retain(|o| o != &host);
99 }
100
101 pub fn remember_printer(&mut self, key: impl Into<String>) {
102 let key = key.into();
103 if key.is_empty() {
104 return;
105 }
106 self.last_printer_key = Some(key);
107 }
108
109 fn normalize(&mut self) {
110 self.version = CONFIG_VERSION;
111 if !self.default_page_width_mm.is_finite() || self.default_page_width_mm < 40.0 {
112 self.default_page_width_mm = 40.0;
113 } else if self.default_page_width_mm > 120.0 {
114 self.default_page_width_mm = 120.0;
115 }
116 let mut hosts: Vec<String> = self
117 .trusted_origins
118 .iter()
119 .filter_map(|o| normalize_origin(o))
120 .collect();
121 hosts.sort();
122 hosts.dedup();
123 self.trusted_origins = hosts;
124 if let Some(key) = &self.last_printer_key {
125 let trimmed = key.trim();
126 if trimmed.is_empty() {
127 self.last_printer_key = None;
128 } else if trimmed != key.as_str() {
129 self.last_printer_key = Some(trimmed.to_string());
130 }
131 }
132 }
133}
134
135/// Config file path: `%APPDATA%/posprint/config.json` (Windows) or
136/// `$XDG_CONFIG_HOME/posprint/config.json` / `~/.config/posprint/config.json` (Unix).
137pub fn config_path() -> PathBuf {
138 #[cfg(windows)]
139 {
140 let base = std::env::var_os("APPDATA")
141 .map(PathBuf::from)
142 .unwrap_or_else(|| PathBuf::from("."));
143 base.join("posprint").join("config.json")
144 }
145 #[cfg(not(windows))]
146 {
147 let base = std::env::var_os("XDG_CONFIG_HOME")
148 .map(PathBuf::from)
149 .or_else(|| {
150 std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config"))
151 })
152 .unwrap_or_else(|| PathBuf::from("."));
153 base.join("posprint").join("config.json")
154 }
155}
156
157/// Normalize a caller-supplied origin to a lowercase hostname.
158/// Accepts `example.com`, `https://example.com/path`, `http://localhost:3000`.
159pub fn normalize_origin(raw: &str) -> Option<String> {
160 let s = raw.trim();
161 if s.is_empty() {
162 return None;
163 }
164 let without_scheme = s
165 .strip_prefix("https://")
166 .or_else(|| s.strip_prefix("http://"))
167 .or_else(|| s.strip_prefix("HTTPS://"))
168 .or_else(|| s.strip_prefix("HTTP://"))
169 .unwrap_or(s);
170 let host_port = without_scheme.split('/').next()?.trim();
171 if host_port.is_empty() {
172 return None;
173 }
174 // Drop port for trust matching (example.com:443 → example.com).
175 let host = host_port.split(':').next()?.trim();
176 if host.is_empty() {
177 return None;
178 }
179 Some(host.to_ascii_lowercase())
180}
181
182#[cfg(test)]
183mod tests {
184 use super::*;
185
186 #[test]
187 fn normalize_strips_scheme_path_and_port() {
188 assert_eq!(
189 normalize_origin("https://Shop.Example.com/checkout").as_deref(),
190 Some("shop.example.com")
191 );
192 assert_eq!(
193 normalize_origin("http://localhost:5173/").as_deref(),
194 Some("localhost")
195 );
196 assert_eq!(normalize_origin("example.com").as_deref(), Some("example.com"));
197 assert_eq!(normalize_origin(" ").as_deref(), None);
198 }
199
200 #[test]
201 fn trust_and_revoke_roundtrip() {
202 let mut cfg = AppConfig::default();
203 assert!(!cfg.is_trusted("https://a.example"));
204 assert!(cfg.trust_origin("https://a.example/x"));
205 assert!(cfg.is_trusted("a.example"));
206 assert!(cfg.is_trusted("HTTPS://A.Example"));
207 cfg.revoke_origin("a.example");
208 assert!(!cfg.is_trusted("a.example"));
209 }
210
211 #[test]
212 fn save_load_roundtrip_in_temp_dir() {
213 let dir = tempfile::tempdir().unwrap();
214 let path = dir.path().join("posprint").join("config.json");
215 let mut cfg = AppConfig::default();
216 cfg.default_page_width_mm = 58.0;
217 cfg.trust_origin("pos.example");
218 cfg.remember_printer("winspool:POS-58");
219 cfg.save_to_path(&path).unwrap();
220
221 let loaded = AppConfig::load_from_path(&path);
222 assert_eq!(loaded.default_page_width_mm, 58.0);
223 assert!(loaded.is_trusted("pos.example"));
224 assert_eq!(loaded.last_printer_key.as_deref(), Some("winspool:POS-58"));
225 }
226}