pastebin/src/routes/insert_paste_route.rs

70 lines
2.5 KiB
Rust

// pastebin.run
// Copyright (C) 2021 Konrad Borowski
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::models::paste::{self, InsertionError};
use crate::Db;
use chrono::{Duration, Utc};
use rocket::form::{self, Form, FromForm, FromFormField};
use rocket::response::Redirect;
#[derive(FromForm)]
pub struct PasteForm {
#[field(validate = len(1..))]
code: String,
duration: ShareDuration,
}
pub enum ShareDuration {
OneHour,
ThreeHour,
TwentyFourHour,
ThreeDays,
SevenDays,
NinetyDays,
}
impl<'v> FromFormField<'v> for ShareDuration {
fn from_value(field: rocket::form::ValueField<'v>) -> rocket::form::Result<'v, Self> {
match field.value {
"1h" => Ok(ShareDuration::OneHour),
"3h" => Ok(ShareDuration::ThreeHour),
"24h" => Ok(ShareDuration::TwentyFourHour),
"3d" => Ok(ShareDuration::ThreeDays),
"7d" => Ok(ShareDuration::SevenDays),
"90d" => Ok(ShareDuration::NinetyDays),
_ => Err(form::Error::validation("invalid value for share duration"))?,
}
}
}
#[post("/", data = "<form>")]
pub async fn insert_paste(db: Db, form: Form<PasteForm>) -> Result<Redirect, InsertionError> {
let delete_at = match form.duration {
ShareDuration::OneHour => Some(Utc::now() + Duration::hours(1)),
ShareDuration::ThreeHour => Some(Utc::now() + Duration::hours(3)),
ShareDuration::TwentyFourHour => Some(Utc::now() + Duration::hours(24)),
ShareDuration::ThreeDays => Some(Utc::now() + Duration::days(3)),
ShareDuration::SevenDays => Some(Utc::now() + Duration::days(7)),
ShareDuration::NinetyDays => Some(Utc::now() + Duration::days(90)),
};
let identifier = db
.run(move |conn| paste::insert(conn, delete_at, &form.code))
.await?;
Ok(Redirect::to(uri!(super::display_paste(identifier))))
}