wellfriend-document-sdk 1.0.0

Official async Rust SDK for the Wellfriend document API: typed document tools, pipelines, streaming uploads and downloads, retries and webhook verification.
Documentation
//! Small serde and file helpers shared by the hand-written and generated code.

use serde::de::DeserializeOwned;
use serde::{Deserialize, Deserializer, Serializer};
use serde_json::Value;

use crate::error::{Error, Result};

/// Decodes one field of a JSON object (`{"document": {...}}` → the document).
pub(crate) fn take_field<T: DeserializeOwned>(value: Value, field: &str) -> Result<T> {
    let inner = match value {
        Value::Object(mut map) => map
            .remove(field)
            .ok_or_else(|| Error::Decode(format!("the response has no `{field}` field")))?,
        other => {
            return Err(Error::Decode(format!(
                "expected an object with `{field}`, got {other}"
            )))
        }
    };
    serde_json::from_value(inner).map_err(|error| Error::decode(field, error))
}

/// Serializes an optional number, writing whole numbers without a fraction (`5`, not `5.0`).
pub(crate) fn number<S: Serializer>(
    value: &Option<f64>,
    serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
    match value {
        Some(number) => whole_number(*number, serializer),
        None => serializer.serialize_none(),
    }
}

/// Serializes a number, writing whole numbers without a fraction.
pub(crate) fn required_number<S: Serializer>(
    value: &f64,
    serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
    whole_number(*value, serializer)
}

fn whole_number<S: Serializer>(number: f64, serializer: S) -> std::result::Result<S::Ok, S::Error> {
    if number.fract() == 0.0 && number.abs() < 9_007_199_254_740_992.0 {
        serializer.serialize_i64(number as i64)
    } else {
        serializer.serialize_f64(number)
    }
}

/// Accepts a byte count sent either as a JSON number or as a decimal string.
pub(crate) fn u64_lenient<'de, D: Deserializer<'de>>(
    deserializer: D,
) -> std::result::Result<Option<u64>, D::Error> {
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum Lenient {
        Number(u64),
        Float(f64),
        Text(String),
    }
    Ok(match Option::<Lenient>::deserialize(deserializer)? {
        None => None,
        Some(Lenient::Number(value)) => Some(value),
        Some(Lenient::Float(value)) if value >= 0.0 => Some(value as u64),
        Some(Lenient::Float(_)) => None,
        Some(Lenient::Text(text)) => text.trim().parse().ok(),
    })
}

/// Treats `null` like a missing value (for lists the API sends as `null` when empty).
pub(crate) fn null_default<'de, D, T>(deserializer: D) -> std::result::Result<T, D::Error>
where
    D: Deserializer<'de>,
    T: Default + Deserialize<'de>,
{
    Ok(Option::<T>::deserialize(deserializer)?.unwrap_or_default())
}

/// The content type for a file name, from its extension. Never assumes PDF.
pub(crate) fn content_type_for(filename: &str) -> &'static str {
    let extension = filename
        .rsplit_once('.')
        .map(|(_, extension)| extension.to_ascii_lowercase())
        .unwrap_or_default();
    match extension.as_str() {
        "pdf" => "application/pdf",
        "jpg" | "jpeg" | "jfif" => "image/jpeg",
        "png" => "image/png",
        "webp" => "image/webp",
        "gif" => "image/gif",
        "tif" | "tiff" => "image/tiff",
        "bmp" => "image/bmp",
        "avif" => "image/avif",
        "heic" => "image/heic",
        "svg" => "image/svg+xml",
        "doc" => "application/msword",
        "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "xls" => "application/vnd.ms-excel",
        "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "ppt" => "application/vnd.ms-powerpoint",
        "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
        "odt" => "application/vnd.oasis.opendocument.text",
        "ods" => "application/vnd.oasis.opendocument.spreadsheet",
        "odp" => "application/vnd.oasis.opendocument.presentation",
        "rtf" => "application/rtf",
        "csv" => "text/csv",
        "tsv" => "text/tab-separated-values",
        "txt" | "text" => "text/plain",
        "md" | "markdown" => "text/markdown",
        "html" | "htm" => "text/html",
        "url" => "text/plain",
        "json" => "application/json",
        "xml" => "application/xml",
        "epub" => "application/epub+zip",
        "zip" => "application/zip",
        _ => "application/octet-stream",
    }
}

/// A file extension for a content type, for naming downloads that arrive without a file name.
pub(crate) fn extension_for(content_type: &str) -> &'static str {
    match content_type.split(';').next().unwrap_or_default().trim() {
        "application/pdf" => "pdf",
        "image/jpeg" => "jpg",
        "image/png" => "png",
        "image/webp" => "webp",
        "image/gif" => "gif",
        "image/tiff" => "tiff",
        "image/bmp" => "bmp",
        "image/avif" => "avif",
        "text/plain" => "txt",
        "text/markdown" => "md",
        "text/html" => "html",
        "text/csv" => "csv",
        "application/json" => "json",
        "application/zip" => "zip",
        "application/epub+zip" => "epub",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document" => "docx",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => "xlsx",
        "application/vnd.openxmlformats-officedocument.presentationml.presentation" => "pptx",
        _ => "bin",
    }
}

/// Keeps only the last path component of a server-provided file name, so a download can never
/// write outside the directory it was asked to write into.
pub(crate) fn safe_file_name(name: &str) -> Option<String> {
    let last = name.rsplit(['/', '\\']).next().unwrap_or_default().trim();
    let cleaned: String = last.chars().filter(|c| !c.is_control()).collect();
    if cleaned.is_empty() || cleaned == "." || cleaned == ".." {
        None
    } else {
        Some(cleaned)
    }
}

/// Lowercase hex of a byte slice.
pub(crate) fn hex(bytes: &[u8]) -> String {
    const DIGITS: &[u8; 16] = b"0123456789abcdef";
    let mut out = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        out.push(DIGITS[(byte >> 4) as usize] as char);
        out.push(DIGITS[(byte & 0x0f) as usize] as char);
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn detects_content_types_from_extensions() {
        assert_eq!(content_type_for("scan.PDF"), "application/pdf");
        assert_eq!(content_type_for("photo.jpeg"), "image/jpeg");
        assert_eq!(
            content_type_for("sheet.xlsx"),
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        );
        assert_eq!(content_type_for("noextension"), "application/octet-stream");
    }

    #[test]
    fn strips_paths_from_server_file_names() {
        assert_eq!(
            safe_file_name("../../etc/passwd").as_deref(),
            Some("passwd")
        );
        assert_eq!(safe_file_name("a\\b\\c.pdf").as_deref(), Some("c.pdf"));
        assert_eq!(safe_file_name(".."), None);
    }

    #[test]
    fn writes_whole_numbers_without_a_fraction() {
        #[derive(serde::Serialize)]
        struct S {
            #[serde(serialize_with = "number")]
            a: Option<f64>,
            #[serde(serialize_with = "number")]
            b: Option<f64>,
        }
        assert_eq!(
            serde_json::to_string(&S {
                a: Some(5.0),
                b: Some(7.5)
            })
            .unwrap(),
            r#"{"a":5,"b":7.5}"#
        );
    }

    #[test]
    fn reads_sizes_sent_as_strings() {
        #[derive(serde::Deserialize)]
        struct S {
            #[serde(default, deserialize_with = "u64_lenient")]
            size: Option<u64>,
        }
        let s: S = serde_json::from_str(r#"{"size":"2215244"}"#).unwrap();
        assert_eq!(s.size, Some(2_215_244));
        let s: S = serde_json::from_str(r#"{"size":12}"#).unwrap();
        assert_eq!(s.size, Some(12));
    }
}