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
#![allow(clippy::all)]

extern crate mime;

#[macro_use]
pub mod actix_ructe;

use server::actix_web::{HttpRequest, HttpResponse, Result};
use server::actix_web::dev::ServiceResponse;
use server::actix_web::body::Body;
use server::actix_web::http::{header, StatusCode};
use server::actix_web::middleware::errhandlers::ErrorHandlerResponse;
use server::actix_web::http::header::{CacheControl, CacheDirective, ContentType};
use server::actix_web::web;

use config::cfg::{AppConfig, RequestConfig};

#[cfg(debug_assertions)]
fn is_debug() -> bool { true }

#[cfg(not(debug_assertions))]
fn is_debug() -> bool { false }


fn req_config(data: web::Data<AppConfig>, _req: HttpRequest) -> RequestConfig {
  RequestConfig {
    debug: is_debug(),
    theme: String::from("uk-dark"),
    app: data.get_ref().clone()
  }
}

pub fn index(data: web::Data<AppConfig>, req: HttpRequest) -> HttpResponse {
  HttpResponse::Ok().body(render!(templates::index, req_config(data, req), "dbui"))
}

pub fn static_file(path: web::Path<(String,)>) -> HttpResponse {
  let name = &path.0;
  if let Some(data) = templates::statics::StaticFile::get(name) {
    HttpResponse::Ok()
      .set(CacheControl(vec![CacheDirective::MaxAge(86400u32)]))
      .set(ContentType(data.mime.clone()))
      .body(data.content)
  } else {
    HttpResponse::NotFound()
      .reason("No such static file.")
      .finish()
  }
}

pub fn favicon() -> Result<HttpResponse> {
  Ok(HttpResponse::Ok()
    .set(CacheControl(vec![CacheDirective::MaxAge(86400u32)]))
    .set(ContentType(mime::APPLICATION_OCTET_STREAM))
    .body(templates::statics::favicon_ico.content))
}

pub fn render_400(res: ServiceResponse<Body>) -> Result<ErrorHandlerResponse<Body>> {
  error_response(res, StatusCode::NOT_FOUND, "Bad request")
}

pub fn render_404(res: ServiceResponse<Body>) -> Result<ErrorHandlerResponse<Body>> {
  error_response(res, StatusCode::NOT_FOUND, "The resource you requested can't be found")
}

pub fn render_500(res: ServiceResponse<Body>) -> Result<ErrorHandlerResponse<Body>> {
  error_response(res, StatusCode::INTERNAL_SERVER_ERROR, "Something went wrong; this is probably not your fault")
}

fn error_response(mut res: ServiceResponse<Body>, status_code: StatusCode, message: &str) -> Result<ErrorHandlerResponse<Body>> {
  res.headers_mut().insert(
    header::CONTENT_TYPE,
    header::HeaderValue::from_str(mime::TEXT_HTML_UTF_8.as_ref())
      .unwrap(),
  );
  Ok(ErrorHandlerResponse::Response(res.map_body(
    |_head, _body| {
      actix_web::dev::ResponseBody::Body(
        render!(templates::error::error, status_code, message).into(),
      )
    },
  )))
}

include!(concat!(env!("OUT_DIR"), "/templates.rs"));