summaryrefslogtreecommitdiffstats
path: root/headers/src/header_components/disposition.rs
blob: c655cd23b1335ce9d490e1177f468aed7ba09826 (plain)
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
use std::borrow::Cow;
#[cfg(feature="serde")]
use std::fmt;

use failure::Fail;
use soft_ascii_string::SoftAsciiStr;
use media_type::push_params_to_buffer;
use media_type::spec::{MimeSpec, Ascii, Modern, Internationalized};

#[cfg(feature="serde")]
use serde::{
    Serialize, Serializer,
    Deserialize, Deserializer,
};

use internals::error::{EncodingError, EncodingErrorKind};
use internals::encoder::{EncodableInHeader, EncodingWriter};
use ::HeaderTryFrom;
use ::error::ComponentCreationError;

use super::FileMeta;

/// Disposition Component mainly used for the Content-Disposition header (rfc2183)
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature="serde", derive(Serialize, Deserialize))]
pub struct Disposition {
    kind: DispositionKind,
    file_meta: DispositionParameters
}

impl Disposition {
    pub fn new(kind: DispositionKind, file_meta: DispositionParameters) -> Self {
        Disposition { kind, file_meta }
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Default)]
#[cfg_attr(feature="serde", derive(Serialize, Deserialize))]
struct DispositionParameters(FileMeta);

/// Represents what kind of disposition is used (Inline/Attachment)
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum DispositionKind {
    /// Display the body "inline".
    ///
    /// This disposition is mainly used to add some additional content
    /// and then refers to it through its cid (e.g. in a html mail).
    Inline,
    /// Display the body as an attachment to of the mail.
    Attachment,
    /// A disposition indicating the content contains a form submission.
    FormData,
    /// Extension type to hold any disposition not explicitly enumerated.
    Extension(String),
}

impl Default for DispositionKind {
    fn default() -> Self {
        DispositionKind::Inline
    }
}

impl Disposition {

    /// Create a inline disposition with default parameters.
    pub fn inline() -> Self {
        Disposition::new( DispositionKind::Inline, FileMeta::default() )
    }

    /// Create a attachment disposition with default parameters.
    pub fn attachment() -> Self {
        Disposition::new( DispositionKind::Attachment, FileMeta::default() )
    }

    pub fn formdata() -> Self {
        Disposition::new( DispositionKind::FormData, FileMeta::default() )
    }

    pub fn disposition_extension(s: String) -> Self {
        Disposition::new( DispositionKind::Extension(s), FileMeta::default() )
    }

    /// Create a new disposition with given parameters.
    pub fn new( kind: DispositionKind, file_meta: FileMeta ) -> Self {
        Disposition { kind, file_meta: DispositionParameters( file_meta ) }
    }

    /// Return which kind of disposition this represents.
    pub fn kind( &self ) -> &DispositionKind {
        &self.kind
    }

    /// Returns the parameters associated with the disposition.
    pub fn file_meta( &self ) -> &FileMeta {
        &self.file_meta
    }

    /// Returns a mutable reference to the parameters associated with the disposition.
    pub fn file_meta_mut( &mut self ) -> &mut FileMeta {
        &mut self.file_meta
    }

}

#[cfg(feature="serde")]
impl Serialize for DispositionKind {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: Serializer
    {
        match self {
            &DispositionKind::Inline =>
                serializer.serialize_str("inline"),
            &DispositionKind::Attachment =>
                serializer.serialize_str("attachment"),
            &DispositionKind::FormData =>
                serializer.serialize_str("form-data"),
            &DispositionKind::Extension(ref s) =>
                serializer.serialize_str(s),
        }
    }
}

#[cfg(feature="serde")]
impl<'de> Deserialize<'de> for DispositionKind {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where D: Deserializer<'de>
    {
        struct Visitor;
        impl<'de> ::serde::de::Visitor<'de> for Visitor {
            type Value = DispositionKind;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("\"inline\" or \"attachment\"")
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
                where E: ::serde::de::Error,
            {
                if value.eq_ignore_ascii_case("inline") {
                    Ok(DispositionKind::Inline)
                } else if value.eq_ignore_ascii_case("attachment") {
                    Ok(DispositionKind::Attachment)
                } else if value.eq_ignore_ascii_case("form-data") {
                    Ok(DispositionKind::FormData)
                } else {
                    Err(E::custom(format!(
                        "unknown disposition: {:?}", value
                    )))
                }
            }
        }

        deserializer.deserialize_str(Visitor)
    }
}

/// This try from is for usability only, it is
/// generally recommendet to use Disposition::inline()/::attachment()
/// as it is type safe / compiler time checked, while this one
/// isn't
impl<'a> HeaderTryFrom<&'a str> for Disposition {
    fn try_from(text: &'a str) -> Result<Self, ComponentCreationError> {
        if text.eq_ignore_ascii_case("Inline") {
            Ok(Disposition::inline())
        } else if text.eq_ignore_ascii_case("Attachment") {
            Ok(Disposition::attachment())
        } else if text.eq_ignore_ascii_case("form-data") {
            Ok(Disposition::formdata())
        } else {
            let mut err = ComponentCreationError::new("Disposition");
            err.set_str_context(text);
            return Err(err);
        }
    }
}


//TODO provide a gnneral way for encoding header parameter ...
//  which follow the scheme: <mainvalue> *(";" <key>"="<value> )
//  this are: ContentType and ContentDisposition for now
impl EncodableInHeader for DispositionParameters {

    fn encode(&self, handle: &mut EncodingWriter) -> Result<(), EncodingError> {
        let mut params = Vec::<(&str, Cow<str>)>::new();
        if let Some(filename) = self.file_name.as_ref() {
            params.push(("filename", Cow::Borrowed(filename)));
        }
        if let Some(creation_date) = self.creation_date.as_ref() {
            params.push(("creation-date", Cow::Owned(creation_date.to_rfc2822())));
        }
        if let Some(date) = self.modification_date.as_ref() {
            params.push(("modification-date", Cow::Owned(date.to_rfc2822())));
        }
        if let Some(date) = self.read_date.as_ref() {
            params.push(("read-date", Cow::Owned(date.to_rfc2822())));
        }
        if let Some(size) = self.size.as_ref() {
            params.push(("size", Cow::Owned(size.to_string())));
        }

        //TODO instead do optCFWS ; spCFWS <name>=<value>
        // so that soft line brakes can be done
        let mut buff = String::new();
        let res =
            if handle.mail_type().is_internationalized() {
                push_params_to_buffer::<MimeSpec<Internationalized, Modern>, _, _, _>(
                    &mut buff, params
                )
            } else {
                push_params_to_buffer::<MimeSpec<Ascii, Modern>, _, _, _>(
                    &mut buff, params
                )
            };

        match res {
            Err(err) => {
                Err(err.context(EncodingErrorKind::Malformed).into())
            },
            Ok(_) => {
                handle.write_str_unchecked(&*buff)?;
                Ok(())
            }
        }
    }

    fn boxed_clone(&self) -> Box<EncodableInHeader> {
        Box::new(self.clone())
    }
}


impl EncodableInHeader for Disposition {

    fn encode(&self, handle: &mut EncodingWriter) -> Result<(), EncodingError> {
        use self::DispositionKind::*;
        match self.kind {
            Inline => {
                handle.write_str(SoftAsciiStr::from_unchecked("inline"))?;
            },
            Attachment => {
                handle.write_str(SoftAsciiStr::from_unchecked("attachment"))?;
            }
            FormData => {
                handle.write_str(SoftAsciiStr::from_unchecked("form-data"))?;
            }
            Extension(ref s) => {
                handle.write_str(SoftAsciiStr::from_unchecked(s))