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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! Routes for burrow

use chrono::{Duration, FixedOffset, Utc};
use rocket::http::Status;
use rocket::serde::json::Json;
use rocket::{Build, Rocket};
use rocket_db_pools::Connection;
use sea_orm::{entity::*, query::*, DbBackend, DbErr};

use crate::config::burrow::{BURROW_CREATE_DURATION, BURROW_LIMIT};
use crate::config::content::REPLY_PER_PAGE;
use crate::db::{self, prelude::*};
use crate::models::{burrow::*, content::Post, error::*, pulsar::*};
use crate::pool::{PgDb, PulsarMq};
use crate::utils::auth::Auth;
use crate::utils::burrow_valid::*;

pub async fn init(rocket: Rocket<Build>) -> Rocket<Build> {
    rocket.mount(
        "/burrows",
        routes![
            create_burrow,
            discard_burrow,
            show_burrow,
            update_burrow,
            get_total_burrow_count
        ],
    )
}

/// Get total burrow count
///
/// ## Parameters
///
/// - `Auth`: Authenticated User
/// - `Connection<PgDb>`: Postgres connection
///
/// ## Returns
///
/// - `Status`: HTTP status
/// - `Json<BurrowTotalCount>`: Number of total burrow
///
/// ## Errors
///
/// - `ErrorResponse`: Error message
///     - `ErrorCode::DatabaseErr`
///
#[get("/total")]
pub async fn get_total_burrow_count(
    _auth: Auth,
    db: Connection<PgDb>,
) -> (Status, Result<Json<BurrowTotalCount>, Json<ErrorResponse>>) {
    let pg_con = db.into_inner();
    match LastBurrowSeq::find_by_statement(Statement::from_sql_and_values(
        DbBackend::Postgres,
        r#"SELECT "last_value" FROM "burrow_burrow_id_seq""#,
        vec![],
    ))
    .one(&pg_con)
    .await
    {
        Ok(r) => match r {
            Some(r) => (Status::Ok, Ok(Json(r.into()))),
            None => (
                Status::InternalServerError,
                Err(Json(ErrorResponse::default())),
            ),
        },
        Err(e) => {
            log::error!("[TOTAL-BURROW] Database error: {:?}", e);
            (
                Status::InternalServerError,
                Err(Json(ErrorResponse::default())),
            )
        }
    }
}

/// Create Burrow
///
/// ## Parameters
///
/// - `Auth`: Authenticated user
/// - `Connection<PgDb>`: Postgres connection
/// - `Json<BurrowInfo>`: Burrow information
/// - `Connection<PulsarMq>`: Pulsar connection
///
/// ## Returns
///
/// - `Status`: HTTP status
/// - `BurrowCreateResponse`: Response of create burrow
///
/// ## Errors
///
/// - `ErrorResponse`: Error message
///   - `ErrorCode::EmptyField`
///   - `ErrorCode::RateLimit`
///   - `ErrorCode::UserNotExist`
///   - `ErrorCode::UserForbidden`
///   - `ErrorCode::BurrowNumLimit`
///   - `ErrorCode::DatabaseErr`
///
#[post("/", data = "<burrow_info>", format = "json")]
pub async fn create_burrow(
    db: Connection<PgDb>,
    burrow_info: Json<BurrowInfo>,
    mut producer: Connection<PulsarMq>,
    auth: Auth,
) -> (
    Status,
    Result<Json<BurrowCreateResponse>, Json<ErrorResponse>>,
) {
    let pg_con = db.into_inner();
    // check if user has too many burrows, return corresponding error if so
    match UserStatus::find_by_id(auth.id).one(&pg_con).await {
        Ok(opt_state) => match opt_state {
            Some(state) => {
                if state.user_state != 0 {
                    return (
                        Status::Forbidden,
                        Err(Json(ErrorResponse::build(
                            ErrorCode::UserForbidden,
                            "User not in a valid state",
                        ))),
                    );
                }
                let now = Utc::now().with_timezone(&FixedOffset::east(8 * 3600));
                if state
                    .update_time
                    .checked_add_signed(Duration::seconds(*BURROW_CREATE_DURATION))
                    .unwrap()
                    > now
                {
                    return (
                        Status::TooManyRequests,
                        Err(Json(ErrorResponse::build(
                            ErrorCode::RateLimit,
                            "User can only create a new burrow every 24 hours",
                        ))),
                    );
                }
                let valid_burrows = get_burrow_list(&state.valid_burrow);
                let banned_burrows = get_burrow_list(&state.banned_burrow);
                if banned_burrows.len() + valid_burrows.len() < BURROW_LIMIT {
                    // get burrow info from request
                    let burrow = burrow_info.into_inner();
                    // check if Burrow Title is empty, return corresponding error if so
                    if burrow.title.is_empty() {
                        return (
                            Status::BadRequest,
                            Err(Json(ErrorResponse::build(
                                ErrorCode::EmptyField,
                                "Burrow title cannot be empty",
                            ))),
                        );
                    }
                    // fill the row of table 'burrow'
                    let burrows = db::burrow::ActiveModel {
                        uid: Set(auth.id),
                        title: Set(burrow.title),
                        description: Set(burrow.description),
                        create_time: Set(now.to_owned()),
                        update_time: Set(now.to_owned()),
                        ..Default::default()
                    };
                    // insert the row in database
                    // <Fn, A, B> -> Result<A, B>
                    let mut ust: db::user_status::ActiveModel = state.into();
                    match pg_con
                        .transaction::<_, BurrowCreateResponse, DbErr>(|txn| {
                            Box::pin(async move {
                                let res = burrows.insert(txn).await?;
                                let burrow_id = res.burrow_id.unwrap();
                                let pulsar_burrow = PulsarSearchBurrowData {
                                    burrow_id,
                                    title: res.title.unwrap(),
                                    description: res.description.unwrap(),
                                    update_time: now.to_owned(),
                                };
                                let uid = res.uid.unwrap();
                                ust.update_time = Set(now);
                                ust.valid_burrow = {
                                    let mut valid_burrows: Vec<i64> =
                                        get_burrow_list(&ust.valid_burrow.unwrap());
                                    valid_burrows.push(burrow_id);
                                    let valid_burrows_str = valid_burrows
                                        .iter()
                                        .map(|x| x.to_string())
                                        .collect::<Vec<String>>()
                                        .join(",");
                                    Set(valid_burrows_str)
                                };
                                ust.update(txn).await?;
                                info!(
                                    "[Create-Burrow] successfully create burrow {} for user {}",
                                    burrow_id, uid
                                );
                                // TODO: move them out of the transaction
                                let msg = PulsarSearchData::CreateBurrow(pulsar_burrow);
                                let _ = producer
                                    .send("persistent://public/default/search", msg)
                                    .await;
                                Ok(BurrowCreateResponse { burrow_id })
                            })
                        })
                        .await
                    {
                        Ok(resp) => (Status::Ok, Ok(Json(resp))),
                        Err(e) => {
                            error!("Database error: {:?}", e);
                            (
                                Status::InternalServerError,
                                Err(Json(ErrorResponse::default())),
                            )
                        }
                    }
                } else {
                    info!("[CREATE-BURROW] Owned burrow amount reaches threshold.");
                    (
                        Status::Forbidden,
                        Err(Json(ErrorResponse::build(
                            ErrorCode::BurrowNumLimit,
                            "Owned burrow amount is up to limit.",
                        ))),
                    )
                }
            }
            None => {
                info!("[CREATE BURROW] Cannot find user_status by uid.");
                (
                    Status::BadRequest,
                    Err(Json(ErrorResponse::build(ErrorCode::UserNotExist, ""))),
                )
            }
        },
        Err(e) => {
            error!("[CREATE BURROW] Database Error: {:?}", e);
            (
                Status::InternalServerError,
                Err(Json(ErrorResponse::default())),
            )
        }
    }
}

/// Discard Burrow
///
/// ## Parameters
///
/// - `Auth`: Authenticated user
/// - `Connection<PgDb>`: Postgres connection
/// - `i64`: Burrow id
///
/// ## Returns
///
/// - `Status`: HTTP status
/// - `String`: "Success"
///
/// ## Errors
///
/// - `ErrorResponse`: Error message
///   - `ErrorCode::UserNotExist`
///   - `ErrorCode::UserForbidden`
///   - `ErrorCode::DatabaseErr`
///
#[delete("/<burrow_id>")]
pub async fn discard_burrow(
    db: Connection<PgDb>,
    burrow_id: i64,
    auth: Auth,
) -> (Status, Result<String, Json<ErrorResponse>>) {
    let pg_con = db.into_inner();
    match UserStatus::find_by_id(auth.id).one(&pg_con).await {
        Ok(opt_ust) => match opt_ust {
            Some(state) => {
                let mut valid_burrows: Vec<i64> = get_burrow_list(&state.valid_burrow);
                let mut banned_burrows: Vec<i64> = get_burrow_list(&state.banned_burrow);
                let mut ac_state: db::user_status::ActiveModel = state.into();
                // update valid_burrow / banned_burrow in user_status table
                // do some type-convert things, and fill in the row according to different situations
                if valid_burrows.contains(&burrow_id) {
                    valid_burrows.remove(valid_burrows.binary_search(&burrow_id).unwrap());
                    let valid_burrows_str = valid_burrows
                        .iter()
                        .map(|x| x.to_string())
                        .collect::<Vec<String>>()
                        .join(",");
                    ac_state.valid_burrow = Set(valid_burrows_str);
                    // update table user_status
                    match pg_con
                        .transaction::<_, (), DbErr>(|txn| {
                            Box::pin(async move {
                                ac_state.update(txn).await?;
                                let ac_burrow: db::burrow::ActiveModel = db::burrow::ActiveModel {
                                    burrow_id: Set(burrow_id),
                                    burrow_state: Set(2),
                                    ..Default::default()
                                };
                                ac_burrow.update(txn).await?;
                                info!("[DISCARD-BURROW] Burrow {} discarded.", burrow_id);
                                Ok(())
                            })
                        })
                        .await
                    {
                        Ok(_) => (Status::Ok, Ok("Success".to_string())),
                        Err(e) => {
                            error!("Database error: {:?}", e);
                            (
                                Status::InternalServerError,
                                Err(Json(ErrorResponse::default())),
                            )
                        }
                    }
                } else if banned_burrows.contains(&burrow_id) {
                    banned_burrows.remove(banned_burrows.binary_search(&burrow_id).unwrap());
                    let banned_burrows_str = banned_burrows
                        .iter()
                        .map(|x| x.to_string())
                        .collect::<Vec<String>>()
                        .join(",");
                    ac_state.banned_burrow = Set(banned_burrows_str);
                    // update table user_status
                    match pg_con
                        .transaction::<_, (), DbErr>(|txn| {
                            Box::pin(async move {
                                ac_state.update(txn).await?;
                                let ac_burrow: db::burrow::ActiveModel = db::burrow::ActiveModel {
                                    burrow_id: Set(burrow_id),
                                    burrow_state: Set(3),
                                    ..Default::default()
                                };
                                ac_burrow.update(txn).await?;
                                info!("[DISCARD-BURROW] Burrow {} discarded.", burrow_id);
                                Ok(())
                            })
                        })
                        .await
                    {
                        Ok(_) => (Status::Ok, Ok("Success".to_string())),
                        Err(e) => {
                            error!("Database error: {:?}", e);
                            (
                                Status::InternalServerError,
                                Err(Json(ErrorResponse::default())),
                            )
                        }
                    }
                } else {
                    info!(
                        "[DEL-BURROW] Cannot delete burrow: Burrow doesn't belong to current user."
                    );
                    (
                        Status::Forbidden,
                        Err(Json(ErrorResponse::build(
                            ErrorCode::UserForbidden,
                            "Burrow doesn't belong to current user or already be discarded",
                        ))),
                    )
                }
            }
            None => {
                info!("[DEL-BURROW] Cannot find user_status by uid.");
                (
                    Status::BadRequest,
                    Err(Json(ErrorResponse::build(ErrorCode::UserNotExist, ""))),
                )
            }
        },
        Err(e) => {
            error!("[DEL-BURROW] Database Error: {:?}", e);
            (
                Status::InternalServerError,
                Err(Json(ErrorResponse::default())),
            )
        }
    }
}

/// Show a Specific Burrow with Up to Ten Posts
///
/// ## Parameters
///
/// - `Auth`: Authenticated user
/// - `Connection<PgDb>`: Postgres connection
/// - `i64`: Burrow id
/// - `Option<usize>`: Page number for burrow
///
/// ## Returns
///
/// - `Status`: HTTP status
/// - `BurrowShowResponse`: Burrow detail information, including burrow information and up to 10 posts
///
/// ## Errors
///
/// - `ErrorResponse`: Error message
///   - `ErrorCode::BurrowNotExist`
///   - `ErrorCode::DatabaseErr`
///
#[get("/<burrow_id>?<page>")]
pub async fn show_burrow(
    db: Connection<PgDb>,
    burrow_id: i64,
    page: Option<usize>,
    _auth: Auth,
) -> (
    Status,
    Result<Json<BurrowShowResponse>, Json<ErrorResponse>>,
) {
    let pg_con = db.into_inner();
    let page = page.unwrap_or(0);
    match Burrow::find_by_id(burrow_id).one(&pg_con).await {
        Ok(opt_burrow) => match opt_burrow {
            Some(burrow) => {
                match ContentPost::find()
                    .filter(db::content_post::Column::BurrowId.eq(burrow_id))
                    .order_by_desc(db::content_post::Column::PostId)
                    .paginate(&pg_con, REPLY_PER_PAGE)
                    .fetch_page(page)
                    .await
                {
                    Ok(posts) => (
                        Status::Ok,
                        Ok(Json(BurrowShowResponse {
                            title: burrow.title,
                            description: burrow.description,
                            posts: {
                                let posts_info: Vec<Post> =
                                    posts.iter().map(|post| post.into()).collect();
                                posts_info
                            },
                        })),
                    ),
                    Err(e) => {
                        error!("[SHOW-BURROW] Database Error: {:?}", e);
                        (
                            Status::InternalServerError,
                            Err(Json(ErrorResponse::default())),
                        )
                    }
                }
            }
            None => {
                info!("[SHOW-BURROW] Cannot find burrow {}", burrow_id);
                (
                    Status::NotFound,
                    Err(Json(ErrorResponse::build(ErrorCode::BurrowNotExist, ""))),
                )
            }
        },
        Err(e) => {
            error!("[SHOW-BURROW] Database Error: {:?}", e);
            (
                Status::InternalServerError,
                Err(Json(ErrorResponse::default())),
            )
        }
    }
}

/// Update Burrow
///
/// ## Parameters
///
/// - `Auth`: Authenticated user
/// - `Connection<PgDb>`: Postgres connection
/// - `i64`: Burrow id
/// - `Json<BurrowInfo>`: Burrow information
/// - `Connection<PulsarMq>`: Pulsar connection
///
/// ## Returns
///
/// - `Status`: HTTP status
/// - `String`: "Success"
///
/// ## Errors
///
/// - `ErrorResponse`: Error message
///   - `ErrorCode::EmptyField`
///   - `ErrorCode::UserNotExist`
///   - `ErrorCode::UserForbidden`
///   - `ErrorCode::DatabaseErr`
///
#[patch("/<burrow_id>", data = "<burrow_info>", format = "json")]
pub async fn update_burrow(
    db: Connection<PgDb>,
    burrow_id: i64,
    burrow_info: Json<BurrowInfo>,
    mut producer: Connection<PulsarMq>,
    auth: Auth,
) -> (Status, Result<String, Json<ErrorResponse>>) {
    let pg_con = db.into_inner();
    let burrow = burrow_info.into_inner();
    if burrow.title.is_empty() {
        return (
            Status::BadRequest,
            Err(Json(ErrorResponse::build(
                ErrorCode::EmptyField,
                "Burrow title cannot be empty",
            ))),
        );
    }
    match UserStatus::find_by_id(auth.id).one(&pg_con).await {
        Ok(opt_ust) => match opt_ust {
            Some(state) => {
                if state.user_state != 0 {
                    (
                        Status::Forbidden,
                        Err(Json(ErrorResponse::build(
                            ErrorCode::UserForbidden,
                            "User not in a valid state",
                        ))),
                    )
                } else if is_valid_burrow(&state.valid_burrow, &burrow_id) {
                    let now = Utc::now().with_timezone(&FixedOffset::east(8 * 3600));
                    let burrows = db::burrow::ActiveModel {
                        burrow_id: Set(burrow_id),
                        title: Set(burrow.title.to_owned()),
                        description: Set(burrow.description.to_owned()),
                        update_time: Set(now.to_owned()),
                        ..Default::default()
                    };
                    let pulsar_burrow = PulsarSearchBurrowData {
                        burrow_id,
                        title: burrow.title,
                        description: burrow.description,
                        update_time: now,
                    };
                    match burrows.update(&pg_con).await {
                        Ok(_) => {
                            let msg = PulsarSearchData::UpdateBurrow(pulsar_burrow);
                            let _ = producer
                                .send("persistent://public/default/search", msg)
                                .await;
                            (Status::Ok, Ok("Success".to_string()))
                        }
                        Err(e) => {
                            error!("[UPDATE-BURROW] Database Error: {:?}", e);
                            (
                                Status::InternalServerError,
                                Err(Json(ErrorResponse::default())),
                            )
                        }
                    }
                } else {
                    info!(
                        "[UPDATE-BURROW] Cannot update burrow: Burrow doesn't belong to current user."
                    );
                    (
                        Status::Forbidden,
                        Err(Json(ErrorResponse::build(
                            ErrorCode::UserForbidden,
                            "Burrow doesn't belong to current user or already be discarded",
                        ))),
                    )
                }
            }
            None => {
                info!("[UPDATE-BURROW] Cannot find user_status by uid.");
                (
                    Status::BadRequest,
                    Err(Json(ErrorResponse::build(ErrorCode::UserNotExist, ""))),
                )
            }
        },
        Err(e) => {
            error!("[UPDATE-BURROW] Database Error: {:?}", e);
            (
                Status::InternalServerError,
                Err(Json(ErrorResponse::default())),
            )
        }
    }
}