BlueGit

timfa posprint

Files

posprint / src / protocol_url.rs

protocol_url.rs

protocol_url.rs 7.5 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/// True when `s` looks like a `posprint:` / `posprint://` protocol URL.
55pub fn is_posprint_url(s: &str) -> bool {
56 let s = s.trim();
57 let lower = s.to_ascii_lowercase();
58 lower.starts_with("posprint://") || lower.starts_with("posprint:")
59}
60
61/// Encode a `.pos` file as `posprint://print?v=1&d=…` (raw deflate + base64url, no padding).
62pub fn encode_posprint_url(file: &PosFile) -> Result<String, ProtocolUrlError> {
63 let json = serde_json::to_vec(file)?;
64 let mut encoder = DeflateEncoder::new(Vec::new(), Compression::best());
65 encoder
66 .write_all(&json)
67 .map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?;
68 let compressed = encoder
69 .finish()
70 .map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?;
71 let b64 = URL_SAFE_NO_PAD.encode(compressed);
72 Ok(format!("posprint://print?v=1&d={b64}"))
73}
74
75/// Decode a `posprint://print?v=1&d=…` URL into a [`PosFile`].
76pub fn parse_posprint_url(url: &str) -> Result<PosFile, ProtocolUrlError> {
77 let url = url.trim();
78 if !is_posprint_url(url) {
79 return Err(ProtocolUrlError::NotPosprintUrl);
80 }
81
82 let after_scheme = url
83 .split_once(':')
84 .map(|(_, rest)| rest)
85 .ok_or(ProtocolUrlError::NotPosprintUrl)?;
86 let after_scheme = after_scheme.strip_prefix("//").unwrap_or(after_scheme);
87
88 let (path, query) = match after_scheme.split_once('?') {
89 Some((path, query)) => (path, query),
90 None => (after_scheme, ""),
91 };
92 let path = path.trim_matches('/');
93 if !path.is_empty() && !path.eq_ignore_ascii_case("print") {
94 return Err(ProtocolUrlError::InvalidEncoding(format!(
95 "unknown action '{path}' (expected print)"
96 )));
97 }
98
99 let mut version: Option<String> = None;
100 let mut payload: Option<String> = None;
101 for pair in query.split('&') {
102 if pair.is_empty() {
103 continue;
104 }
105 let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
106 let key = percent_decode_str(key)?;
107 match key.as_str() {
108 "v" => version = Some(percent_decode_str(value)?),
109 "d" => payload = Some(percent_decode_str(value)?),
110 _ => {}
111 }
112 }
113
114 match version.as_deref() {
115 None | Some("1") => {}
116 Some(other) => return Err(ProtocolUrlError::UnsupportedVersion(other.to_string())),
117 }
118
119 let payload = payload.ok_or(ProtocolUrlError::MissingPayload)?;
120 let compressed = URL_SAFE_NO_PAD
121 .decode(payload.trim())
122 .map_err(|e| ProtocolUrlError::Base64(e.to_string()))?;
123
124 let mut decoder = DeflateDecoder::new(compressed.as_slice());
125 let mut json = Vec::new();
126 decoder
127 .read_to_end(&mut json)
128 .map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?;
129
130 let file: PosFile = serde_json::from_slice(&json)?;
131 if file.version != 1 {
132 return Err(ProtocolUrlError::UnsupportedPosVersion(file.version));
133 }
134 Ok(file)
135}
136
137fn percent_decode_str(input: &str) -> Result<String, ProtocolUrlError> {
138 let bytes = percent_decode_bytes(input.as_bytes())?;
139 String::from_utf8(bytes).map_err(|e| ProtocolUrlError::InvalidEncoding(e.to_string()))
140}
141
142fn percent_decode_bytes(input: &[u8]) -> Result<Vec<u8>, ProtocolUrlError> {
143 let mut out = Vec::with_capacity(input.len());
144 let mut i = 0;
145 while i < input.len() {
146 match input[i] {
147 b'+' => {
148 out.push(b' ');
149 i += 1;
150 }
151 b'%' if i + 2 < input.len() => {
152 let h = from_hex(input[i + 1])?;
153 let l = from_hex(input[i + 2])?;
154 out.push((h << 4) | l);
155 i += 3;
156 }
157 b'%' => {
158 return Err(ProtocolUrlError::InvalidEncoding(
159 "truncated percent-escape".into(),
160 ));
161 }
162 c => {
163 out.push(c);
164 i += 1;
165 }
166 }
167 }
168 Ok(out)
169}
170
171fn from_hex(b: u8) -> Result<u8, ProtocolUrlError> {
172 match b {
173 b'0'..=b'9' => Ok(b - b'0'),
174 b'a'..=b'f' => Ok(b - b'a' + 10),
175 b'A'..=b'F' => Ok(b - b'A' + 10),
176 _ => Err(ProtocolUrlError::InvalidEncoding(format!(
177 "invalid hex digit {}",
178 b as char
179 ))),
180 }
181}
182
183#[cfg(test)]
184mod tests {
185 use super::*;
186 use crate::io::PosMetadata;
187
188 fn sample_file() -> PosFile {
189 PosFile {
190 version: 1,
191 metadata: PosMetadata {
192 title: Some("Demo".into()),
193 page_width_mm: 53.0,
194 chars_per_line: Some(32),
195 codepage: Some("CP437".into()),
196 },
197 body: "@barcode RASTER CODE128 ${data}\nHello\n@cut\n".into(),
198 }
199 }
200
201 #[test]
202 fn round_trips_pos_file() {
203 let file = sample_file();
204 let url = encode_posprint_url(&file).unwrap();
205 assert!(url.starts_with("posprint://print?v=1&d="));
206 let decoded = parse_posprint_url(&url).unwrap();
207 assert_eq!(decoded, file);
208 }
209
210 #[test]
211 fn rejects_bad_version() {
212 let err = parse_posprint_url("posprint://print?v=99&d=aa").unwrap_err();
213 assert!(matches!(err, ProtocolUrlError::UnsupportedVersion(_)));
214 }
215
216 #[test]
217 fn rejects_missing_payload() {
218 let err = parse_posprint_url("posprint://print?v=1").unwrap_err();
219 assert!(matches!(err, ProtocolUrlError::MissingPayload));
220 }
221
222 #[test]
223 fn detects_scheme() {
224 assert!(is_posprint_url("posprint://print?v=1&d=x"));
225 assert!(is_posprint_url("POSPRINT:print?v=1&d=x"));
226 assert!(!is_posprint_url("https://example.com"));
227 }
228}