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
use std::fmt;
use std::path::{Path, PathBuf};

use bytes::Bytes;
use futures_util::{Stream, StreamExt, TryStreamExt};
use reqwest::header::{CONTENT_DISPOSITION, CONTENT_TYPE};
use tokio::io::AsyncWriteExt;

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

/// A file download, streamed from the API. Nothing is buffered until you ask for it.
///
/// ```no_run
/// # async fn run(wf: wellfriend::Wellfriend) -> wellfriend::Result<()> {
/// let download = wf.document_versions().download("doc_8kq2W1", "ver_3Jx9Lm").await?;
/// println!("{:?} ({:?} bytes)", download.filename(), download.content_length());
/// download.save("copy.pdf").await?;
/// # Ok(())
/// # }
/// ```
pub struct Download {
    response: reqwest::Response,
}

impl fmt::Debug for Download {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Download")
            .field("filename", &self.filename())
            .field("content_type", &self.content_type())
            .field("content_length", &self.content_length())
            .finish()
    }
}

impl Download {
    pub(crate) fn new(response: reqwest::Response) -> Self {
        Download { response }
    }

    /// The file name from the `Content-Disposition` header, without any directory part.
    pub fn filename(&self) -> Option<String> {
        let header = self
            .response
            .headers()
            .get(CONTENT_DISPOSITION)?
            .to_str()
            .ok()?;
        parse_disposition(header).and_then(|name| crate::util::safe_file_name(&name))
    }

    /// The content type.
    pub fn content_type(&self) -> Option<&str> {
        self.response.headers().get(CONTENT_TYPE)?.to_str().ok()
    }

    /// The size in bytes, when the server announced it.
    pub fn content_length(&self) -> Option<u64> {
        self.response.content_length()
    }

    /// The body as a stream of chunks.
    pub fn bytes_stream(self) -> impl Stream<Item = Result<Bytes>> + Send + 'static {
        self.response.bytes_stream().map_err(Error::connection)
    }

    /// The whole body in memory. Prefer [`save`](Self::save) or
    /// [`bytes_stream`](Self::bytes_stream) for large files.
    pub async fn bytes(self) -> Result<Bytes> {
        self.response.bytes().await.map_err(Error::connection)
    }

    /// Streams the body to `path`. The data goes to a temporary file next to it, renamed into
    /// place once complete, so `path` never holds a partial file. Returns the number of bytes.
    pub async fn save(self, path: impl AsRef<Path>) -> Result<u64> {
        let path = path.as_ref();
        let partial = partial_path(path);
        let result = self.write_to(&partial).await;
        match result {
            Ok(written) => {
                tokio::fs::rename(&partial, path).await?;
                Ok(written)
            }
            Err(error) => {
                let _ = tokio::fs::remove_file(&partial).await;
                Err(error)
            }
        }
    }

    async fn write_to(self, partial: &Path) -> Result<u64> {
        let expected = self.content_length();
        let mut file = tokio::fs::File::create(partial).await?;
        let mut stream = self.response.bytes_stream();
        let mut written: u64 = 0;
        while let Some(chunk) = stream.next().await {
            let chunk = chunk.map_err(Error::connection)?;
            file.write_all(&chunk).await?;
            written += chunk.len() as u64;
        }
        file.flush().await?;
        file.sync_all().await?;
        if let Some(expected) = expected {
            if expected != written {
                return Err(Error::connection(std::io::Error::new(
                    std::io::ErrorKind::UnexpectedEof,
                    format!("the download ended after {written} of {expected} bytes"),
                )));
            }
        }
        Ok(written)
    }
}

fn partial_path(path: &Path) -> PathBuf {
    let mut name = path
        .file_name()
        .map(|name| name.to_os_string())
        .unwrap_or_default();
    name.push(".wfpart");
    path.with_file_name(name)
}

/// The file name of a `Content-Disposition` header, preferring the UTF-8 `filename*`.
fn parse_disposition(header: &str) -> Option<String> {
    let mut plain = None;
    for part in header.split(';').map(str::trim) {
        if let Some(value) = part.strip_prefix("filename*=") {
            let encoded = value
                .split_once("''")
                .map(|(_, rest)| rest)
                .unwrap_or(value);
            if let Some(decoded) = percent_decode(encoded.trim_matches('"')) {
                return Some(decoded);
            }
        } else if let Some(value) = part.strip_prefix("filename=") {
            plain = Some(value.trim_matches('"').replace("\\\"", "\""));
        }
    }
    plain
}

fn percent_decode(text: &str) -> Option<String> {
    let bytes = text.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut index = 0;
    while index < bytes.len() {
        if bytes[index] == b'%' && index + 2 < bytes.len() {
            let hex = std::str::from_utf8(&bytes[index + 1..index + 3]).ok()?;
            out.push(u8::from_str_radix(hex, 16).ok()?);
            index += 3;
        } else {
            out.push(bytes[index]);
            index += 1;
        }
    }
    String::from_utf8(out).ok()
}

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

    #[test]
    fn reads_both_disposition_forms() {
        assert_eq!(
            parse_disposition(
                r#"attachment; filename="a.pdf"; filename*=UTF-8''r%C3%A9sum%C3%A9.pdf"#
            )
            .as_deref(),
            Some("résumé.pdf")
        );
        assert_eq!(
            parse_disposition(r#"attachment; filename="plain.pdf""#).as_deref(),
            Some("plain.pdf")
        );
        assert_eq!(parse_disposition("inline"), None);
    }

    #[test]
    fn partial_files_sit_next_to_the_target() {
        assert_eq!(
            partial_path(Path::new("/tmp/out.pdf")),
            PathBuf::from("/tmp/out.pdf.wfpart")
        );
    }
}