BlueGit

timfa posprint

Files

posprint / src / protocol_url.rs

protocol_url.rs

protocol_url.rs 9.4 KiB Download Raw
1//! `posprint://` URLs that embed a compressed `.pos` document (magnet-style).
2
3use std::fmt;
4use std::io::{Read, Write};
5
6use base64::engine::general_purpose::URL_SAFE_NO_PAD;
7use base64::Engine;
8use flate2::read::DeflateDecoder;
9use flate2::write::DeflateEncoder;
10use flate2::Compression;
11
12use crate::io::PosFile;
13
14/// Soft warning threshold for cross-platform protocol handoff (~Windows cmdline limit).
15pub const WARN_URL_LEN: usize = 7000;
16
17#[derive(Debug)]
18pub enum ProtocolUrlError {
19 NotPosprintUrl,
20 UnsupportedVersion(String),
21 MissingPayload,
22 InvalidEncoding(String),
23 Base64(String),
24 Inflate(String),
25 Json(String),
26 UnsupportedPosVersion(u32),
27}
28
29impl fmt::Display for ProtocolUrlError {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31 match self {
32 Self::NotPosprintUrl => write!(f, "not a posprint:// URL"),
33 Self::UnsupportedVersion(v) => {
34 write!(f, "unsupported URL version '{v}' (expected 1)")
35 }
36 Self::MissingPayload => write!(f, "missing document payload (d=)"),
37 Self::InvalidEncoding(e) => write!(f, "invalid URL / percent-encoding: {e}"),
38 Self::Base64(e) => write!(f, "invalid base64 payload: {e}"),
39 Self::Inflate(e) => write!(f, "decompression failed: {e}"),
40 Self::Json(e) => write!(f, "invalid .pos JSON: {e}"),
41 Self::UnsupportedPosVersion(v) => write!(f, "unsupported .pos version {v}"),
42 }
43 }
44}
45
46impl std::error::Error for ProtocolUrlError {}
47
48impl From<serde_json::Error> for ProtocolUrlError {
49 fn from(value: serde_json::Error) -> Self {
50 Self::Json(value.to_string())
51 }
52}
53
54/// Decoded `posprint://` launch request.
55#[derive(Debug, Clone, PartialEq)]
56pub struct PosprintLaunch {
57 pub file: PosFile,
58 /// When true, print without waiting for the Print button.
59 pub noconfirm: bool,
60}
61
62/// Optional extras when encoding a URL.
63#[derive(Debug, Clone, Default)]
64pub struct EncodeOptions {
65 pub noconfirm: bool,
66}
67
68/// True when `s` looks like a `posprint:` / `posprint://` protocol URL.
69pub fn is_posprint_url(s: &str) -> bool {
70 let s = s.trim();
71 let lower = s.to_ascii_lowercase();
72 lower.starts_with("posprint://") || lower.starts_with("posprint:")
73}
74
75/// Encode a `.pos` file as `posprint://print?v=1&d=…` (raw deflate + base64url, no padding).
76pub fn encode_posprint_url(file: &PosFile) -> Result<String, ProtocolUrlError> {
77 encode_posprint_url_with_options(file, &EncodeOptions::default())
78}
79
80/// Encode with optional `noconfirm` query parameter.
81pub fn encode_posprint_url_with_options(
82 file: &PosFile,
83 options: &EncodeOptions,
84) -> Result<String, ProtocolUrlError> {
85 let json = serde_json::to_vec(file)?;
86 let mut encoder = DeflateEncoder::new(Vec::new(), Compression::best());
87 encoder
88 .write_all(&json)
89 .map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?;
90 let compressed = encoder
91 .finish()
92 .map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?;
93 let b64 = URL_SAFE_NO_PAD.encode(compressed);
94 let mut url = format!("posprint://print?v=1&d={b64}");
95 if options.noconfirm {
96 url.push_str("&noconfirm=1");
97 }
98 Ok(url)
99}
100
101/// Decode a `posprint://print?v=1&d=…` URL into a [`PosprintLaunch`].
102pub fn parse_posprint_url(url: &str) -> Result<PosprintLaunch, ProtocolUrlError> {
103 let url = url.trim();
104 if !is_posprint_url(url) {
105 return Err(ProtocolUrlError::NotPosprintUrl);
106 }
107
108 let after_scheme = url
109 .split_once(':')
110 .map(|(_, rest)| rest)
111 .ok_or(ProtocolUrlError::NotPosprintUrl)?;
112 let after_scheme = after_scheme.strip_prefix("//").unwrap_or(after_scheme);
113
114 let (path, query) = match after_scheme.split_once('?') {
115 Some((path, query)) => (path, query),
116 None => (after_scheme, ""),
117 };
118 let path = path.trim_matches('/');
119 if !path.is_empty() && !path.eq_ignore_ascii_case("print") {
120 return Err(ProtocolUrlError::InvalidEncoding(format!(
121 "unknown action '{path}' (expected print)"
122 )));
123 }
124
125 let mut version: Option<String> = None;
126 let mut payload: Option<String> = None;
127 let mut noconfirm = false;
128 for pair in query.split('&') {
129 if pair.is_empty() {
130 continue;
131 }
132 let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
133 let key = percent_decode_str(key)?;
134 match key.as_str() {
135 "v" => version = Some(percent_decode_str(value)?),
136 "d" => payload = Some(percent_decode_str(value)?),
137 "noconfirm" => noconfirm = parse_bool_flag(value),
138 // Legacy `referrer=` is ignored (browser protocol prompt is the trust gate).
139 "referrer" => {}
140 _ => {}
141 }
142 }
143
144 match version.as_deref() {
145 None | Some("1") => {}
146 Some(other) => return Err(ProtocolUrlError::UnsupportedVersion(other.to_string())),
147 }
148
149 let payload = payload.ok_or(ProtocolUrlError::MissingPayload)?;
150 let compressed = URL_SAFE_NO_PAD
151 .decode(payload.trim())
152 .map_err(|e| ProtocolUrlError::Base64(e.to_string()))?;
153
154 let mut decoder = DeflateDecoder::new(compressed.as_slice());
155 let mut json = Vec::new();
156 decoder
157 .read_to_end(&mut json)
158 .map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?;
159
160 let file: PosFile = serde_json::from_slice(&json)?;
161 if file.version != 1 {
162 return Err(ProtocolUrlError::UnsupportedPosVersion(file.version));
163 }
164
165 Ok(PosprintLaunch { file, noconfirm })
166}
167
168fn parse_bool_flag(value: &str) -> bool {
169 let v = value.trim();
170 if v.is_empty() {
171 return true;
172 }
173 matches!(
174 v.to_ascii_lowercase().as_str(),
175 "1" | "true" | "yes" | "on"
176 )
177}
178
179fn percent_decode_str(input: &str) -> Result<String, ProtocolUrlError> {
180 let bytes = percent_decode_bytes(input.as_bytes())?;
181 String::from_utf8(bytes).map_err(|e| ProtocolUrlError::InvalidEncoding(e.to_string()))
182}
183
184fn percent_decode_bytes(input: &[u8]) -> Result<Vec<u8>, ProtocolUrlError> {
185 let mut out = Vec::with_capacity(input.len());
186 let mut i = 0;
187 while i < input.len() {
188 match input[i] {
189 b'+' => {
190 out.push(b' ');
191 i += 1;
192 }
193 b'%' if i + 2 < input.len() => {
194 let h = from_hex(input[i + 1])?;
195 let l = from_hex(input[i + 2])?;
196 out.push((h << 4) | l);
197 i += 3;
198 }
199 b'%' => {
200 return Err(ProtocolUrlError::InvalidEncoding(
201 "truncated percent-escape".into(),
202 ));
203 }
204 c => {
205 out.push(c);
206 i += 1;
207 }
208 }
209 }
210 Ok(out)
211}
212
213fn from_hex(b: u8) -> Result<u8, ProtocolUrlError> {
214 match b {
215 b'0'..=b'9' => Ok(b - b'0'),
216 b'a'..=b'f' => Ok(b - b'a' + 10),
217 b'A'..=b'F' => Ok(b - b'A' + 10),
218 _ => Err(ProtocolUrlError::InvalidEncoding(format!(
219 "invalid hex digit {}",
220 b as char
221 ))),
222 }
223}
224
225#[cfg(test)]
226mod tests {
227 use super::*;
228 use crate::io::PosMetadata;
229
230 fn sample_file() -> PosFile {
231 PosFile {
232 version: 1,
233 metadata: PosMetadata {
234 title: Some("Demo".into()),
235 page_width_mm: 53.0,
236 chars_per_line: Some(32),
237 codepage: Some("CP437".into()),
238 },
239 body: "@barcode RASTER CODE128 ${data}\nHello\n@cut\n".into(),
240 }
241 }
242
243 #[test]
244 fn round_trips_pos_file() {
245 let file = sample_file();
246 let url = encode_posprint_url(&file).unwrap();
247 assert!(url.starts_with("posprint://print?v=1&d="));
248 let decoded = parse_posprint_url(&url).unwrap();
249 assert_eq!(decoded.file, file);
250 assert!(!decoded.noconfirm);
251 }
252
253 #[test]
254 fn encodes_and_parses_noconfirm() {
255 let file = sample_file();
256 let url = encode_posprint_url_with_options(
257 &file,
258 &EncodeOptions { noconfirm: true },
259 )
260 .unwrap();
261 assert!(url.contains("&noconfirm=1"));
262 assert!(!url.contains("referrer"));
263 let launch = parse_posprint_url(&url).unwrap();
264 assert!(launch.noconfirm);
265 }
266
267 #[test]
268 fn parses_noconfirm_and_ignores_legacy_referrer() {
269 let file = sample_file();
270 let base = encode_posprint_url(&file).unwrap();
271 let url = format!("{base}&noconfirm&referrer=shop.example%2Fv");
272 let launch = parse_posprint_url(&url).unwrap();
273 assert!(launch.noconfirm);
274 }
275
276 #[test]
277 fn rejects_bad_version() {
278 let err = parse_posprint_url("posprint://print?v=99&d=aa").unwrap_err();
279 assert!(matches!(err, ProtocolUrlError::UnsupportedVersion(_)));
280 }
281
282 #[test]
283 fn rejects_missing_payload() {
284 let err = parse_posprint_url("posprint://print?v=1").unwrap_err();
285 assert!(matches!(err, ProtocolUrlError::MissingPayload));
286 }
287
288 #[test]
289 fn detects_scheme() {
290 assert!(is_posprint_url("posprint://print?v=1&d=x"));
291 assert!(is_posprint_url("POSPRINT:print?v=1&d=x"));
292 assert!(!is_posprint_url("https://example.com"));
293 }
294}