logo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use poem::{http::HeaderValue, Body, IntoResponse, Response};

use crate::{
    payload::{Binary, Payload},
    registry::{MetaResponses, MetaSchemaRef, Registry},
    ApiResponse,
};

/// A binary payload for download file.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Attachment<T> {
    data: Binary<T>,
    filename: Option<String>,
}

impl<T: Into<Body> + Send> Attachment<T> {
    /// Create an attachment with data.
    pub fn new(data: T) -> Self {
        Self {
            data: Binary(data),
            filename: None,
        }
    }

    /// Specify the file name.
    #[must_use]
    pub fn filename(self, filename: impl Into<String>) -> Self {
        Self {
            filename: Some(filename.into()),
            ..self
        }
    }
}

impl<T: Into<Body> + Send> Payload for Attachment<T> {
    const CONTENT_TYPE: &'static str = Binary::<T>::CONTENT_TYPE;

    fn schema_ref() -> MetaSchemaRef {
        Binary::<T>::schema_ref()
    }
}

impl<T: Into<Body> + Send> IntoResponse for Attachment<T> {
    fn into_response(self) -> Response {
        let mut resp = self.data.into_response();

        if let Some(header_value) = self.filename.as_ref().and_then(|filename| {
            let legal_filename = filename
                .replace('\\', "\\\\")
                .replace('\"', "\\\"")
                .replace('\r', "\\\r")
                .replace('\n', "\\\n");
            HeaderValue::from_str(&format!("attachment; filename=\"{}\"", legal_filename)).ok()
        }) {
            resp.headers_mut()
                .insert("Content-Disposition", header_value);
        }

        resp
    }
}

impl<T: Into<Body> + Send> ApiResponse for Attachment<T> {
    fn meta() -> MetaResponses {
        Binary::<T>::meta()
    }

    fn register(_registry: &mut Registry) {}
}