Skip to main content

collect_settings/
codec.rs

1use crate::Settings;
2use base64::Engine;
3use flate2::{read::ZlibDecoder, write::ZlibEncoder, Compression};
4use std::io::{Read, Write};
5
6/// Errors from encoding, decoding or rendering.
7#[derive(Debug, thiserror::Error)]
8pub enum Error {
9    /// The settings could not be (de)serialised as JSON.
10    #[error("json: {0}")]
11    Json(#[from] serde_json::Error),
12    /// The payload is not valid base64.
13    #[error("base64: {0}")]
14    Base64(#[from] base64::DecodeError),
15    /// The payload could not be zlib-(de)compressed.
16    #[error("zlib: {0}")]
17    Zlib(#[from] std::io::Error),
18    /// The decompressed payload is not UTF-8.
19    #[error("payload is not utf-8")]
20    Utf8(#[from] std::string::FromUtf8Error),
21    /// The payload is too large for any QR code version.
22    #[cfg(feature = "qr")]
23    #[error("qr: {0}")]
24    Qr(#[from] qrcode::types::QrError),
25}
26
27/// Compress and encode an already serialised JSON document.
28pub fn encode_json(json: &str) -> Result<String, Error> {
29    let mut z = ZlibEncoder::new(Vec::new(), Compression::best());
30    z.write_all(json.as_bytes())?;
31    let bytes = z.finish()?;
32    Ok(base64::engine::general_purpose::STANDARD.encode(bytes))
33}
34
35/// Serialise, compress and encode: the exact string a QR code must carry.
36pub fn encode(settings: &Settings) -> Result<String, Error> {
37    encode_json(&settings.to_json()?)
38}
39
40/// Decode a scanned payload back into [`Settings`].
41///
42/// Whitespace is ignored and both standard and URL-safe base64 alphabets are
43/// accepted, because scanners and chat apps mangle long strings.
44pub fn decode(payload: &str) -> Result<Settings, Error> {
45    let cleaned: String = payload.chars().filter(|c| !c.is_whitespace()).collect();
46    let std = base64::engine::general_purpose::STANDARD;
47    let bytes = match std.decode(&cleaned) {
48        Ok(b) => b,
49        Err(e) => base64::engine::general_purpose::URL_SAFE
50            .decode(&cleaned)
51            .or_else(|_| base64::engine::general_purpose::STANDARD_NO_PAD.decode(&cleaned))
52            .map_err(|_| e)?,
53    };
54    let mut json = String::new();
55    ZlibDecoder::new(bytes.as_slice()).read_to_string(&mut json)?;
56    Ok(serde_json::from_str(&json)?)
57}
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62
63    /// Produced by the Python example in the ODK docs:
64    /// `b64encode(zlib.compress(json.dumps(settings).encode()))`.
65    #[test]
66    fn decodes_python_payload() {
67        let s = Settings::decode("eJwVzEsKgDAMRdG9vHHReTcjqcYq/UTSVgXp3tXh5cB94DmzUoR90AprpsSwIBh8dbJOTT/EVutR7DiGeQjipIpEJ/cg6tENaEl7/hdJzj37ydEcLtKlwK4UC/f+AqVRJcs=").unwrap();
68        assert_eq!(s.general.username.as_deref(), Some("a"));
69        assert_eq!(s.admin.moving_backwards, Some(false));
70    }
71}