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

use super::{ with_file, with_partial_file };
use super::{ IntoPathBuf, Caching, Range };

use crate::{ Error, Data };
use crate::routes::{ Route, check_static };
use crate::into::IntoResponse;
use crate::error::ClientErrorKind;
use crate::util::PinnedFuture;
use crate::request::Request;

use std::path::{ Path, PathBuf };
use std::time::Duration;
use std::io;

use http::header::{ RequestHeader, Method };
use http::Response;


/// returns io::Error not found if path is directory
pub async fn serve_file(
	path: impl AsRef<Path>,
	req: &Request,
	caching: Option<Caching>
) -> io::Result<Response> {

	// check caching
	if matches!(&caching, Some(c) if c.if_none_match(req.header())) {
		return Ok(caching.unwrap().into_response())
	}

	let range = Range::parse(req.header());

	let mut res = match range {
		Some(range) => {
			with_partial_file(path, range).await?
				.into_response()
		},
		None => {
			with_file(path).await?
				.into_response()
		}
	};

	// set etag
	if let Some(caching) = caching {
		caching.complete_header(&mut res.header);
	}

	Ok(res)
}




pub struct StaticFilesRoute {
	uri: &'static str,
	path: PathBuf,
	caching: Option<Caching>
}

impl StaticFilesRoute {

	pub fn new(uri: &'static str, raw_path: &'static str) -> Self {
		Self::prv_new(uri, raw_path, None)
	}

	pub fn new_raw(
		uri: &'static str,
		path: PathBuf,
		caching: Option<Caching>
	) -> Self {
		Self { uri, path, caching }
	}

	fn prv_new(
		uri: &'static str,
		raw_path: &'static str,
		caching: Option<Caching>
	) -> Self {
		let path = PathBuf::from(raw_path);
		Self { uri, path, caching }
	}

	pub fn cache(uri: &'static str, raw_path: &'static str) -> Self {
		Self::prv_new(uri, raw_path, Some(Caching::default()))
	}

	pub fn cache_with_age(
		uri: &'static str,
		raw_path: &'static str,
		max_age: Duration
	) -> Self {
		Self::prv_new(uri, raw_path, Some(Caching::new(max_age)))
	}

}

impl<D: Data> Route<D> for StaticFilesRoute {

	fn check(&self, header: &RequestHeader) -> bool {
		header.method() == &Method::Get &&
		header.uri().path().starts_with(self.uri)
	}

	fn call<'a>(
		&'a self,
		req: &'a mut Request,
		_: &'a D
	) -> PinnedFuture<'a, crate::Result<Response>> {

		let mut full_path_buf = self.path.clone();
		let uri = self.uri;
		let caching = self.caching.clone();

		PinnedFuture::new(async move {

			let res_path_buf = req.header().uri()
				.path()[uri.len()..]
				.into_path_buf();

			// validate path buf
			// if path is a directory serve_file will return NotFound
			let path_buf = res_path_buf
				.map_err(|e| Error::new(ClientErrorKind::NotFound, e))?;

			// build full pathbuf
			full_path_buf.push(path_buf);

			serve_file(full_path_buf, &req, caching).await
				.map_err(Error::from_client_io)
		})
	}

}


/// Static get handler which servers files from a directory.
/// 
/// ## Example
/// ```
/// # use fire_http as fire;
/// use std::time::Duration;
/// use fire::static_files;
/// 
/// type Data = ();
/// 
/// static_files! { Files, "/files" => "./www/" }
/// 
/// #[tokio::main]
/// async fn main() {
/// 	let mut server = fire::build("127.0.0.1:0", ()).unwrap();
/// 	// adds the handler without any caching
/// 	server.add_route(Files::new());
/// 	// adds caching in release builds
/// 	server.add_route(Files::cache());
/// 	// adds caching with customized Max Age in release builds
/// 	server.add_route(Files::cache_with_age(Duration::from_secs(60)));
/// }
/// ```
/// 
/// ## Caching
/// Todo: document caveats
#[macro_export]
macro_rules! static_files {
	($name:ident, $uri:expr => $path:expr) => (

		pub struct $name;

		impl $name {
			pub fn new() -> $crate::fs::StaticFilesRoute {
				$crate::fs::StaticFilesRoute::new($uri, $path)
			}

			// only caches on release
			pub fn cache() -> $crate::fs::StaticFilesRoute {
				if cfg!(debug_assertions) {
					Self::new()
				} else {
					$crate::fs::StaticFilesRoute::cache($uri, $path)
				}
			}

			pub fn cache_with_age(
				max_age: std::time::Duration
			) -> $crate::fs::StaticFilesRoute {
				if cfg!(debug_assertions) {
					Self::new()
				} else {
					$crate::fs::StaticFilesRoute::cache_with_age(
						$uri,
						$path,
						max_age
					)
				}
			}

			pub fn cache_no_age() -> $crate::fs::StaticFilesRoute {
				Self::cache_with_age(std::time::Duration::from_secs(0))
			}

			pub fn cache_always() -> $crate::fs::StaticFilesRoute {
				$crate::fs::StaticFilesRoute::cache($uri, $path)
			}
		}

	)
}


#[derive(Debug, Clone)]
pub struct StaticFileRoute {
	uri: &'static str,
	path: &'static str,
	caching: Option<Caching>
}

impl StaticFileRoute {

	pub fn new(uri: &'static str, path: &'static str) -> Self {
		Self { uri, path, caching: None }
	}

	pub fn cache(uri: &'static str, path: &'static str) -> Self {
		Self { uri, path, caching: Some(Caching::default()) }
	}

	pub fn cache_with_age(
		uri: &'static str,
		path: &'static str,
		max_age: Duration
	) -> Self {
		Self { uri, path, caching: Some(Caching::new(max_age)) }
	}

}

impl<D: Data> Route<D> for StaticFileRoute {

	fn check(&self, header: &RequestHeader) -> bool {
		header.method() == &Method::Get
		&& check_static(header.uri().path(), self.uri)
	}

	fn call<'a>(
		&'a self,
		req: &'a mut Request,
		_: &D
	) -> PinnedFuture<'a, crate::Result<Response>> {

		let path = self.path;
		let caching = self.caching.clone();

		PinnedFuture::new(async move {
			serve_file(path, &req, caching).await
				.map_err(Error::from_client_io)
		})
	}

}


#[macro_export]
macro_rules! static_file {
	($name:ident, $uri:expr => $path:expr) => (

		pub struct $name;

		impl $name {
			pub fn new() -> $crate::fs::StaticFileRoute {
				$crate::fs::StaticFileRoute::new($uri, $path)
			}

			// only caches on release
			pub fn cache() -> $crate::fs::StaticFileRoute {
				if cfg!(debug_assertions) {
					$crate::fs::StaticFileRoute::new($uri, $path)
				} else {
					$crate::fs::StaticFileRoute::cache($uri, $path)
				}
			}

			pub fn cache_with_age(
				max_age: std::time::Duration
			) -> $crate::fs::StaticFileRoute {
				if cfg!(debug_assertions) {
					$crate::fs::StaticFileRoute::new($uri, $path)
				} else {
					$crate::fs::StaticFileRoute::cache_with_age(
						$uri,
						$path,
						max_age
					)
				}
			}

			pub fn cache_no_age() -> $crate::fs::StaticFileRoute {
				Self::cache_with_age(std::time::Duration::from_secs(0))
			}

			pub fn cache_always() -> $crate::fs::StaticFileRoute {
				$crate::fs::StaticFileRoute::cache($uri, $path)
			}
		}

	)
}

/// Dynamic get request handler which servers a file if a path is provided.
/// 
/// 
/// Can be used if the uri needs to be mapped from a database
/// or for example if a file is only available for certain users.
/// 
/// ## Example
/// ```
/// # use fire_http as fire;
/// use fire::dyn_static_files;
/// 
/// type Data = ();
/// 
/// dyn_static_files! {
/// 	DynamicFiles, "/files/",
/// 	|req| { // needs to return fire::Result<PathBuf>
/// 		unimplemented!()
/// 	}
/// }
/// 
/// ```
#[macro_export]
macro_rules! dyn_static_files {
	($name:ident, $uri:expr, |$req:ident| $block:block) => (
		$crate::dyn_static_files!($name, $uri, self, |$req,| $block);
	);
	($name:ident, $uri:expr, $self:ident, |$req:ident| $block:block) => (
		$crate::dyn_static_files!($name, $uri, $self, |$req,| $block);
	);
	($name:ident, $uri:expr, |$req:ident, $($data:ident),*| $block:block) => (
		$crate::dyn_static_files!($name, $uri, self, |$req, $($data),*| $block);
	);
	(
		$name:ident,
		$uri:expr,
		$self:ident,
		|$req:ident, $($data:ident),*| $block:block
	) => (

		pub struct $name {
			caching: Option<$crate::fs::Caching>
		}

		impl $name {

			pub fn new() -> Self {
				Self { caching: None }
			}

			pub fn cache() -> Self {
				Self {
					caching: match cfg!(debug_assertions) {
						true => None,
						false => Some($crate::fs::Caching::default())
					}
				}
			}

			pub fn cache_with_age(max_age: std::time::Duration) -> Self {
				Self {
					caching: match cfg!(debug_assertions) {
						true => None,
						false => Some($crate::fs::Caching::new(max_age))
					}
				}
			}

			pub fn cache_always() -> Self {
				Self {
					caching: Some($crate::fs::Caching::default())
				}
			}

			pub fn req_uri<'a>(
				&self,
				req: &'a $crate::request::Request
			) -> &'a str {
				&req.header().uri().path()[$uri.len()..]
			}

		}

		impl $crate::routes::Route<Data> for $name {

			fn check(
				&self,
				header: &$crate::http::header::RequestHeader
			) -> bool {
				header.method() == &$crate::http::header::Method::Get
				&& header.uri().path().starts_with($uri)
			}

			fn call<'a>(
				&'a $self,
				$req: &'a mut $crate::request::Request,
				raw_data: &'a Data
			) -> $crate::util::PinnedFuture<'a, $crate::Result<$crate::http::Response>> {

				let caching = $self.caching.clone();

				$crate::util::PinnedFuture::new(async move {

					$(let $data = raw_data.$data();)*

					let path_buf: $crate::Result<std::path::PathBuf> = async {
						$block
					}.await;

					let path_buf = path_buf?;

					$crate::fs::serve_file(path_buf, &$req, caching).await
						.map_err($crate::Error::from_client_io)
				})
			}

		}

	)
}