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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
use super::body::{Body, BodyKind};
use super::{Error, ErrorKind, Result};
use mime::Mime;
use multipart::client as mp;
use std::fmt;
use std::io::{copy, prelude::*, Cursor, Error as IoError, Result as IoResult};

/// A file to be uploaded as part of a multipart form.
#[derive(Debug, Clone)]
pub struct MultipartFile<'key, 'data> {
    name: &'key str,
    file: &'data [u8],
    filename: Option<&'key str>,
    mime: Option<Mime>,
}

impl<'key, 'data> MultipartFile<'key, 'data> {
    /// Constructs a new `MultipartFile` from the name and contents.
    pub fn new(name: &'key str, file: &'data [u8]) -> Self {
        Self {
            name,
            file,
            filename: None,
            mime: None,
        }
    }

    /// Sets the MIME type of the file.
    ///
    /// # Errors
    /// Returns an error if the MIME type is invalid.
    pub fn with_type(self, mime_type: impl AsRef<str>) -> Result<Self> {
        let mime_str = mime_type.as_ref();
        let mime: Mime = match mime_str.parse() {
            Ok(mime) => mime,
            Err(error) => return Err(Error(Box::new(ErrorKind::InvalidMimeType(error.to_string())))),
        };
        Ok(Self {
            mime: Some(mime),
            ..self
        })
    }

    /// Sets the filename of the file.
    pub fn with_filename(self, filename: &'key str) -> Self {
        Self {
            filename: Some(filename),
            ..self
        }
    }
}

/// A builder for creating a `Multipart` body.
#[derive(Debug, Clone, Default)]
pub struct MultipartBuilder<'key, 'data> {
    text: Vec<(&'key str, &'data str)>,
    files: Vec<MultipartFile<'key, 'data>>,
}

impl<'key, 'data> MultipartBuilder<'key, 'data> {
    /// Creates a new `MultipartBuilder`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a text field to the form.
    pub fn with_text(mut self, name: &'key str, text: &'data str) -> Self {
        self.text.push((name, text));
        self
    }

    /// Adds a `MultipartFile` to the form.
    pub fn with_file(mut self, file: MultipartFile<'key, 'data>) -> Self {
        self.files.push(file);
        self
    }

    /// Creates a `Multipart` to be used as a body.
    pub fn build(self) -> Result<Multipart<'data>> {
        let mut mp = mp::lazy::Multipart::new();
        for (k, v) in self.text {
            mp.add_text(k, v);
        }
        for file in self.files {
            mp.add_stream(file.name, Cursor::new(file.file), file.filename, file.mime);
        }
        let prepared = mp.prepare().map_err::<IoError, _>(Into::into)?;
        Ok(Multipart { data: prepared })
    }
}

/// A multipart form created using `MultipartBuilder`.
pub struct Multipart<'data> {
    data: mp::lazy::PreparedFields<'data>,
}

impl Body for Multipart<'_> {
    fn kind(&mut self) -> IoResult<BodyKind> {
        Ok(BodyKind::Chunked)
    }

    fn write<W: Write>(&mut self, mut writer: W) -> IoResult<()> {
        copy(&mut self.data, &mut writer)?;
        Ok(())
    }

    fn content_type(&mut self) -> IoResult<Option<String>> {
        Ok(Some(format!("multipart/form-data; boundary={}", self.data.boundary())))
    }
}

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