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
use rouille;
use rouille::router;
use serde::Deserialize;
use serde::Serialize;
use serde_json;

use url::form_urlencoded;

use chrono::offset::Local;
use chrono::DateTime;
use chrono::NaiveDateTime;

use log::warn;

use crate::errors::Error;
use crate::errors::ErrorKind;

use crate::tests::questions::models::AnonymousQuestionList;
use crate::tests::questions::models::ResponseQuestionList;

use super::schema::test_session_registrations;
use super::schema::test_sessions;

#[derive(Queryable, Debug)]
pub struct RawTestSession {
    pub id: u64,
    pub test_id: u64,
    pub name: String,
    pub max_registrations: Option<u32>,
    pub registrations_enabled: bool,
    pub opening_enabled: bool,
    pub submissions_enabled: bool,
}

#[derive(Insertable, Debug)]
#[table_name = "test_sessions"]
pub struct NewRawTestSession {
    pub test_id: u64,
    pub name: String,
    pub max_registrations: Option<u32>,
    pub registrations_enabled: bool,
    pub opening_enabled: bool,
    pub submissions_enabled: bool,
}

#[derive(Queryable, Debug)]
pub struct RawTestSessionRegistration {
    pub id: u64,
    pub test_session_id: u64,
    pub taker_id: u64,
    pub registered: NaiveDateTime,
    pub opened_test: Option<NaiveDateTime>,
    pub submitted_test: Option<NaiveDateTime>,
    pub score: Option<f32>,
}

#[derive(Insertable, Debug)]
#[table_name = "test_session_registrations"]
pub struct NewRawTestSessionRegistration {
    pub test_session_id: u64,
    pub taker_id: u64,
    pub registered: NaiveDateTime,
    pub opened_test: Option<NaiveDateTime>,
    pub submitted_test: Option<NaiveDateTime>,
    pub score: Option<f32>,
}

#[derive(Debug, AsChangeset)]
#[table_name = "test_session_registrations"]
pub struct PartialRawTestSessionRegistration {
    pub taker_id: Option<u64>,
    pub registered: Option<NaiveDateTime>,
    pub opened_test: Option<Option<NaiveDateTime>>,
    pub submitted_test: Option<Option<NaiveDateTime>>,
    pub score: Option<Option<f32>>,
}

#[derive(Queryable, Debug)]
pub struct JoinedTestSession {
    pub test_session: RawTestSession,
    pub test_session_registration: Option<RawTestSessionRegistration>,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct TestSession {
    pub id: u64,
    pub test_id: u64,
    pub name: String,
    pub max_registrations: Option<u32>,
    pub registrations: Vec<TestSessionRegistration>,
    pub registrations_enabled: bool,
    pub opening_enabled: bool,
    pub submissions_enabled: bool,
}

#[derive(Serialize, Deserialize)]
pub struct NewTestSession {
    pub test_id: u64,
    pub name: String,
    pub max_registrations: Option<u32>,
}

#[derive(AsChangeset, Serialize, Deserialize, Debug)]
#[table_name = "test_sessions"]
pub struct PartialTestSession {
    pub registrations_enabled: Option<bool>,
    pub opening_enabled: Option<bool>,
    pub submissions_enabled: Option<bool>,
}

#[derive(Serialize, Deserialize)]
pub struct TestSessionList {
    pub test_sessions: Vec<TestSession>,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct TestSessionRegistration {
    pub id: u64,
    pub taker_id: u64,
    pub registered: DateTime<Local>,
    pub opened_test: Option<DateTime<Local>>,
    pub submitted_test: Option<DateTime<Local>>,
    pub score: Option<f32>,
}

pub enum TestSessionRequest {
    GetTestSessions(Option<u64>),
    GetTestSession(u64),
    CreateTestSession(NewTestSession),
    UpdateTestSession(u64, PartialTestSession),
    DeleteTestSession(u64),
    Register(u64),
    Unregister(u64, Option<u64>),
    Open(u64),
    Submit(u64, ResponseQuestionList),
    Certificate(u64),
}

impl TestSessionRequest {
    pub fn from_rouille(request: &rouille::Request) -> Result<TestSessionRequest, Error> {
        let mut url_queries = form_urlencoded::parse(request.raw_query_string().as_bytes());
        router!(request,
            (GET) (/) => {

                let test_id = url_queries.find_map(|q| {
                    if q.0 == "test_id" {
                        q.1.parse().ok()
                    } else {
                        None
                    }
                });

                Ok(TestSessionRequest::GetTestSessions(test_id))
            },

            (GET) (/{id: u64}) => {
                Ok(TestSessionRequest::GetTestSession(id))
            },

            (GET) (/certificates/{id: u64}) => {
                Ok(TestSessionRequest::Certificate(id))
            },

            (POST) (/{id: u64}/register) => {
                Ok(TestSessionRequest::Register(id))
            },

            (POST) (/{test_session_id: u64}/unregister) => {
                Ok(TestSessionRequest::Unregister(test_session_id, None))
            },

            (POST) (/{test_session_id: u64}/unregister/{user_id: u64}) => {
                Ok(TestSessionRequest::Unregister(test_session_id, Some(user_id)))
            },

            (GET) (/{id: u64}/open) => {
                Ok(TestSessionRequest::Open(id))
            },

            (POST) (/{id: u64}/submit) => {
                let request_body = request.data()
                    .ok_or(Error::new(ErrorKind::Body))?;
                let respose_questions: ResponseQuestionList =
                    serde_json::from_reader(request_body)?;
                Ok(TestSessionRequest::Submit(id, respose_questions))
            },

            (POST) (/) => {
                let request_body = request.data()
                    .ok_or(Error::new(ErrorKind::Body))?;
                let new_question: NewTestSession =
                    serde_json::from_reader(request_body)?;
                Ok(TestSessionRequest::CreateTestSession(new_question))
            },

            (PUT) (/{id: u64}) => {
                let request_body = request.data()
                    .ok_or(Error::new(ErrorKind::Body))?;
                let partial_test_session: PartialTestSession =
                    serde_json::from_reader(request_body)?;
                Ok(TestSessionRequest::UpdateTestSession(id, partial_test_session))
            },

            (DELETE) (/{id: u64}) => {
                Ok(TestSessionRequest::DeleteTestSession(id))
            },

            _ => {
                warn!("Could not create a question request for the given rouille request");
                Err(Error::new(ErrorKind::NotFound))
            }
        )
    }
}

pub enum TestSessionResponse {
    OneTestSession(TestSession),
    ManyTestSessions(TestSessionList),
    AnonymousQuestions(AnonymousQuestionList),
    TestSessionRegistration(TestSessionRegistration),
    Image(Vec<u8>),
    NoResponse,
}

impl TestSessionResponse {
    pub fn to_rouille(self) -> rouille::Response {
        match self {
            TestSessionResponse::OneTestSession(test_session) => {
                rouille::Response::json(&test_session)
            }
            TestSessionResponse::ManyTestSessions(test_sessions) => {
                rouille::Response::json(&test_sessions)
            }
            TestSessionResponse::TestSessionRegistration(registration) => {
                rouille::Response::json(&registration)
            }
            TestSessionResponse::AnonymousQuestions(questions) => {
                rouille::Response::json(&questions)
            }
            TestSessionResponse::Image(bytes) => {
                rouille::Response::from_data("image/png", bytes)
            }
            TestSessionResponse::NoResponse => rouille::Response::empty_204(),
        }
    }
}