BlueGit

timfa posprint

Files

posprint / src / image_load.rs

image_load.rs

image_load.rs 4.7 KiB Download Raw
1//! Load images from local paths or `http(s)://` URLs.
2
3use std::collections::HashMap;
4use std::io::Read;
5use std::path::{Path, PathBuf};
6use std::sync::{Mutex, OnceLock};
7use std::time::Duration;
8
9use image::DynamicImage;
10
11const MAX_DOWNLOAD_BYTES: u64 = 5 * 1024 * 1024;
12const DOWNLOAD_TIMEOUT_SECS: u64 = 10;
13
14#[derive(Debug)]
15pub enum ImageLoadError {
16 Message(String),
17}
18
19impl std::fmt::Display for ImageLoadError {
20 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21 match self {
22 Self::Message(m) => write!(f, "{m}"),
23 }
24 }
25}
26
27impl std::error::Error for ImageLoadError {}
28
29fn cache() -> std::sync::MutexGuard<'static, HashMap<String, Vec<u8>>> {
30 static CACHE: OnceLock<Mutex<HashMap<String, Vec<u8>>>> = OnceLock::new();
31 CACHE
32 .get_or_init(|| Mutex::new(HashMap::new()))
33 .lock()
34 .unwrap_or_else(|e| e.into_inner())
35}
36
37pub fn is_http_url(path: &str) -> bool {
38 let lower = path.trim().to_ascii_lowercase();
39 lower.starts_with("https://") || lower.starts_with("http://")
40}
41
42/// Open a local image path or download an `http`/`https` URL (cached per process).
43pub fn load_image(path: &str, base_dir: Option<&Path>) -> Result<DynamicImage, ImageLoadError> {
44 let path = path.trim();
45 if path.is_empty() {
46 return Err(ImageLoadError::Message("image path is empty".into()));
47 }
48
49 if is_http_url(path) {
50 let bytes = download_cached(path)?;
51 return image::load_from_memory(&bytes)
52 .map_err(|e| ImageLoadError::Message(format!("decode {path}: {e}")));
53 }
54
55 if path.contains("://") {
56 return Err(ImageLoadError::Message(format!(
57 "unsupported image URL scheme (only http/https): {path}"
58 )));
59 }
60
61 let resolved = resolve_image_path(path, base_dir);
62 image::open(&resolved).map_err(|e| ImageLoadError::Message(format!("image {path}: {e}")))
63}
64
65fn download_cached(url: &str) -> Result<Vec<u8>, ImageLoadError> {
66 {
67 let guard = cache();
68 if let Some(bytes) = guard.get(url) {
69 return Ok(bytes.clone());
70 }
71 }
72
73 let bytes = download(url)?;
74 cache().insert(url.to_string(), bytes.clone());
75 Ok(bytes)
76}
77
78fn download(url: &str) -> Result<Vec<u8>, ImageLoadError> {
79 // Accept certificates the rustls/webpki bundle does not know (corporate CAs,
80 // incomplete chains). Remote logos on POS templates often live on such hosts.
81 let tls = native_tls::TlsConnector::builder()
82 .danger_accept_invalid_certs(true)
83 .danger_accept_invalid_hostnames(true)
84 .build()
85 .map_err(|e| ImageLoadError::Message(format!("tls setup: {e}")))?;
86
87 let agent = ureq::AgentBuilder::new()
88 .tls_connector(std::sync::Arc::new(tls))
89 .timeout_connect(Duration::from_secs(DOWNLOAD_TIMEOUT_SECS))
90 .timeout_read(Duration::from_secs(DOWNLOAD_TIMEOUT_SECS))
91 .build();
92
93 let response = agent
94 .get(url)
95 .call()
96 .map_err(|e| ImageLoadError::Message(format!("download {url}: {e}")))?;
97
98 let len = response
99 .header("Content-Length")
100 .and_then(|v| v.parse::<u64>().ok());
101 if let Some(len) = len {
102 if len > MAX_DOWNLOAD_BYTES {
103 return Err(ImageLoadError::Message(format!(
104 "download {url}: Content-Length {len} exceeds {MAX_DOWNLOAD_BYTES} byte limit"
105 )));
106 }
107 }
108
109 let mut reader = response.into_reader().take(MAX_DOWNLOAD_BYTES + 1);
110 let mut bytes = Vec::new();
111 reader
112 .read_to_end(&mut bytes)
113 .map_err(|e| ImageLoadError::Message(format!("download {url}: {e}")))?;
114 if bytes.len() as u64 > MAX_DOWNLOAD_BYTES {
115 return Err(ImageLoadError::Message(format!(
116 "download {url}: response exceeds {MAX_DOWNLOAD_BYTES} byte limit"
117 )));
118 }
119 Ok(bytes)
120}
121
122pub fn resolve_image_path(path: &str, base_dir: Option<&Path>) -> PathBuf {
123 let p = Path::new(path);
124 if p.is_absolute() {
125 p.to_path_buf()
126 } else if let Some(base) = base_dir {
127 base.join(p)
128 } else {
129 p.to_path_buf()
130 }
131}
132
133#[cfg(test)]
134mod tests {
135 use super::*;
136
137 #[test]
138 fn detects_http_urls() {
139 assert!(is_http_url("https://example.com/a.png"));
140 assert!(is_http_url("http://example.com/a.png"));
141 assert!(!is_http_url("logo.png"));
142 assert!(!is_http_url("file:///tmp/a.png"));
143 }
144
145 #[test]
146 fn rejects_non_http_schemes() {
147 let err = load_image("file:///tmp/x.png", None).unwrap_err();
148 assert!(err.to_string().contains("unsupported"));
149 }
150}