diff --git a/backend/src/db/mod.rs b/backend/src/db/mod.rs index 4cade1b..f2868cc 100644 --- a/backend/src/db/mod.rs +++ b/backend/src/db/mod.rs @@ -8,7 +8,7 @@ use std::time::Duration; use crate::{ env::EnvVars, - pathutils::PaperCategory, + pathutils::{PaperCategory, Paths}, qp::{self, AdminDashboardQP, Exam, Semester}, routing::{EditReq, FileDetails}, }; @@ -147,8 +147,11 @@ impl Database { } else if approve_status { env_vars.paths.get_slug( &format!( - "{}_{}_{}_{}_{}_{}.pdf", - id, course_code, course_name, year, semester, exam + "{}.pdf", + Paths::sanitize_path(&format!( + "{}_{}_{}_{}_{}_{}", + id, course_code, course_name, year, semester, exam + )) ), PaperCategory::Approved, ) diff --git a/backend/src/pathutils.rs b/backend/src/pathutils.rs index 9141aba..d99e5c5 100644 --- a/backend/src/pathutils.rs +++ b/backend/src/pathutils.rs @@ -174,4 +174,19 @@ impl Paths { pub fn get_url_from_slug(&self, slug: &str) -> Result { Ok(self.static_files_url.join(slug)?.as_str().to_string()) } + + /// Removes any non-alphanumeric character and replaces whitespaces with `-` + /// Also replaces `/` with `-` and multiple spaces or hyphens will be replaced with a single one + pub fn sanitize_path(path: &str) -> String { + path.replace('/', "-") // Replace specific characters with a `-` + .replace('-', " ") // Convert any series of spaces and hyphens to just spaces + .split_whitespace() // Split at whitespaces to later replace all whitespaces with `-` + .map(|part| { + part.chars() + .filter(|&character| character.is_alphanumeric() || character == '-' || character == '_') // Remove any character that is not a `-` or alphanumeric + .collect::() + }) + .collect::>() + .join("-") // Join the parts with `-` + } } diff --git a/backend/src/routing/handlers.rs b/backend/src/routing/handlers.rs index 9760163..af03e1a 100644 --- a/backend/src/routing/handlers.rs +++ b/backend/src/routing/handlers.rs @@ -181,6 +181,8 @@ pub async fn edit( let old_filepath = state.env_vars.paths.get_path_from_slug(&old_filelink); let new_filepath = state.env_vars.paths.get_path_from_slug(&new_qp.filelink); + println!("{}, {}", new_filepath.to_string_lossy(), old_filepath.to_string_lossy()); + if fs::copy(old_filepath, new_filepath).await.is_ok() { // Commit the transaction tx.commit().await?;