add download paste

This commit is contained in:
nullobsi 2022-04-03 20:47:08 -07:00
parent fa78dd4246
commit 4c6c02cb74
No known key found for this signature in database
GPG Key ID: 933A1F44222C2634
2 changed files with 64 additions and 1 deletions

View File

@ -14,7 +14,7 @@ use config::Config;
use sqlx::{postgres::PgPoolOptions, PgPool};
use crate::routes::{get_paste, get_stats, get_total_pastes_badge, get_version_badge, new_paste, get_raw_paste};
use crate::routes::{get_paste, get_stats, get_total_pastes_badge, get_version_badge, new_paste, get_raw_paste, download_paste};
#[derive(Clone)]
pub struct AppState {
@ -63,6 +63,7 @@ async fn main() -> io::Result<()> {
.wrap(Governor::new(&paste_governor))
.service(get_paste)
.service(new_paste)
.service(download_paste)
.service(get_raw_paste),
)
.service(

View File

@ -2,6 +2,7 @@ use actix_web::{
get, post,
web::{self},
HttpResponse, Responder,
http::header
};
use badge_maker::{BadgeBuilder, Style};
@ -138,6 +139,67 @@ pub async fn get_raw_paste(state: web::Data<AppState>, id: web::Path<String>) ->
}
}
#[get("/d/{id}")]
pub async fn download_paste(state: web::Data<AppState>, id: web::Path<String>) -> impl Responder {
let id = id.into_inner();
let res: Result<Paste, sqlx::Error> =
sqlx::query_as::<_, Paste>(r#"SELECT * FROM pastes WHERE "id" = $1"#)
.bind(id.clone())
.fetch_one(&state.pool)
.await;
match res {
Ok(p) => {
if p.single_view {
let _ = sqlx::query(r#"DELETE FROM pastes WHERE "id" = $1"#)
.bind(id.clone())
.execute(&state.pool)
.await;
} else {
let _ = sqlx::query(r#"UPDATE pastes SET "views" = "views" + 1 WHERE "id" = $1"#)
.bind(id.clone())
.execute(&state.pool)
.await;
}
if state.config.logging.on_get_paste {
println!("[GET] download id={} views={} single_view={}", id, p.views + 1, p.single_view);
}
HttpResponse::Ok()
.insert_header(header::ContentType::octet_stream())
.insert_header(header::ContentDisposition {
disposition: header::DispositionType::Attachment,
parameters: vec![header::DispositionParam::Filename(format!("{}.txt", id))]
})
.body(p.content)
}
Err(e) => match e {
sqlx::Error::RowNotFound => {
return HttpResponse::NotFound().json(ApiResponse {
success: false,
data: ApiError {
message: format!("Paste {id} wasn't found."),
},
});
}
_ => {
eprintln!("Error occured while getting paste: {:?}", e);
HttpResponse::InternalServerError().json(ApiResponse {
success: false,
data: ApiError {
message: "Unknown error occured, please try again.".to_string(),
},
})
}
},
}
}
#[post("/n")]
pub async fn new_paste(
state: web::Data<AppState>,