summaryrefslogtreecommitdiff
path: root/src/server.rs
blob: e20bb96a7b7ae61e996ed22140d2ca0cfceed539 (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
use data;

use handlebars_iron::{HandlebarsEngine, MemorySource, Template};
use iron::headers::ContentType;
use iron::modifiers::Header;
use iron::{self, Iron, Plugin, Chain, Request, Response, IronResult, status};
use rusqlite::Connection;
use std::collections::BTreeMap;
use persistent::Write;
use handlebars_iron::handlebars::to_json;
use serde_json::Map;
use params;
use error::LinoError;

#[derive(Debug)]
pub struct State {
    pub connection: Connection,
}
impl iron::typemap::Key for State {
    type Value = State;
}

fn get_param(r: &mut Request, param: &str) -> IronResult<String> {
    let map = itry!(r.get_ref::<params::Params>());
    match map.get(param) {
        Some(&params::Value::String(ref v)) => Ok(v.to_string()),
        _ => Err(From::from(LinoError::NotFound(param.to_string()))),
    }
}

fn make_renderer() -> HandlebarsEngine {
    let mut e = HandlebarsEngine::new();

    let mut templates = BTreeMap::new();
    templates.insert(
        "quotes".to_string(),
        include_str!("data/templates/quotes.hbs").to_string(),
    );
    templates.insert(
        "add".to_string(),
        include_str!("data/templates/add.hbs").to_string(),
    );
    templates.insert(
        "add_post".to_string(),
        include_str!("data/templates/add_post.hbs").to_string(),
    );
    templates.insert(
        "approve".to_string(),
        include_str!("data/templates/approve.hbs").to_string(),
    );

    e.add(Box::new(MemorySource(templates)));
    if let Err(r) = e.reload() {
        panic!("Error loading templates: {}", r)
    }
    e
}

fn quotes(r: &mut Request) -> IronResult<Response> {
    let mut result = Map::new();
    let quote_id = get_param(r, "id").ok().and_then(
        |id| id.parse::<i64>().ok(),
    );
    let ordering = get_param(r, "order").unwrap_or("".to_string());

    let quotes = {
        let mu = r.get::<Write<State>>().unwrap();
        let state = mu.lock().unwrap();
        match quote_id {
            Some(id) => vec![data::get_quote(&state.connection, id)?],
            None => data::get_quotes(&state.connection, &ordering)?,
        }
    };
    result.insert("quotes".to_string(), to_json(&quotes));
    Ok(Response::with((
        status::Ok,
        Header(ContentType::html()),
        Template::new("quotes", result),
    )))
}

fn add_get(r: &mut Request) -> IronResult<Response> {
    Ok(Response::with((
        status::Ok,
        Header(ContentType::html()),
        Template::new("add", Map::new()),
    )))
}

fn add_post(r: &mut Request) -> IronResult<Response> {
    let nick = get_param(r, "nick")?;
    let date = get_param(r, "date")?;
    let quote = get_param(r, "quote")?;

    macro_rules! check {
      ($i:ident) => (
        if $i.is_empty() {
          return Err(From::from(LinoError::BadRequest(
              format!("missing parameter: {}", stringify!($i)))));
        }
      )
    }
    check!(nick);
    check!(date);
    check!(quote);

    {
        let mu = r.get::<Write<State>>().unwrap();
        let state = mu.lock().unwrap();
        data::new_quote(&state.connection, &date, &nick, &quote)?;
    }

    Ok(Response::with((
        status::Ok,
        Header(ContentType::html()),
        Template::new("add_post", Map::new()),
    )))
}

fn approve(r: &mut Request) -> IronResult<Response> {
    let mut result = Map::new();
    let quote_id = get_param(r, "id").ok().and_then(
        |id| id.parse::<i64>().ok(),
    );
    let action = get_param(r, "action").unwrap_or("".to_string());

    let quotes = {
        let mu = r.get::<Write<State>>().unwrap();
        let state = mu.lock().unwrap();
        if let Some(quote_id) = quote_id {
            info!("Approval for quote({}): {}", quote_id, action);
            if action == "approve" {
                data::approve_quote(&state.connection, quote_id)?;
            } else if action == "reject" {
                data::delete_quote(&state.connection, quote_id)?;
            } else {
                return Err(From::from(
                    LinoError::BadRequest(format!("invalid action: {}", action)),
                ));
            }
        }
        data::get_pending_quotes(&state.connection)?
    };
    result.insert("quotes".to_string(), to_json(&quotes));
    Ok(Response::with((
        status::Ok,
        Header(ContentType::html()),
        Template::new("approve", result),
    )))
}

pub fn serve(state: State, port: u16) {
    let router =
        router!(
        index: get "/" => quotes,
        add_get: get "/add.jsp" => add_get,
        add_post: post "/add.jsp" => add_post,
        quotes_jsp: get "/quotes.jsp" => quotes,
        view_quote: get "/view_quote" => quotes,
        approve: get "/approve.jsp" => approve,
    );
    let mut chain = Chain::new(router);
    chain.link_after(make_renderer());
    chain.link(Write::<State>::both(state));
    let bind_address = format!("{}:{}", "::", port);
    let _server = Iron::new(chain).http(bind_address.as_str());
    info!("Serving on {}", bind_address);
}