From 64c2567918cb011549ec4e07f8268f4917db914b Mon Sep 17 00:00:00 2001 From: neri Date: Mon, 3 Aug 2020 02:42:27 +0200 Subject: [PATCH] append original file name to urls --- src/file_kind.rs | 2 +- src/main.rs | 32 +++++++++++++++++++++++--------- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/src/file_kind.rs b/src/file_kind.rs index 4654c32..d3ce841 100644 --- a/src/file_kind.rs +++ b/src/file_kind.rs @@ -1,6 +1,6 @@ use std::{fmt::Display, str::FromStr}; -#[derive(Debug)] +#[derive(Debug, PartialEq)] pub(crate) enum FileKind { TEXT, BINARY, diff --git a/src/main.rs b/src/main.rs index 6336a2a..71027cb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -58,7 +58,7 @@ async fn upload( sqlx::query("INSERT INTO Files (file_id, file_name, valid_till, kind) VALUES ($1, $2, $3, $4)") .bind(&file_id) - .bind(original_name.unwrap_or_else(|| file_id.clone())) + .bind(original_name.as_ref().unwrap_or_else(|| &file_id)) .bind(valid_till.naive_local()) .bind(kind.to_string()) .execute(db.as_ref()) @@ -74,13 +74,25 @@ async fn upload( sender.send(()).await; + let redirect = if kind == FileKind::BINARY && original_name.is_some() { + format!("/upload/{}/{}", file_id, original_name.unwrap()) + } else { + format!("/upload/{}", file_id) + }; Ok(HttpResponse::SeeOther() - .header("location", format!("/upload/{}", file_id)) + .header("location", redirect) .finish()) } -async fn uploaded(id: web::Path, req: web::HttpRequest) -> Result { - let url = req.url_for("file", &[id.as_str()])?; +async fn uploaded(req: web::HttpRequest) -> Result { + let id = req.match_info().query("id"); + let name = req.match_info().get("name"); + let conn = req.connection_info(); + let url = if let Some(name) = name { + format!("{}://{}/file/{}/{}", conn.scheme(), conn.host(), id, name) + } else { + format!("{}://{}/file/{}", conn.scheme(), conn.host(), id) + }; let upload_html = UPLOAD_HTML.replace("{url}", url.as_str()); Ok(HttpResponse::Ok() .content_type("text/html") @@ -89,12 +101,12 @@ async fn uploaded(id: web::Path, req: web::HttpRequest) -> Result, db: web::Data, config: web::Data, ) -> Result { + let id = req.match_info().query("id"); let mut cursor = sqlx::query("SELECT file_id, file_name, kind from files WHERE file_id = $1") - .bind(id.as_ref()) + .bind(id) .fetch(db.as_ref()); let row: PgRow = cursor .next() @@ -218,10 +230,12 @@ async fn main() -> std::io::Result<()> { .data(config.clone()) .service(web::resource("/").route(web::get().to(index))) .service(web::resource("/upload").route(web::post().to(upload))) - .service(web::resource("/upload/{id}").route(web::get().to(uploaded))) .service( - web::resource("/file/{id}") - .name("file") + web::resource(["/upload/{id}", "/upload/{id}/{name}"]) + .route(web::get().to(uploaded)), + ) + .service( + web::resource(["/file/{id}", "/file/{id}/{name}"]) .route(web::get().to(download)), ) .service(Files::new("/static", "static").disable_content_disposition())