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
use super::directory::index::IndexStrategy;
use crate::config::{ContentDispositionConfig, PathConfig, PathMatcherConfig, ServerConfig};
use actix_web::http::header::{self, DispositionType, HeaderMap};
use regex::Regex;
use snafu::{ResultExt, Snafu};
use std::{
  collections::HashMap,
  convert::{TryFrom, TryInto},
  fmt::Debug,
  path::{Path, PathBuf},
};

#[derive(Snafu, Debug)]
pub enum Error {
  #[snafu(display("Failed to parse the Mime type."))]
  ParseMime { source: mime::FromStrError },
  #[snafu(display("Failed to parse the header name: {}", name))]
  ParseHeaderName {
    source: header::InvalidHeaderName,
    name: String,
  },
  #[snafu(display("Failed to parse the header value: {}", value))]
  ParseHeaderValue {
    source: header::InvalidHeaderValue,
    value: String,
  },
  #[snafu(display("Failed to compile the Regex pattern: {}", pattern))]
  InvalidRegexPattern {
    pattern: String,
    source: regex::Error,
  },
}

type Result<T, E = Error> = std::result::Result<T, E>;

#[derive(Clone, Debug)]
enum PathMatcher {
  Static { path: PathBuf },
  Prefix { prefix: String },
  Regex { regex: Regex },
}

impl PathMatcher {
  pub fn matches_path<P: AsRef<Path>>(&self, input_path: P) -> bool {
    let input_path = input_path.as_ref();

    match self {
      Self::Static { path } => input_path.eq(path),
      Self::Prefix { prefix } => input_path.starts_with(prefix),
      Self::Regex { regex } => match input_path.to_str() {
        Some(raw_input_path) => regex.is_match(raw_input_path),
        None => false,
      },
    }
  }
}

impl TryFrom<&PathMatcherConfig> for PathMatcher {
  type Error = Error;

  fn try_from(config: &PathMatcherConfig) -> Result<Self, Self::Error> {
    Ok(match config {
      PathMatcherConfig::StaticMatcher { path } => PathMatcher::Static {
        path: PathBuf::from(path.clone()),
      },
      PathMatcherConfig::PrefixMatcher { prefix } => PathMatcher::Prefix {
        prefix: prefix.clone(),
      },
      PathMatcherConfig::RegexMatcher { pattern } => PathMatcher::Regex {
        regex: Regex::new(pattern).context(InvalidRegexPattern {
          pattern: pattern.clone(),
        })?,
      },
    })
  }
}

#[derive(Clone)]
pub struct PathContext {
  matcher: Option<PathMatcher>,
  mime_disposition: Option<HashMap<mime::Mime, DispositionType>>,
  set_etag: Option<bool>,
  set_last_modified: Option<bool>,
  index_strategy: Option<IndexStrategy>,
  headers: Option<HeaderMap>,
  not_found_path: Option<PathBuf>,
}

impl PathContext {
  pub fn matches_path<P: AsRef<Path>>(&self, input_path: P) -> bool {
    if let Some(matcher) = &self.matcher {
      matcher.matches_path(input_path)
    } else {
      true
    }
  }

  /// Combines the configuration entries on this context with another.
  ///
  /// Useful for overlaying configurations. e.g. Defaults + Configuration.
  pub fn merge(&self, other: &Self) -> Self {
    PathContext {
      matcher: other.matcher.clone(),
      mime_disposition: other
        .mime_disposition
        .clone()
        .or_else(|| self.mime_disposition.clone()),
      set_etag: other.set_etag.or(self.set_etag),
      set_last_modified: other.set_last_modified.or(self.set_last_modified),
      index_strategy: other
        .index_strategy
        .clone()
        .or_else(|| self.index_strategy.clone()),
      headers: other.headers.clone().or_else(|| self.headers.clone()),
      not_found_path: other
        .not_found_path
        .clone()
        .or_else(|| self.not_found_path.clone()),
    }
  }

  pub fn get_mime_disposition(&self) -> &Option<HashMap<mime::Mime, DispositionType>> {
    &self.mime_disposition
  }

  pub fn get_index_strategy_or_default(&self) -> &IndexStrategy {
    if let Some(index_strategy) = &self.index_strategy {
      index_strategy
    } else {
      &IndexStrategy::NoIndex
    }
  }

  pub fn get_use_etag_or_default(&self) -> bool {
    self.set_etag.unwrap_or(true)
  }

  pub fn get_use_last_modifiedor_default(&self) -> bool {
    self.set_last_modified.unwrap_or(true)
  }

  pub fn append_headers_to_map(&self, header_map: &mut HeaderMap) {
    if let Some(headers) = &self.headers {
      for (header_name, header_value) in headers.iter() {
        if header_map.contains_key(header_name) {
          log::warn!(
            "Unable to replace header '{}' since it was already set.",
            header_name
          );
        } else {
          header_map.insert(header_name.clone(), header_value.clone());
        }
      }
    }
  }

  pub fn get_not_found_path(&self) -> &Option<PathBuf> {
    &self.not_found_path
  }
}

impl Debug for PathContext {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(f, "PathContext (Matcher: {:?})", self.matcher)
  }
}

impl TryFrom<&PathConfig> for PathContext {
  type Error = Error;

  fn try_from(config: &PathConfig) -> Result<Self, Error> {
    let mime_disposition = try_get_mime_disposition(&config.mime_disposition)?;
    let headers = try_get_headers(&config.headers)?;

    let matcher = (&config.matcher).try_into()?;

    Ok(PathContext {
      matcher: Some(matcher),
      mime_disposition,
      index_strategy: config.index_strategy.clone().map(|x| x.into()),
      set_etag: config.set_etag,
      set_last_modified: config.set_last_modified,
      headers,
      not_found_path: config.not_found_path.clone(),
    })
  }
}

impl TryFrom<&ServerConfig> for PathContext {
  type Error = Error;

  fn try_from(config: &ServerConfig) -> Result<Self, Error> {
    let mime_disposition = try_get_mime_disposition(&config.mime_disposition)?;
    let headers = try_get_headers(&config.headers)?;

    Ok(PathContext {
      matcher: None,
      mime_disposition,
      index_strategy: config.index_strategy.clone().map(|x| x.into()),
      set_etag: config.set_etag,
      set_last_modified: config.set_last_modified,
      headers,
      not_found_path: config.not_found_path.clone(),
    })
  }
}

fn try_get_mime_disposition(
  mime_disposition: &Option<HashMap<String, ContentDispositionConfig>>,
) -> Result<Option<HashMap<mime::Mime, DispositionType>>> {
  Ok(if let Some(mime_disposition) = mime_disposition {
    let mut new_mime_disposition = HashMap::new();

    for (key, value) in mime_disposition.iter() {
      new_mime_disposition.insert(
        key.clone().parse().context(ParseMime)?,
        match value {
          ContentDispositionConfig::Inline => DispositionType::Inline,
          ContentDispositionConfig::Attachment => DispositionType::Attachment,
        },
      );
    }

    Some(new_mime_disposition)
  } else {
    None
  })
}

fn try_get_headers(headers: &Option<HashMap<String, String>>) -> Result<Option<HeaderMap>> {
  Ok(if let Some(headers) = headers {
    let mut new_headers = HeaderMap::new();

    for (name, value) in headers {
      new_headers.insert(
        name
          .parse()
          .context(ParseHeaderName { name: name.clone() })?,
        value.parse().context(ParseHeaderValue {
          value: value.clone(),
        })?,
      );
    }

    Some(new_headers)
  } else {
    None
  })
}

#[cfg(test)]
mod tests {
  use super::PathMatcher;
  use regex::Regex;

  #[test]
  fn test_static_path_matcher() {
    assert!(PathMatcher::Static {
      path: "hello/world.png".into(),
    }
    .matches_path("hello/world.png"),);

    assert!(!PathMatcher::Static {
      path: "hello/world.tar.gz".into(),
    }
    .matches_path("hello/world.png"),);
  }

  #[test]
  fn test_prefix_path_matcher() {
    assert!(PathMatcher::Prefix {
      prefix: "hello/".into(),
    }
    .matches_path("hello/world.png"),);

    assert!(!PathMatcher::Prefix {
      prefix: "hello/bye".into(),
    }
    .matches_path("hello/world.png"),);
  }

  #[test]
  fn test_regex_path_matcher() {
    assert!(Regex::new(r"\.png$").unwrap().is_match("hello/world.png"),);

    assert!(Regex::new(r"\.(js|css|png|jpg|jpeg|gif|ico)$")
      .unwrap()
      .is_match("hello/world.png"),);

    assert!(!PathMatcher::Regex {
      regex: Regex::new(r"\.png$").unwrap(),
    }
    .matches_path("hello/world.tar.gz"),);
  }
}