//! `posprint://` URLs that embed a compressed `.pos` document (magnet-style). use std::fmt; use std::io::{Read, Write}; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use base64::Engine; use flate2::read::DeflateDecoder; use flate2::write::DeflateEncoder; use flate2::Compression; use crate::io::PosFile; /// Soft warning threshold for cross-platform protocol handoff (~Windows cmdline limit). pub const WARN_URL_LEN: usize = 7000; #[derive(Debug)] pub enum ProtocolUrlError { NotPosprintUrl, UnsupportedVersion(String), MissingPayload, InvalidEncoding(String), Base64(String), Inflate(String), Json(String), UnsupportedPosVersion(u32), } impl fmt::Display for ProtocolUrlError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::NotPosprintUrl => write!(f, "not a posprint:// URL"), Self::UnsupportedVersion(v) => { write!(f, "unsupported URL version '{v}' (expected 1)") } Self::MissingPayload => write!(f, "missing document payload (d=)"), Self::InvalidEncoding(e) => write!(f, "invalid URL / percent-encoding: {e}"), Self::Base64(e) => write!(f, "invalid base64 payload: {e}"), Self::Inflate(e) => write!(f, "decompression failed: {e}"), Self::Json(e) => write!(f, "invalid .pos JSON: {e}"), Self::UnsupportedPosVersion(v) => write!(f, "unsupported .pos version {v}"), } } } impl std::error::Error for ProtocolUrlError {} impl From for ProtocolUrlError { fn from(value: serde_json::Error) -> Self { Self::Json(value.to_string()) } } /// Decoded `posprint://` launch request. #[derive(Debug, Clone, PartialEq)] pub struct PosprintLaunch { pub file: PosFile, /// When true, print without waiting for the Print button. pub noconfirm: bool, } /// Optional extras when encoding a URL. #[derive(Debug, Clone, Default)] pub struct EncodeOptions { pub noconfirm: bool, } /// True when `s` looks like a `posprint:` / `posprint://` protocol URL. pub fn is_posprint_url(s: &str) -> bool { let s = s.trim(); let lower = s.to_ascii_lowercase(); lower.starts_with("posprint://") || lower.starts_with("posprint:") } /// Encode a `.pos` file as `posprint://print?v=1&d=…` (raw deflate + base64url, no padding). pub fn encode_posprint_url(file: &PosFile) -> Result { encode_posprint_url_with_options(file, &EncodeOptions::default()) } /// Encode with optional `noconfirm` query parameter. pub fn encode_posprint_url_with_options( file: &PosFile, options: &EncodeOptions, ) -> Result { let json = serde_json::to_vec(file)?; let mut encoder = DeflateEncoder::new(Vec::new(), Compression::best()); encoder .write_all(&json) .map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?; let compressed = encoder .finish() .map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?; let b64 = URL_SAFE_NO_PAD.encode(compressed); let mut url = format!("posprint://print?v=1&d={b64}"); if options.noconfirm { url.push_str("&noconfirm=1"); } Ok(url) } /// Decode a `posprint://print?v=1&d=…` URL into a [`PosprintLaunch`]. pub fn parse_posprint_url(url: &str) -> Result { let url = url.trim(); if !is_posprint_url(url) { return Err(ProtocolUrlError::NotPosprintUrl); } let after_scheme = url .split_once(':') .map(|(_, rest)| rest) .ok_or(ProtocolUrlError::NotPosprintUrl)?; let after_scheme = after_scheme.strip_prefix("//").unwrap_or(after_scheme); let (path, query) = match after_scheme.split_once('?') { Some((path, query)) => (path, query), None => (after_scheme, ""), }; let path = path.trim_matches('/'); if !path.is_empty() && !path.eq_ignore_ascii_case("print") { return Err(ProtocolUrlError::InvalidEncoding(format!( "unknown action '{path}' (expected print)" ))); } let mut version: Option = None; let mut payload: Option = None; let mut noconfirm = false; for pair in query.split('&') { if pair.is_empty() { continue; } let (key, value) = pair.split_once('=').unwrap_or((pair, "")); let key = percent_decode_str(key)?; match key.as_str() { "v" => version = Some(percent_decode_str(value)?), "d" => payload = Some(percent_decode_str(value)?), "noconfirm" => noconfirm = parse_bool_flag(value), // Legacy `referrer=` is ignored (browser protocol prompt is the trust gate). "referrer" => {} _ => {} } } match version.as_deref() { None | Some("1") => {} Some(other) => return Err(ProtocolUrlError::UnsupportedVersion(other.to_string())), } let payload = payload.ok_or(ProtocolUrlError::MissingPayload)?; let compressed = URL_SAFE_NO_PAD .decode(payload.trim()) .map_err(|e| ProtocolUrlError::Base64(e.to_string()))?; let mut decoder = DeflateDecoder::new(compressed.as_slice()); let mut json = Vec::new(); decoder .read_to_end(&mut json) .map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?; let file: PosFile = serde_json::from_slice(&json)?; if file.version != 1 { return Err(ProtocolUrlError::UnsupportedPosVersion(file.version)); } Ok(PosprintLaunch { file, noconfirm }) } fn parse_bool_flag(value: &str) -> bool { let v = value.trim(); if v.is_empty() { return true; } matches!( v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on" ) } fn percent_decode_str(input: &str) -> Result { let bytes = percent_decode_bytes(input.as_bytes())?; String::from_utf8(bytes).map_err(|e| ProtocolUrlError::InvalidEncoding(e.to_string())) } fn percent_decode_bytes(input: &[u8]) -> Result, ProtocolUrlError> { let mut out = Vec::with_capacity(input.len()); let mut i = 0; while i < input.len() { match input[i] { b'+' => { out.push(b' '); i += 1; } b'%' if i + 2 < input.len() => { let h = from_hex(input[i + 1])?; let l = from_hex(input[i + 2])?; out.push((h << 4) | l); i += 3; } b'%' => { return Err(ProtocolUrlError::InvalidEncoding( "truncated percent-escape".into(), )); } c => { out.push(c); i += 1; } } } Ok(out) } fn from_hex(b: u8) -> Result { match b { b'0'..=b'9' => Ok(b - b'0'), b'a'..=b'f' => Ok(b - b'a' + 10), b'A'..=b'F' => Ok(b - b'A' + 10), _ => Err(ProtocolUrlError::InvalidEncoding(format!( "invalid hex digit {}", b as char ))), } } #[cfg(test)] mod tests { use super::*; use crate::io::PosMetadata; fn sample_file() -> PosFile { PosFile { version: 1, metadata: PosMetadata { title: Some("Demo".into()), page_width_mm: 53.0, chars_per_line: Some(32), codepage: Some("CP437".into()), }, body: "@barcode RASTER CODE128 ${data}\nHello\n@cut\n".into(), } } #[test] fn round_trips_pos_file() { let file = sample_file(); let url = encode_posprint_url(&file).unwrap(); assert!(url.starts_with("posprint://print?v=1&d=")); let decoded = parse_posprint_url(&url).unwrap(); assert_eq!(decoded.file, file); assert!(!decoded.noconfirm); } #[test] fn encodes_and_parses_noconfirm() { let file = sample_file(); let url = encode_posprint_url_with_options( &file, &EncodeOptions { noconfirm: true }, ) .unwrap(); assert!(url.contains("&noconfirm=1")); assert!(!url.contains("referrer")); let launch = parse_posprint_url(&url).unwrap(); assert!(launch.noconfirm); } #[test] fn parses_noconfirm_and_ignores_legacy_referrer() { let file = sample_file(); let base = encode_posprint_url(&file).unwrap(); let url = format!("{base}&noconfirm&referrer=shop.example%2Fv"); let launch = parse_posprint_url(&url).unwrap(); assert!(launch.noconfirm); } #[test] fn rejects_bad_version() { let err = parse_posprint_url("posprint://print?v=99&d=aa").unwrap_err(); assert!(matches!(err, ProtocolUrlError::UnsupportedVersion(_))); } #[test] fn rejects_missing_payload() { let err = parse_posprint_url("posprint://print?v=1").unwrap_err(); assert!(matches!(err, ProtocolUrlError::MissingPayload)); } #[test] fn detects_scheme() { assert!(is_posprint_url("posprint://print?v=1&d=x")); assert!(is_posprint_url("POSPRINT:print?v=1&d=x")); assert!(!is_posprint_url("https://example.com")); } }