From 3a3174619dbaeb333c2a98ea3e96695403140ccc Mon Sep 17 00:00:00 2001 From: neri Date: Tue, 9 Mar 2021 22:19:06 +0100 Subject: [PATCH] shorter id generation, shorten file url --- src/main.rs | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/src/main.rs b/src/main.rs index fcdb7d7..be46102 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,6 +19,7 @@ use async_std::{ }; use file_kind::FileKind; use futures::TryStreamExt; +use rand::prelude::SliceRandom; use sqlx::{ postgres::{PgPool, PgPoolOptions, PgRow}, Row, @@ -29,6 +30,11 @@ const INDEX_HTML: &str = include_str!("../template/index.html"); const UPLOAD_HTML: &str = include_str!("../template/upload.html"); const VIEW_HTML: &str = include_str!("../template/view.html"); +const ID_CHARS: &[char] = &[ + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', + 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', +]; + async fn index(req: web::HttpRequest) -> Result { let upload_url = format!("{}/upload", get_host_url(&req)); let index_html = INDEX_HTML.replace("{upload_url}", upload_url.as_str()); @@ -47,7 +53,7 @@ async fn upload( expiry_watch_sender: web::Data>, config: web::Data, ) -> Result { - let file_id = format!("{:x?}", rand::random::()); + let file_id = gen_file_id(); let mut filename = config.files_dir.clone(); filename.push(&file_id); @@ -108,6 +114,15 @@ async fn upload( .body(format!("{}\n", url))) } +fn gen_file_id() -> String { + let mut rng = rand::thread_rng(); + let mut id = String::with_capacity(5); + for _ in 0..5 { + id.push(*ID_CHARS.choose(&mut rng).expect("ID_CHARS is not empty")); + } + id +} + fn get_host_url(req: &web::HttpRequest) -> String { let conn = req.connection_info(); format!("{}://{}", conn.scheme(), conn.host()) @@ -116,9 +131,9 @@ fn get_host_url(req: &web::HttpRequest) -> String { fn get_file_url(req: &web::HttpRequest, id: &str, name: Option<&str>) -> String { if let Some(name) = name { let encoded_name = urlencoding::encode(name); - format!("{}/file/{}/{}", get_host_url(req), id, encoded_name) + format!("{}/{}/{}", get_host_url(req), id, encoded_name) } else { - format!("{}/file/{}", get_host_url(req), id) + format!("{}/{}", get_host_url(req), id) } } @@ -273,11 +288,11 @@ async fn main() -> std::io::Result<()> { web::resource(["/upload/{id}", "/upload/{id}/{name}"]) .route(web::get().to(uploaded)), ) + .service(Files::new("/static", "static").disable_content_disposition()) .service( - web::resource(["/file/{id}", "/file/{id}/{name}"]) + web::resource(["/{id:[a-z0-9]{5}}", "/{id:[a-z0-9]{5}}/{name}"]) .route(web::get().to(download)), ) - .service(Files::new("/static", "static").disable_content_disposition()) .default_service(web::route().to(not_found)) } })