| 1 | use axum::Json; |
| 2 | use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; |
| 3 | use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE}; |
| 4 | use axum::http::{HeaderValue, StatusCode}; |
| 5 | use axum::response::{IntoResponse, Response}; |
| 6 | use serde::{Deserialize, Serialize}; |
| 7 | use utoipa::ToSchema; |
| 8 | use utoipa_axum::router::OpenApiRouter; |
| 9 | use utoipa_axum::routes; |
| 10 | |
| 11 | use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; |
| 12 | use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle}; |
| 13 | use crate::domain::note_file::{FileContentType, FileName, NoteFile, NoteFileId}; |
| 14 | use crate::domain::settings::Settings; |
| 15 | use crate::error::{AppError, ErrorResponse}; |
| 16 | use crate::state::AppState; |
| 17 | |
| 18 | use super::{ |
| 19 | Page, PageParams, RequireStudent, UploadFileForm, blob_path, read_upload, remove_blob, |
| 20 | }; |
| 21 | |
| 22 | pub fn routes() -> OpenApiRouter<AppState> { |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | let files = OpenApiRouter::new() |
| 28 | .routes(routes!(upload_file, list_files)) |
| 29 | .routes(routes!(download_file, delete_file)) |
| 30 | .layer(DefaultBodyLimit::max( |
| 31 | MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES, |
| 32 | )); |
| 33 | OpenApiRouter::new() |
| 34 | .routes(routes!(create, list)) |
| 35 | .routes(routes!(get_one, update, delete_one)) |
| 36 | .merge(files) |
| 37 | } |
| 38 | |
| 39 | #[derive(Deserialize, ToSchema)] |
| 40 | struct CreateNote { |
| 41 | #[schema(example = "Groceries", max_length = 200)] |
| 42 | title: String, |
| 43 | #[schema(example = "milk, eggs", max_length = 10000)] |
| 44 | content: Option<String>, |
| 45 | } |
| 46 | |
| 47 | #[derive(Deserialize, ToSchema)] |
| 48 | struct UpdateNote { |
| 49 | #[schema(max_length = 200)] |
| 50 | title: Option<String>, |
| 51 | #[schema(max_length = 10000)] |
| 52 | content: Option<String>, |
| 53 | } |
| 54 | |
| 55 | #[derive(Serialize, ToSchema)] |
| 56 | struct NoteResponse { |
| 57 | id: String, |
| 58 | title: String, |
| 59 | content: String, |
| 60 | } |
| 61 | |
| 62 | impl NoteResponse { |
| 63 | fn new(note: &Note) -> Self { |
| 64 | Self { |
| 65 | id: note.get_id().key().to_string(), |
| 66 | title: note.get_title().as_str().to_string(), |
| 67 | content: note.get_content().as_str().to_string(), |
| 68 | } |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | |
| 73 | #[utoipa::path( |
| 74 | post, |
| 75 | path = "/", |
| 76 | tag = "notes", |
| 77 | security(("session_cookie" = [])), |
| 78 | request_body = CreateNote, |
| 79 | responses( |
| 80 | (status = 201, description = "Note created", body = NoteResponse), |
| 81 | (status = 400, description = "Invalid title or content", body = ErrorResponse), |
| 82 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 83 | (status = 403, description = "Requires the student role or higher", body = ErrorResponse), |
| 84 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 85 | ), |
| 86 | )] |
| 87 | async fn create( |
| 88 | State(st): State<AppState>, |
| 89 | RequireStudent(user): RequireStudent, |
| 90 | Json(req): Json<CreateNote>, |
| 91 | ) -> Result<(StatusCode, Json<NoteResponse>), AppError> { |
| 92 | let title = NoteTitle::try_new(&req.title)?; |
| 93 | let content = NoteContent::try_new(&req.content.unwrap_or_default())?; |
| 94 | let note = Note::create(user.get_id(), title, content, &st.db).await?; |
| 95 | Ok((StatusCode::CREATED, Json(NoteResponse::new(¬e)))) |
| 96 | } |
| 97 | |
| 98 | |
| 99 | |
| 100 | |
| 101 | #[utoipa::path( |
| 102 | get, |
| 103 | path = "/", |
| 104 | tag = "notes", |
| 105 | security(("session_cookie" = [])), |
| 106 | params(PageParams), |
| 107 | responses( |
| 108 | (status = 200, description = "A page of the user's notes (all of them when unpaged)", body = Page<NoteResponse>), |
| 109 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 110 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 111 | (status = 403, description = "Requires the student role or higher", body = ErrorResponse), |
| 112 | ), |
| 113 | )] |
| 114 | async fn list( |
| 115 | State(st): State<AppState>, |
| 116 | RequireStudent(user): RequireStudent, |
| 117 | Query(page): Query<PageParams>, |
| 118 | ) -> Result<Json<Page<NoteResponse>>, AppError> { |
| 119 | let (limit, offset) = page.resolve()?; |
| 120 | let (notes, total) = Note::list_for(user.get_id(), limit, offset, &st.db).await?; |
| 121 | let items = notes.iter().map(NoteResponse::new).collect(); |
| 122 | Ok(Json(Page::new(items, total, limit, offset))) |
| 123 | } |
| 124 | |
| 125 | |
| 126 | #[utoipa::path( |
| 127 | get, |
| 128 | path = "/{id}", |
| 129 | tag = "notes", |
| 130 | security(("session_cookie" = [])), |
| 131 | params(("id" = String, Path, description = "Note id")), |
| 132 | responses( |
| 133 | (status = 200, description = "The note", body = NoteResponse), |
| 134 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 135 | (status = 403, description = "Requires the student role or higher", body = ErrorResponse), |
| 136 | (status = 404, description = "Not found", body = ErrorResponse), |
| 137 | ), |
| 138 | )] |
| 139 | async fn get_one( |
| 140 | State(st): State<AppState>, |
| 141 | RequireStudent(user): RequireStudent, |
| 142 | Path(id): Path<String>, |
| 143 | ) -> Result<Json<NoteResponse>, AppError> { |
| 144 | let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) |
| 145 | .await? |
| 146 | .ok_or(AppError::NotFound)?; |
| 147 | Ok(Json(NoteResponse::new(¬e))) |
| 148 | } |
| 149 | |
| 150 | |
| 151 | #[utoipa::path( |
| 152 | patch, |
| 153 | path = "/{id}", |
| 154 | tag = "notes", |
| 155 | security(("session_cookie" = [])), |
| 156 | params(("id" = String, Path, description = "Note id")), |
| 157 | request_body = UpdateNote, |
| 158 | responses( |
| 159 | (status = 200, description = "Updated note", body = NoteResponse), |
| 160 | (status = 400, description = "Invalid title or content", body = ErrorResponse), |
| 161 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 162 | (status = 403, description = "Requires the student role or higher", body = ErrorResponse), |
| 163 | (status = 404, description = "Not found", body = ErrorResponse), |
| 164 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 165 | ), |
| 166 | )] |
| 167 | async fn update( |
| 168 | State(st): State<AppState>, |
| 169 | RequireStudent(user): RequireStudent, |
| 170 | Path(id): Path<String>, |
| 171 | Json(req): Json<UpdateNote>, |
| 172 | ) -> Result<Json<NoteResponse>, AppError> { |
| 173 | let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) |
| 174 | .await? |
| 175 | .ok_or(AppError::NotFound)?; |
| 176 | |
| 177 | |
| 178 | |
| 179 | |
| 180 | |
| 181 | let title = req.title.as_deref().map(NoteTitle::try_new).transpose()?; |
| 182 | let content = req |
| 183 | .content |
| 184 | .as_deref() |
| 185 | .map(NoteContent::try_new) |
| 186 | .transpose()?; |
| 187 | |
| 188 | let updated = note.update(title, content, &st.db).await?; |
| 189 | Ok(Json(NoteResponse::new(&updated))) |
| 190 | } |
| 191 | |
| 192 | |
| 193 | #[utoipa::path( |
| 194 | delete, |
| 195 | path = "/{id}", |
| 196 | tag = "notes", |
| 197 | security(("session_cookie" = [])), |
| 198 | params(("id" = String, Path, description = "Note id")), |
| 199 | responses( |
| 200 | (status = 204, description = "Deleted"), |
| 201 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 202 | (status = 403, description = "Requires the student role or higher", body = ErrorResponse), |
| 203 | (status = 404, description = "Not found", body = ErrorResponse), |
| 204 | ), |
| 205 | )] |
| 206 | async fn delete_one( |
| 207 | State(st): State<AppState>, |
| 208 | RequireStudent(user): RequireStudent, |
| 209 | Path(id): Path<String>, |
| 210 | ) -> Result<StatusCode, AppError> { |
| 211 | let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) |
| 212 | .await? |
| 213 | .ok_or(AppError::NotFound)?; |
| 214 | |
| 215 | |
| 216 | |
| 217 | |
| 218 | let (_, files) = note.delete(&st.db).await?; |
| 219 | for file in &files { |
| 220 | remove_blob(&st.files_path, file.get_id().key()).await; |
| 221 | } |
| 222 | Ok(StatusCode::NO_CONTENT) |
| 223 | } |
| 224 | |
| 225 | |
| 226 | |
| 227 | #[derive(Serialize, ToSchema)] |
| 228 | struct NoteFileResponse { |
| 229 | id: String, |
| 230 | |
| 231 | #[schema(example = "homework.pdf")] |
| 232 | name: String, |
| 233 | |
| 234 | #[schema(example = "application/pdf")] |
| 235 | content_type: String, |
| 236 | |
| 237 | #[schema(example = 24_576)] |
| 238 | size: i64, |
| 239 | } |
| 240 | |
| 241 | impl NoteFileResponse { |
| 242 | fn new(file: &NoteFile) -> Self { |
| 243 | Self { |
| 244 | id: file.get_id().key().to_string(), |
| 245 | name: file.get_name().as_str().to_string(), |
| 246 | content_type: file.get_content_type().as_str().to_string(), |
| 247 | size: file.get_size(), |
| 248 | } |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | |
| 253 | |
| 254 | |
| 255 | |
| 256 | #[utoipa::path( |
| 257 | post, |
| 258 | path = "/{id}/files", |
| 259 | tag = "notes", |
| 260 | security(("session_cookie" = [])), |
| 261 | params(("id" = String, Path, description = "Note id")), |
| 262 | request_body(content = UploadFileForm, content_type = "multipart/form-data"), |
| 263 | responses( |
| 264 | (status = 201, description = "File stored", body = NoteFileResponse), |
| 265 | (status = 400, description = "Missing file field, invalid filename or content type, or empty file", body = ErrorResponse), |
| 266 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 267 | (status = 403, description = "Requires the student role or higher", body = ErrorResponse), |
| 268 | (status = 404, description = "Note not found", body = ErrorResponse), |
| 269 | (status = 409, description = "The note already holds the maximum number of files", body = ErrorResponse), |
| 270 | (status = 413, description = "File exceeds the school's size limit", body = ErrorResponse), |
| 271 | ), |
| 272 | )] |
| 273 | async fn upload_file( |
| 274 | State(st): State<AppState>, |
| 275 | RequireStudent(user): RequireStudent, |
| 276 | Path(id): Path<String>, |
| 277 | mut multipart: Multipart, |
| 278 | ) -> Result<(StatusCode, Json<NoteFileResponse>), AppError> { |
| 279 | let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) |
| 280 | .await? |
| 281 | .ok_or(AppError::NotFound)?; |
| 282 | |
| 283 | |
| 284 | let limit = Settings::load(&st.db).await?.get_max_file_bytes(); |
| 285 | |
| 286 | let upload = read_upload(&mut multipart, limit).await?; |
| 287 | let name = FileName::try_new(&upload.name.unwrap_or_default())?; |
| 288 | let content_type = FileContentType::try_new(&upload.content_type.unwrap_or_default())?; |
| 289 | |
| 290 | |
| 291 | |
| 292 | let file = NoteFile::new(note.get_id(), name, content_type, upload.data.len() as i64); |
| 293 | let path = blob_path(&st.files_path, file.get_id().key()); |
| 294 | tokio::fs::write(&path, &upload.data) |
| 295 | .await |
| 296 | .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?; |
| 297 | match file.insert(&st.db).await { |
| 298 | Ok(created) => Ok((StatusCode::CREATED, Json(NoteFileResponse::new(&created)))), |
| 299 | Err(err) => { |
| 300 | let _ = tokio::fs::remove_file(&path).await; |
| 301 | Err(err) |
| 302 | } |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | |
| 307 | |
| 308 | #[utoipa::path( |
| 309 | get, |
| 310 | path = "/{id}/files", |
| 311 | tag = "notes", |
| 312 | security(("session_cookie" = [])), |
| 313 | params(("id" = String, Path, description = "Note id"), PageParams), |
| 314 | responses( |
| 315 | (status = 200, description = "A page of the note's files", body = Page<NoteFileResponse>), |
| 316 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 317 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 318 | (status = 403, description = "Requires the student role or higher", body = ErrorResponse), |
| 319 | (status = 404, description = "Note not found", body = ErrorResponse), |
| 320 | ), |
| 321 | )] |
| 322 | async fn list_files( |
| 323 | State(st): State<AppState>, |
| 324 | RequireStudent(user): RequireStudent, |
| 325 | Path(id): Path<String>, |
| 326 | Query(page): Query<PageParams>, |
| 327 | ) -> Result<Json<Page<NoteFileResponse>>, AppError> { |
| 328 | let (limit, offset) = page.resolve()?; |
| 329 | let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) |
| 330 | .await? |
| 331 | .ok_or(AppError::NotFound)?; |
| 332 | let (files, total) = NoteFile::list_for(note.get_id(), limit, offset, &st.db).await?; |
| 333 | let items = files.iter().map(NoteFileResponse::new).collect(); |
| 334 | Ok(Json(Page::new(items, total, limit, offset))) |
| 335 | } |
| 336 | |
| 337 | |
| 338 | |
| 339 | #[utoipa::path( |
| 340 | get, |
| 341 | path = "/{id}/files/{file_id}", |
| 342 | tag = "notes", |
| 343 | security(("session_cookie" = [])), |
| 344 | params( |
| 345 | ("id" = String, Path, description = "Note id"), |
| 346 | ("file_id" = String, Path, description = "File id"), |
| 347 | ), |
| 348 | responses( |
| 349 | (status = 200, description = "The file bytes", content_type = "application/octet-stream"), |
| 350 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 351 | (status = 403, description = "Requires the student role or higher", body = ErrorResponse), |
| 352 | (status = 404, description = "Note or file not found", body = ErrorResponse), |
| 353 | ), |
| 354 | )] |
| 355 | async fn download_file( |
| 356 | State(st): State<AppState>, |
| 357 | RequireStudent(user): RequireStudent, |
| 358 | Path((id, file_id)): Path<(String, String)>, |
| 359 | ) -> Result<Response, AppError> { |
| 360 | let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) |
| 361 | .await? |
| 362 | .ok_or(AppError::NotFound)?; |
| 363 | let file = NoteFile::read_for(&NoteFileId::from_key(&file_id), note.get_id(), &st.db) |
| 364 | .await? |
| 365 | .ok_or(AppError::NotFound)?; |
| 366 | let bytes = tokio::fs::read(blob_path(&st.files_path, file.get_id().key())) |
| 367 | .await |
| 368 | .map_err(|err| { |
| 369 | |
| 370 | |
| 371 | AppError::Internal(format!( |
| 372 | "missing blob for note file {}: {err}", |
| 373 | file.get_id().key() |
| 374 | )) |
| 375 | })?; |
| 376 | |
| 377 | |
| 378 | let content_type = HeaderValue::from_str(file.get_content_type().as_str()) |
| 379 | .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream")); |
| 380 | let disposition = HeaderValue::from_str(&content_disposition(file.get_name().as_str())) |
| 381 | .unwrap_or_else(|_| HeaderValue::from_static("attachment")); |
| 382 | Ok(( |
| 383 | [ |
| 384 | (CONTENT_TYPE, content_type), |
| 385 | (CONTENT_DISPOSITION, disposition), |
| 386 | ], |
| 387 | bytes, |
| 388 | ) |
| 389 | .into_response()) |
| 390 | } |
| 391 | |
| 392 | |
| 393 | #[utoipa::path( |
| 394 | delete, |
| 395 | path = "/{id}/files/{file_id}", |
| 396 | tag = "notes", |
| 397 | security(("session_cookie" = [])), |
| 398 | params( |
| 399 | ("id" = String, Path, description = "Note id"), |
| 400 | ("file_id" = String, Path, description = "File id"), |
| 401 | ), |
| 402 | responses( |
| 403 | (status = 204, description = "Deleted"), |
| 404 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 405 | (status = 403, description = "Requires the student role or higher", body = ErrorResponse), |
| 406 | (status = 404, description = "Note or file not found", body = ErrorResponse), |
| 407 | ), |
| 408 | )] |
| 409 | async fn delete_file( |
| 410 | State(st): State<AppState>, |
| 411 | RequireStudent(user): RequireStudent, |
| 412 | Path((id, file_id)): Path<(String, String)>, |
| 413 | ) -> Result<StatusCode, AppError> { |
| 414 | let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) |
| 415 | .await? |
| 416 | .ok_or(AppError::NotFound)?; |
| 417 | let file = NoteFile::read_for(&NoteFileId::from_key(&file_id), note.get_id(), &st.db) |
| 418 | .await? |
| 419 | .ok_or(AppError::NotFound)?; |
| 420 | let file = file.delete(&st.db).await?; |
| 421 | remove_blob(&st.files_path, file.get_id().key()).await; |
| 422 | Ok(StatusCode::NO_CONTENT) |
| 423 | } |
| 424 | |
| 425 | |
| 426 | |
| 427 | |
| 428 | |
| 429 | pub(crate) fn content_disposition(name: &str) -> String { |
| 430 | let fallback: String = name |
| 431 | .chars() |
| 432 | .map(|c| { |
| 433 | if c.is_ascii_graphic() && c != '"' && c != '\\' || c == ' ' { |
| 434 | c |
| 435 | } else { |
| 436 | '_' |
| 437 | } |
| 438 | }) |
| 439 | .collect(); |
| 440 | format!( |
| 441 | "attachment; filename=\"{fallback}\"; filename*=UTF-8''{}", |
| 442 | rfc5987_encode(name) |
| 443 | ) |
| 444 | } |
| 445 | |
| 446 | |
| 447 | |
| 448 | fn rfc5987_encode(value: &str) -> String { |
| 449 | let mut out = String::with_capacity(value.len()); |
| 450 | for byte in value.bytes() { |
| 451 | match byte { |
| 452 | b'a'..=b'z' |
| 453 | | b'A'..=b'Z' |
| 454 | | b'0'..=b'9' |
| 455 | | b'!' |
| 456 | | b'#' |
| 457 | | b'$' |
| 458 | | b'&' |
| 459 | | b'+' |
| 460 | | b'-' |
| 461 | | b'.' |
| 462 | | b'^' |
| 463 | | b'_' |
| 464 | | b'`' |
| 465 | | b'|' |
| 466 | | b'~' => out.push(byte as char), |
| 467 | _ => out.push_str(&format!("%{byte:02X}")), |
| 468 | } |
| 469 | } |
| 470 | out |
| 471 | } |
| 472 | |
| 473 | #[cfg(test)] |
| 474 | mod tests { |
| 475 | use super::*; |
| 476 | |
| 477 | #[tokio::test] |
| 478 | async fn disposition_keeps_ascii_and_encodes_the_rest() { |
| 479 | assert_eq!( |
| 480 | content_disposition("plan.pdf"), |
| 481 | "attachment; filename=\"plan.pdf\"; filename*=UTF-8''plan.pdf" |
| 482 | ); |
| 483 | |
| 484 | assert_eq!( |
| 485 | content_disposition("ödev 1.pdf"), |
| 486 | "attachment; filename=\"_dev 1.pdf\"; filename*=UTF-8''%C3%B6dev%201.pdf" |
| 487 | ); |
| 488 | |
| 489 | assert_eq!( |
| 490 | content_disposition("a\"b.pdf"), |
| 491 | "attachment; filename=\"a_b.pdf\"; filename*=UTF-8''a%22b.pdf" |
| 492 | ); |
| 493 | } |
| 494 | } |