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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
//! Module for handling content types

use std::collections::BTreeMap;
use std::str::{from_utf8, FromStr};

use itertools::Itertools;
use lazy_static::*;
use log::*;
use mime::Mime;
use regex::Regex;
use serde::{Deserialize, Serialize};

/// Content type of a body
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, Hash)]
pub struct ContentType {
  /// Main content type
  pub main_type: String,
  /// Sub content type
  pub sub_type: String,
  /// Content type attributes
  pub attributes: BTreeMap<String, String>,
  /// Suffix
  pub suffix: Option<String>
}

lazy_static! {
  /// XML Content Type
  pub static ref XML: ContentType = ContentType {
    main_type: "application".into(),
    sub_type: "xml".into(),
    .. ContentType::default()
  };

  /// HTML Content Type
  pub static ref HTML: ContentType = ContentType {
    main_type: "text".into(),
    sub_type: "html".into(),
    .. ContentType::default()
  };

  /// JSON Content Type
  pub static ref JSON: ContentType = ContentType {
    main_type: "application".into(),
    sub_type: "json".into(),
    .. ContentType::default()
  };

  /// TEXT Content Type
  pub static ref TEXT: ContentType = ContentType {
    main_type: "text".into(),
    sub_type: "plain".into(),
    .. ContentType::default()
  };

  static ref XMLREGEXP: Regex = Regex::new(r"^\s*<\?xml\s*version.*").unwrap();
  static ref HTMLREGEXP: Regex = Regex::new(r"^\s*(<!DOCTYPE)|(<HTML>).*").unwrap();
  static ref JSONREGEXP: Regex = Regex::new(r#"^\s*(true|false|null|[0-9]+|"\w*|\{\s*(}|"\w+)|\[\s*)"#).unwrap();
  static ref XMLREGEXP2: Regex = Regex::new(r#"^\s*<\w+\s*(:\w+=["”][^"”]+["”])?.*"#).unwrap();
}

impl ContentType {
  /// Parses a string into a ContentType
  pub fn parse<'a, S: Into<&'a str>>(content_type: S) -> Result<ContentType, String> {
    let content_type = content_type.into();
    match Mime::from_str(content_type) {
      Ok(mime) => {
        Ok(ContentType {
          main_type: mime.type_().to_string(),
          sub_type: mime.subtype().to_string(),
          attributes: mime.params().map(|(key, value)| (key.to_string(), value.to_string())).collect(),
          suffix: mime.suffix().map(|name| name.to_string())
        })
      },
      Err(err) => {
        let message = format!("Failed to parse '{}' as a content type: {}",
                              content_type, err);
        warn!("{}", message);
        Err(message)
      }
    }
  }

  /// If it is a JSON type
  pub fn is_json(&self) -> bool {
    self.main_type == "application" && (self.sub_type.starts_with("json") ||
      self.suffix.as_ref().unwrap_or(&String::default()) == "json")
  }

  /// If it is a XML type
  pub fn is_xml(&self) -> bool {
    (self.main_type == "application" || self.main_type == "text") && (self.sub_type == "xml" ||
      self.suffix.as_ref().unwrap_or(&String::default()) == "xml")
  }

  /// If it is a XML type (not including ones with suffixes like atom+xml)
  pub fn is_strict_xml(&self) -> bool {
    (self.main_type == "application" || self.main_type == "text") && self.sub_type == "xml"
  }

  /// If it is a text type
  pub fn is_text(&self) -> bool {
    self.main_type == "text" || self.is_xml() || self.is_json()
  }

  /// If it is a known binary type
  pub fn is_binary(&self) -> bool {
    match self.main_type.as_str() {
      "audio" | "font" | "image" | "video" => true,
      "text" => false,
      _ => false
    }
  }

  /// Returns the base type with no attributes or suffix
  pub fn base_type(&self) -> ContentType {
    match self.suffix.as_ref() {
      Some(suffix) => ContentType {
        main_type: self.main_type.clone(),
        sub_type: suffix.clone(),
        .. ContentType::default()
      },
      None => ContentType {
        main_type: self.main_type.clone(),
        sub_type: self.sub_type.clone(),
        .. ContentType::default()
      }
    }
  }

  /// If the content type is the default type
  pub fn is_unknown(&self) -> bool {
    self.main_type == "*" || self.sub_type == "*"
  }

  /// Equals, ignoring attributes if not present on self
  pub fn is_equivalent_to(&self, other: &ContentType) -> bool {
    if self.is_strict_xml() && other.is_strict_xml() {
      self.attributes.is_empty() || self.attributes == other.attributes
    }
    else if self.attributes.is_empty() {
      self.main_type == other.main_type && self.sub_type == other.sub_type
    } else {
      self == other
    }
  }
}

impl Default for ContentType {
  fn default() -> Self {
    ContentType {
      main_type: "*".into(),
      sub_type: "*".into(),
      attributes: BTreeMap::new(),
      suffix: None
    }
  }
}

impl std::fmt::Display for ContentType {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    let base = if let Some(suffix) = &self.suffix {
      format!("{}/{}+{}", self.main_type, self.sub_type, suffix)
    } else {
      format!("{}/{}", self.main_type, self.sub_type)
    };
    if self.attributes.is_empty() {
      write!(f, "{}", base)
    } else {
      write!(f, "{};{}", base, self.attributes.iter()
        .map(|(key, value)| format!("{}={}", key, value)).join(";"))
    }
  }
}

impl From<String> for ContentType {
  fn from(s: String) -> Self {
    ContentType::parse(s.as_str()).unwrap_or_default()
  }
}

impl From<&String> for ContentType {
  fn from(s: &String) -> Self {
    ContentType::parse(s.as_str()).unwrap_or_default()
  }
}

impl From<&str> for ContentType {
  fn from(s: &str) -> Self {
    ContentType::parse(s).unwrap_or_default()
  }
}

impl FromStr for ContentType {
  type Err = String;

  fn from_str(s: &str) -> Result<Self, Self::Err> {
    ContentType::parse(s)
  }
}

impl PartialEq<str> for ContentType {
  fn eq(&self, other: &str) -> bool {
    match ContentType::parse(other) {
      Ok(other) => *self == other,
      Err(_) => false
    }
  }
}

impl PartialEq<&str> for ContentType {
  fn eq(&self, other: &&str) -> bool {
    match ContentType::parse(*other) {
      Ok(other) => *self == other,
      Err(_) => false
    }
  }
}

fn is_match(regex: &Regex, string: &str) -> bool {
  if let Some(m) = regex.find(string) {
    m.start() == 0
  } else {
    false
  }
}

/// Try detect the content type from the contents of a string
pub fn detect_content_type_from_string(s: &String) -> Option<ContentType> {
  log::debug!("Detecting content type from contents: '{}'", s);
  if is_match(&XMLREGEXP, s.as_str()) {
    Some(XML.clone())
  } else if is_match(&HTMLREGEXP, s.to_uppercase().as_str()) {
    Some(HTML.clone())
  } else if is_match(&XMLREGEXP2, s.as_str()) {
    Some(XML.clone())
  } else if is_match(&JSONREGEXP, s.as_str()) {
    Some(JSON.clone())
  } else {
    Some(TEXT.clone())
  }
}

/// Try detect the content type from a sequence bytes
pub fn detect_content_type_from_bytes(s: &[u8]) -> Option<ContentType> {
  debug!("Detecting content type from byte contents");
  let header = if s.len() > 32 {
    &s[0..32]
  } else {
    s
  };
  match from_utf8(header) {
    Ok(s) => {
      if is_match(&XMLREGEXP, s) {
        Some(XML.clone())
      } else if is_match(&HTMLREGEXP, &*s.to_uppercase()) {
        Some(HTML.clone())
      } else if is_match(&XMLREGEXP2, s) {
        Some(XML.clone())
      } else if is_match(&JSONREGEXP, s) {
        Some(JSON.clone())
      } else {
        Some(TEXT.clone())
      }
    },
    Err(_) => None
  }
}

#[cfg(test)]
mod tests {
  use expectest::prelude::*;
  use maplit::btreemap;

  use super::ContentType;

  #[test]
  fn parse_test() {
    let content_type = &ContentType::parse("application/json").unwrap();
    expect!(&content_type.main_type).to(be_equal_to(&"application".to_string()));
    expect!(&content_type.sub_type).to(be_equal_to(&"json".to_string()));
    expect!(content_type.attributes.iter()).to(be_empty());
    expect!(content_type.clone().suffix).to(be_none());

    let content_type = &ContentType::parse("application/json;charset=UTF-16").unwrap();
    expect!(&content_type.main_type).to(be_equal_to(&"application".to_string()));
    expect!(&content_type.sub_type).to(be_equal_to(&"json".to_string()));
    expect!(content_type.clone().attributes).to(be_equal_to(btreemap! {
    "charset".to_string() => "utf-16".to_string()
  }));
    expect!(content_type.clone().suffix).to(be_none());

    let content_type = &ContentType::parse("application/hal+json; charset=UTF-8").unwrap();
    expect!(&content_type.main_type).to(be_equal_to(&"application".to_string()));
    expect!(&content_type.sub_type).to(be_equal_to(&"hal".to_string()));
    expect!(content_type.clone().attributes).to(be_equal_to(btreemap! {
    "charset".to_string() => "utf-8".to_string()
  }));
    expect!(content_type.clone().suffix).to(be_some().value("json".to_string()));
  }

  #[test]
  fn to_string_test() {
    let content_type = ContentType {
      main_type: "application".into(),
      sub_type: "hal+json".into(),
      ..ContentType::default()
    };
    expect!(content_type.to_string()).to(be_equal_to("application/hal+json".to_string()));

    let content_type = ContentType {
      main_type: "application".into(),
      sub_type: "hal".into(),
      suffix: Some("json".into()),
      ..ContentType::default()
    };
    expect!(content_type.to_string()).to(be_equal_to("application/hal+json".to_string()));

    let content_type = ContentType {
      main_type: "application".into(),
      sub_type: "hal+json".into(),
      attributes: btreemap! {
      "charset".to_string() => "UTF-32".to_string(),
      "b".to_string() => "c".to_string()
    },
      suffix: None
    };
    expect!(content_type.to_string()).to(be_equal_to("application/hal+json;b=c;charset=UTF-32".to_string()));
  }

  #[test]
  fn is_json_test() {
    let content_type = ContentType {
      main_type: "application".into(),
      sub_type: "hal".into(),
      suffix: Some("json".to_string()),
      ..ContentType::default()
    };
    expect!(content_type.is_json()).to(be_true());

    let content_type = ContentType {
      main_type: "text".into(),
      sub_type: "javascript".into(),
      ..ContentType::default()
    };
    expect!(content_type.is_json()).to(be_false());

    let content_type = ContentType {
      main_type: "application".into(),
      sub_type: "json".into(),
      ..ContentType::default()
    };
    expect!(content_type.is_json()).to(be_true());

    let content_type = ContentType {
      main_type: "application".into(),
      sub_type: "json-rpc".into(),
      ..ContentType::default()
    };
    expect!(content_type.is_json()).to(be_true());
  }

  #[test]
  fn is_xml_test() {
    let content_type = ContentType::parse("application/atom+xml").unwrap();
    expect!(content_type.is_xml()).to(be_true());

    let content_type = ContentType {
      main_type: "text".into(),
      sub_type: "javascript".into(),
      ..ContentType::default()
    };
    expect!(content_type.is_xml()).to(be_false());

    let content_type = ContentType {
      main_type: "application".into(),
      sub_type: "xml".into(),
      ..ContentType::default()
    };
    expect!(content_type.is_xml()).to(be_true());

    let content_type = ContentType {
      main_type: "text".into(),
      sub_type: "xml".into(),
      ..ContentType::default()
    };
    expect!(content_type.is_xml()).to(be_true());
  }

  #[test]
  fn base_type_test() {
    let content_type = ContentType::parse("application/atom+xml").unwrap();
    expect!(content_type.base_type()).to(be_equal_to(ContentType {
      main_type: "application".into(),
      sub_type: "xml".into(),
      ..ContentType::default()
    }));

    let content_type = ContentType {
      main_type: "text".into(),
      sub_type: "javascript".into(),
      ..ContentType::default()
    };
    expect!(content_type.base_type()).to(be_equal_to(ContentType {
      main_type: "text".into(),
      sub_type: "javascript".into(),
      ..ContentType::default()
    }));

    let content_type = ContentType {
      main_type: "application".into(),
      sub_type: "xml".into(),
      attributes: btreemap! { "charset".to_string() => "UTF-8".to_string() },
      ..ContentType::default()
    };
    expect!(content_type.base_type()).to(be_equal_to(ContentType {
      main_type: "application".into(),
      sub_type: "xml".into(),
      ..ContentType::default()
    }));
  }

  #[test]
  fn is_binary_test() {
    let content_type = ContentType::parse("application/atom+xml").unwrap();
    expect!(content_type.is_binary()).to(be_false());

    let content_type = ContentType {
      main_type: "text".into(),
      sub_type: "javascript".into(),
      ..ContentType::default()
    };
    expect!(content_type.is_binary()).to(be_false());

    let content_type = ContentType {
      main_type: "image".into(),
      sub_type: "jpeg".into(),
      ..ContentType::default()
    };
    expect!(content_type.is_binary()).to(be_true());
  }

  #[test]
  fn xml_equivalent_test() {
    let content_type = ContentType::parse("application/atom+xml").unwrap();
    let content_type2 = ContentType::parse("application/xml").unwrap();
    let content_type3 = ContentType::parse("text/xml").unwrap();
    let content_type4 = ContentType::parse("application/json").unwrap();

    expect!(content_type.is_equivalent_to(&content_type)).to(be_true());
    expect!(content_type.is_equivalent_to(&content_type2)).to(be_false());
    expect!(content_type2.is_equivalent_to(&content_type3)).to(be_true());
    expect!(content_type2.is_equivalent_to(&content_type4)).to(be_false());
  }
}