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
use std::convert::Infallible;
use std::collections::HashMap;
use warp::http::StatusCode;
use log::*;

use crate::db::{self, DbConn};
use crate::models::comment::{self, Comment};
use crate::models::reply::{self, Reply};
use crate::models::upvote::{self, Upvote};
use crate::models::downvote::{self, Downvote};
use crate::models::status::Status;

pub async fn list_comments(
    db_conn: DbConn,
) -> Result<impl warp::Reply, Infallible> {
    let mut results: Vec<Comment> = Vec::new();
    match db::get_all_comments(db_conn).await {
        Ok(data) => results = data,
        Err(message) => error!("{:?} occurred in handlers::list_comments()", message),
    };
    let filtered: Vec<Comment> = results.into_iter().filter(|each| 
        each.status == Status::Pending 
        || each.status == Status::Approved 
        || each.status == Status:: Disabled 
    ).collect();
    Ok( warp::reply::json( &filtered ) )
}

pub async fn more_comments(
    count: usize,
    db_conn: DbConn,
) -> Result<impl warp::Reply, Infallible> {
    let mut results: Vec<Comment> = Vec::new();
    match db::get_more_comments(count, db_conn).await {
        Ok(data) => results = data,
        Err(message) => error!("{:?} occurred in handlers::more_comments()", message),
    };
    let filtered: Vec<Comment> = results.into_iter().filter(|each| 
        each.status == Status::Pending 
        || each.status == Status::Approved 
        || each.status == Status:: Disabled 
    ).collect();
    Ok( warp::reply::json( &filtered ) )    
}

pub async fn add_comment(
    new_comment: Comment,
    db_conn: DbConn,
) -> Result<impl warp::Reply, Infallible> {
    debug!("add comment: {:?}", new_comment);
    let mut comment_clone = new_comment.clone();
    comment::assign_uid(&mut comment_clone);
    comment::assign_created_date(&mut comment_clone);
    let result = db::add_comment(&comment_clone, db_conn).await;
    let code = process_db_result( result );
    Ok(code)
}

fn process_db_result(result: Result<usize, rusqlite::Error>) -> warp::http::StatusCode {
    match result {
        Ok(count) => {
            match count {
                1 => StatusCode::NO_CONTENT,
                _ => StatusCode::NOT_FOUND
            }
        },
        Err(error) => {
            error!("Error: {} occurred in process_db_result...........", &error);
            StatusCode::NOT_FOUND
        }
    }
}

pub async fn update_comment(
    uid: String,
    mut comment: Comment,
    db_conn: DbConn,
) -> Result<impl warp::Reply, Infallible> {
    debug!("update comment: uid = {}, comment = {:?}", uid, comment);
    comment.unique_id = uid;
    comment.remarks = String::from("several fields are updated");
    comment::assign_updated_date(&mut comment);
    let result = db::update_comment(&comment, db_conn).await;
    let code = process_db_result( result );
    Ok(code)
}

pub async fn update_comment_status(
    stat: String,
    uid: String,
    db_conn: DbConn,
) -> Result<impl warp::Reply, Infallible> {
    debug!("update comment status: stat = {}, uid = {}", &stat, uid);
    let now: String = comment::timestamp_now();
    let status: Status = Status::from_string(stat);
    let result = db::update_comment_status(status, uid, now, db_conn).await;
    let code = process_db_result( result );
    Ok(code)
}

pub async fn update_comment_message(
    uid: String,
    map: HashMap<String, String>,
    db_conn: DbConn,
) -> Result<impl warp::Reply, Infallible> {
    debug!("update comment message: uid = {}, new-message: {:?}+++++++++++++++++++++++++++", &uid, &map);
    let now: String = comment::timestamp_now();
    let msg = map.get("message").unwrap();
    let result = db::update_comment_message(msg.to_string(), uid, now, db_conn).await;
    let code = process_db_result(result);
    Ok(code)
}

pub async fn delete_comment(
    uid: String, 
    db_conn: DbConn
) -> Result<impl warp::Reply, Infallible> {
    debug!("delete comment: uid = {}", uid);
    let now: String = comment::timestamp_now();
    let result = db::delete_comment(&uid, now, db_conn).await;
    let code = process_db_result( result );
    Ok(code)
}

pub async fn get_comment(
    uid: String, 
    db_conn: DbConn
) -> Result<impl warp::Reply, Infallible> {
    // just return a json of comment for the given uid 
    debug!("get comment: uid = {}", uid);
    match db::get_comment(&uid, db_conn).await {
        Ok(data) => Ok( warp::reply::json( &data ) ),
        Err(message) => {
            error!("{} occurred in handlers::get_comment()", message);
            Ok( warp::reply::json( &"No Data Found" ) )
        },
    }

}

pub async fn comments_total(
    db_conn: DbConn,
) -> Result<impl warp::Reply, Infallible> {
    let total: u32 = match db::get_comments_total(db_conn).await {
        Ok(data) => data,
        Err(message) => {
            error!("{:?} occurred in handlers::comments_total()", message);
            0u32
        }
    };
    Ok( warp::reply::json( &total ) )
}

// Reply functions
pub async fn add_reply(
    new_reply: Reply,
    db_conn: DbConn,
) -> Result<impl warp::Reply, Infallible> {
    debug!("add reply: {:?}", new_reply);
    let mut reply_clone = new_reply.clone();
    reply::assign_uid(&mut reply_clone);
    reply::assign_created_date(&mut reply_clone);
    let result = db::add_reply(&reply_clone, db_conn).await;
    let code = process_db_result( result );
    Ok(code)
}

pub async fn list_replies(
    comment_id: String,
    db_conn: DbConn,
) -> Result<impl warp::Reply, Infallible> {
    let mut results: Vec<Reply> = Vec::new();
    match db::get_replies(comment_id, &Status::Pending.to_string(), db_conn).await {
        Ok(data) => results = data,
        Err(message) => error!("{:?} occurred in handlers::list_replies()", message),
    };
    Ok( warp::reply::json( &results ) )
}

pub async fn update_reply(
    uid: String,
    mut reply: Reply,
    db_conn: DbConn,
) -> Result<impl warp::Reply, Infallible> {
    debug!("update reply: uid = {}, reply = {:?}", uid, reply);
    reply.unique_id = uid;
    reply.status = Status::Approved;
    reply.remarks = String::from("updated");
    reply::assign_updated_date(&mut reply);
    let result = db::update_reply(&reply, db_conn).await;
    let code = process_db_result( result );
    Ok(code)
}

pub async fn update_reply_message(
    uid: String,
    map: HashMap<String, String>,
    db_conn: DbConn,
) -> Result<impl warp::Reply, Infallible> {
    debug!("update reply message: uid = {}, new-message: {:?}+++++++++++++++++++++++++++", &uid, &map);
    let now: String = comment::timestamp_now();
    let msg = map.get("message").unwrap();
    let result = db::update_reply_message(msg.to_string(), uid, now, db_conn).await;
    let code = process_db_result( result );
    Ok(code)
}

pub async fn delete_reply(
    uid: String, 
    db_conn: DbConn
) -> Result<impl warp::Reply, Infallible> {
    debug!("delete reply: uid = {}", uid);
    let now: String = comment::timestamp_now();
    let result = db::delete_reply(&uid, now, db_conn).await;
    let code = process_db_result( result );
    Ok(code)
}

pub async fn get_reply(
    uid: String, 
    db_conn: DbConn
) -> Result<impl warp::Reply, Infallible> {
    // just return a json of reply for the given uid 
    debug!("get reply: uid = {}", uid);
    match db::get_reply(&uid, db_conn).await {
        Ok(data) => Ok( warp::reply::json( &data ) ),
        Err(message) => {
            error!("{} occurred in handlers::get_reply()", message);
            Ok( warp::reply::json( &"No Data Found" ) )
        },
    }
}

// This function serves two purposes: Add upvote and Revoke upvote (toggling effect)
// Add upvote happens when there is no row in the database for the combination of
// comment_id and user_id; if a row already exist for this combination, remove this row.
// To be precise, first time request on add_upvote will actually add an upvote, whereas
// second time request on add_upvote will remove the upvote
pub async fn add_upvote(
    new_upvote: Upvote,
    db_conn: DbConn,
) -> Result<impl warp::Reply, Infallible> {
    debug!("add upvote: {:?}", new_upvote);
    let mut upvote_clone = new_upvote.clone();
    upvote::assign_created_date(&mut upvote_clone);
    match db::add_upvote(&upvote_clone, db_conn.clone()).await {
        Ok(count) => {
            match count { 
                1 => Ok(StatusCode::CREATED),
                _ => Ok(StatusCode::BAD_REQUEST)
            }
        },
        Err(rusqlite::Error::SqliteFailure(error, _options)) => { // if unique constraint occurs, treat it as revoke request
            let mut code = StatusCode::BAD_REQUEST;
            let is_constraint_error =  error.code == rusqlite::ErrorCode::ConstraintViolation 
                                            && error.extended_code == "2067".parse::<i32>().unwrap();
            if is_constraint_error {                                            
                code = revoke_upvote(&upvote_clone, db_conn.clone()).await;
            }
            Ok(code)
        },
        Err(error) => {
            error!("{:?} occurred in handlers::add_upvote()", &error);
            Ok(StatusCode::BAD_REQUEST)
        },
    }
}

async fn revoke_upvote(upvote: &Upvote, db_conn: DbConn) -> warp::http::StatusCode {
    let now: String = upvote::timestamp_now();
    let result = db::delete_upvote(&upvote.comment_id, &upvote.user_id, now, db_conn).await;
    process_db_result(result)
}

pub async fn delete_upvote(
    comment_id: String,
    user_id: String, 
    db_conn: DbConn
) -> Result<impl warp::Reply, Infallible> {
    debug!("delete upvote: comment_id = {}, user_id = {}", &comment_id, &user_id);
    let now: String = upvote::timestamp_now();
    let result = db::delete_upvote(&comment_id, &user_id, now, db_conn).await;
    let code = process_db_result(result);
    Ok(code)
}

pub async fn upvotes_total(
    comment_id: String,
    db_conn: DbConn,
) -> Result<impl warp::Reply, Infallible> {
    let total: u32 = match db::get_upvotes_total(&comment_id, db_conn).await {
        Ok(data) => data,
        Err(message) => {
            error!("{:?} occurred in handlers::upvotes_total()", message);
            0u32
        }
    };
    Ok( warp::reply::json( &total ) )
}

///////////////////////// Downvote
// This function serves two purposes: Add downvote and Revoke downvote (toggling effect)
// Add downvote happens when there is no row in the database for the combination of
// comment_id and user_id; if a row already exist for this combination, remove this row.
// To be precise, first time request on add_downvote will actually add an downvote, whereas
// second time request on add_downvote will remove the downvote
pub async fn add_downvote(
    new_downvote: Downvote,
    db_conn: DbConn,
) -> Result<impl warp::Reply, Infallible> {
    debug!("add downvote: {:?}", new_downvote);
    let mut downvote_clone = new_downvote.clone();
    downvote::assign_created_date(&mut downvote_clone);
    match db::add_downvote(&downvote_clone, db_conn.clone()).await {
        Ok(count) => {
            match count { 
                1 => Ok(StatusCode::CREATED),
                _ => Ok(StatusCode::BAD_REQUEST)
            }
        },
        Err(rusqlite::Error::SqliteFailure(error, _options)) => { // if unique constraint occurs, treat it as revoke request
            let mut code = StatusCode::BAD_REQUEST;
            let is_constraint_error =  error.code == rusqlite::ErrorCode::ConstraintViolation 
                                            && error.extended_code == "2067".parse::<i32>().unwrap();
            if is_constraint_error {                                            
                code = revoke_downvote(&downvote_clone, db_conn.clone()).await;
            }
            Ok(code)
        },
        Err(error) => {
            error!("{:?} occurred in handlers::add_downvote()", &error);
            Ok(StatusCode::BAD_REQUEST)
        },
    }
}

async fn revoke_downvote(downvote: &Downvote, db_conn: DbConn) -> warp::http::StatusCode {
    let now: String = downvote::timestamp_now();
    let result = db::delete_downvote(&downvote.comment_id, &downvote.user_id, now, db_conn).await;
    process_db_result(result)
}

pub async fn delete_downvote(
    comment_id: String,
    user_id: String, 
    db_conn: DbConn
) -> Result<impl warp::Reply, Infallible> {
    debug!("delete downvote: comment_id = {}, user_id = {}", &comment_id, &user_id);
    let now: String = downvote::timestamp_now();
    let result = db::delete_downvote(&comment_id, &user_id, now, db_conn).await;
    let code = process_db_result(result);
    Ok(code)
}

pub async fn downvotes_total(
    comment_id: String,
    db_conn: DbConn,
) -> Result<impl warp::Reply, Infallible> {
    let total: u32 = match db::get_downvotes_total(&comment_id, db_conn).await {
        Ok(data) => data,
        Err(message) => {
            error!("{:?} occurred in handlers::downvotes_total()", message);
            0u32
        }
    };
    Ok( warp::reply::json( &total ) )
}