forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB0346717Ahmet Kaan Gümüş3 months ago230 commits

notes.rs494 lines, 18.6 KiBHistoryRawDownload
1use axum::Json;
2use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State};
3use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE};
4use axum::http::{HeaderValue, StatusCode};
5use axum::response::{IntoResponse, Response};
6use serde::{Deserialize, Serialize};
7use utoipa::ToSchema;
8use utoipa_axum::router::OpenApiRouter;
9use utoipa_axum::routes;
10
11use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};
12use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle};
13use crate::domain::note_file::{FileContentType, FileName, NoteFile, NoteFileId};
14use crate::domain::settings::Settings;
15use crate::error::{AppError, ErrorResponse};
16use crate::state::AppState;
17
18use super::{
19 Page, PageParams, RequireStudent, UploadFileForm, blob_path, read_upload, remove_blob,
20};
21
22pub fn routes() -> OpenApiRouter<AppState> {
23 // The file routes get their own HTTP body cap: the server-wide hard
24 // ceiling plus multipart framing headroom (axum's 2 MB default would
25 // reject legal uploads). The school's actual — usually smaller — limit
26 // from settings is enforced while the stream is read.
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)]
40struct 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)]
48struct 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)]
56struct NoteResponse {
57 id: String,
58 title: String,
59 content: String,
60}
61
62impl 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/// Create a note owned by the current user.
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)]
87async 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(&note))))
96}
97
98/// List the notes owned by the current user, newest first. Paged via
99/// `?limit=&offset=` (omit `limit` for all of them); returns a
100/// `{items, total, limit, offset}` envelope.
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)]
114async 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/// Fetch a single note by id (must be owned by the current user).
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)]
139async 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(&note)))
148}
149
150/// Update a note's title and/or content. Omitted fields keep their value.
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)]
167async 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 // Only what the request carried: an omitted field stays `None` and is
178 // never written, so a concurrent PATCH of the other field survives. (A
179 // JSON `null` deserializes to `None` too — neither column is nullable, so
180 // "omitted" and "null" both mean "keep it".)
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/// Delete a note owned by the current user, along with its files.
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)]
206async 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 // Rows go first (the note delete cascades them), blobs after: a crash in
215 // between strands at worst an unreachable blob, never a row whose blob is
216 // already gone. The files to unlink come from the delete itself, not a
217 // pre-read list — an upload that landed in between is in the cascade too.
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/// A note file's stored metadata; the bytes themselves come from the
226/// download endpoint.
227#[derive(Serialize, ToSchema)]
228struct NoteFileResponse {
229 id: String,
230 /// The uploader's original filename.
231 #[schema(example = "homework.pdf")]
232 name: String,
233 /// MIME type as declared on upload.
234 #[schema(example = "application/pdf")]
235 content_type: String,
236 /// File size in bytes.
237 #[schema(example = 24_576)]
238 size: i64,
239}
240
241impl 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/// Attach a file to a note owned by the current user. `multipart/form-data`
253/// with the file under a `file` field; its `filename` is required. At most
254/// 10 files per note; each file at most the school's `max_file_bytes`
255/// (settings, default 5 MiB).
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)]
273async 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 // The 10-file cap is enforced inside `NoteFile::insert` (count and create
283 // under one lock) — checking it here too would just race.
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 // Blob first, row second — a stored row always points at a real blob. If
291 // the row insert fails, take the fresh blob back out.
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/// List a note's files (metadata only), newest first. Paged via
307/// `?limit=&offset=`.
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)]
322async 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/// Download a note file's bytes. `Content-Type` is the one declared on
338/// upload; `Content-Disposition` carries the original filename.
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)]
355async 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 // The row exists but its blob doesn't — that's server-side damage
370 // (a lost volume path), not a client 404.
371 AppError::Internal(format!(
372 "missing blob for note file {}: {err}",
373 file.get_id().key()
374 ))
375 })?;
376 // The stored content type is validated ASCII without control characters,
377 // so it always parses; the fallback is for belt and braces.
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/// Delete a note file (row first, then its blob).
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)]
409async 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/// `Content-Disposition` for a download: an ASCII-safe `filename` fallback
426/// plus the RFC 5987 `filename*` form so non-ASCII names (`ödev.pdf`) survive.
427/// `attachment`, so an uploaded HTML/SVG never renders inline — shared with
428/// homework submission files, which take any content type.
429pub(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/// Percent-encode everything outside RFC 5987's `attr-char` set, on UTF-8
447/// bytes.
448fn 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)]
474mod 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 // Non-ASCII survives in the RFC 5987 form; the fallback degrades.
484 assert_eq!(
485 content_disposition("ödev 1.pdf"),
486 "attachment; filename=\"_dev 1.pdf\"; filename*=UTF-8''%C3%B6dev%201.pdf"
487 );
488 // Quotes can't break out of the quoted fallback.
489 assert_eq!(
490 content_disposition("a\"b.pdf"),
491 "attachment; filename=\"a_b.pdf\"; filename*=UTF-8''a%22b.pdf"
492 );
493 }
494}