BlueGit

timfa posprint

Files

posprint / src / config.rs

config.rs

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