forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBcd6bccfAhmet Kaan Gümüş4 months ago177 commits

notes.rs492 lines, 18.2 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 ),
85)]
86async fn create(
87 State(st): State<AppState>,
88 RequireStudent(user): RequireStudent,
89 Json(req): Json<CreateNote>,
90) -> Result<(StatusCode, Json<NoteResponse>), AppError> {
91 let title = NoteTitle::try_new(&req.title)?;
92 let content = NoteContent::try_new(&req.content.unwrap_or_default())?;
93 let note = Note::create(user.get_id(), title, content, &st.db).await?;
94 Ok((StatusCode::CREATED, Json(NoteResponse::new(&note))))
95}
96
97/// List the notes owned by the current user, newest first. Paged via
98/// `?limit=&offset=` (omit `limit` for all of them); returns a
99/// `{items, total, limit, offset}` envelope.
100#[utoipa::path(
101 get,
102 path = "/",
103 tag = "notes",
104 security(("session_cookie" = [])),
105 params(PageParams),
106 responses(
107 (status = 200, description = "A page of the user's notes (all of them when unpaged)", body = Page<NoteResponse>),
108 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
109 (status = 401, description = "Not authenticated", body = ErrorResponse),
110 (status = 403, description = "Requires the student role or higher", body = ErrorResponse),
111 ),
112)]
113async fn list(
114 State(st): State<AppState>,
115 RequireStudent(user): RequireStudent,
116 Query(page): Query<PageParams>,
117) -> Result<Json<Page<NoteResponse>>, AppError> {
118 let (limit, offset) = page.resolve()?;
119 let (notes, total) = Note::list_for(user.get_id(), limit, offset, &st.db).await?;
120 let items = notes.iter().map(NoteResponse::new).collect();
121 Ok(Json(Page::new(items, total, limit, offset)))
122}
123
124/// Fetch a single note by id (must be owned by the current user).
125#[utoipa::path(
126 get,
127 path = "/{id}",
128 tag = "notes",
129 security(("session_cookie" = [])),
130 params(("id" = String, Path, description = "Note id")),
131 responses(
132 (status = 200, description = "The note", body = NoteResponse),
133 (status = 401, description = "Not authenticated", body = ErrorResponse),
134 (status = 403, description = "Requires the student role or higher", body = ErrorResponse),
135 (status = 404, description = "Not found", body = ErrorResponse),
136 ),
137)]
138async fn get_one(
139 State(st): State<AppState>,
140 RequireStudent(user): RequireStudent,
141 Path(id): Path<String>,
142) -> Result<Json<NoteResponse>, AppError> {
143 let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db)
144 .await?
145 .ok_or(AppError::NotFound)?;
146 Ok(Json(NoteResponse::new(&note)))
147}
148
149/// Update a note's title and/or content. Omitted fields keep their value.
150#[utoipa::path(
151 patch,
152 path = "/{id}",
153 tag = "notes",
154 security(("session_cookie" = [])),
155 params(("id" = String, Path, description = "Note id")),
156 request_body = UpdateNote,
157 responses(
158 (status = 200, description = "Updated note", body = NoteResponse),
159 (status = 400, description = "Invalid title or content", body = ErrorResponse),
160 (status = 401, description = "Not authenticated", body = ErrorResponse),
161 (status = 403, description = "Requires the student role or higher", body = ErrorResponse),
162 (status = 404, description = "Not found", body = ErrorResponse),
163 ),
164)]
165async fn update(
166 State(st): State<AppState>,
167 RequireStudent(user): RequireStudent,
168 Path(id): Path<String>,
169 Json(req): Json<UpdateNote>,
170) -> Result<Json<NoteResponse>, AppError> {
171 let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db)
172 .await?
173 .ok_or(AppError::NotFound)?;
174
175 // Only what the request carried: an omitted field stays `None` and is
176 // never written, so a concurrent PATCH of the other field survives. (A
177 // JSON `null` deserializes to `None` too — neither column is nullable, so
178 // "omitted" and "null" both mean "keep it".)
179 let title = req.title.as_deref().map(NoteTitle::try_new).transpose()?;
180 let content = req
181 .content
182 .as_deref()
183 .map(NoteContent::try_new)
184 .transpose()?;
185
186 let updated = note.update(title, content, &st.db).await?;
187 Ok(Json(NoteResponse::new(&updated)))
188}
189
190/// Delete a note owned by the current user, along with its files.
191#[utoipa::path(
192 delete,
193 path = "/{id}",
194 tag = "notes",
195 security(("session_cookie" = [])),
196 params(("id" = String, Path, description = "Note id")),
197 responses(
198 (status = 204, description = "Deleted"),
199 (status = 401, description = "Not authenticated", body = ErrorResponse),
200 (status = 403, description = "Requires the student role or higher", body = ErrorResponse),
201 (status = 404, description = "Not found", body = ErrorResponse),
202 ),
203)]
204async fn delete_one(
205 State(st): State<AppState>,
206 RequireStudent(user): RequireStudent,
207 Path(id): Path<String>,
208) -> Result<StatusCode, AppError> {
209 let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db)
210 .await?
211 .ok_or(AppError::NotFound)?;
212 // Rows go first (the note delete cascades them), blobs after: a crash in
213 // between strands at worst an unreachable blob, never a row whose blob is
214 // already gone.
215 let (files, _) = NoteFile::list_for(note.get_id(), None, 0, &st.db).await?;
216 note.delete(&st.db).await?;
217 for file in &files {
218 remove_blob(&st.files_path, file.get_id().key()).await;
219 }
220 Ok(StatusCode::NO_CONTENT)
221}
222
223/// A note file's stored metadata; the bytes themselves come from the
224/// download endpoint.
225#[derive(Serialize, ToSchema)]
226struct NoteFileResponse {
227 id: String,
228 /// The uploader's original filename.
229 #[schema(example = "homework.pdf")]
230 name: String,
231 /// MIME type as declared on upload.
232 #[schema(example = "application/pdf")]
233 content_type: String,
234 /// File size in bytes.
235 #[schema(example = 24_576)]
236 size: i64,
237}
238
239impl NoteFileResponse {
240 fn new(file: &NoteFile) -> Self {
241 Self {
242 id: file.get_id().key().to_string(),
243 name: file.get_name().as_str().to_string(),
244 content_type: file.get_content_type().as_str().to_string(),
245 size: file.get_size(),
246 }
247 }
248}
249
250/// Attach a file to a note owned by the current user. `multipart/form-data`
251/// with the file under a `file` field; its `filename` is required. At most
252/// 10 files per note; each file at most the school's `max_file_bytes`
253/// (settings, default 5 MiB).
254#[utoipa::path(
255 post,
256 path = "/{id}/files",
257 tag = "notes",
258 security(("session_cookie" = [])),
259 params(("id" = String, Path, description = "Note id")),
260 request_body(content = UploadFileForm, content_type = "multipart/form-data"),
261 responses(
262 (status = 201, description = "File stored", body = NoteFileResponse),
263 (status = 400, description = "Missing file field, invalid filename or content type, or empty file", body = ErrorResponse),
264 (status = 401, description = "Not authenticated", body = ErrorResponse),
265 (status = 403, description = "Requires the student role or higher", body = ErrorResponse),
266 (status = 404, description = "Note not found", body = ErrorResponse),
267 (status = 409, description = "The note already holds the maximum number of files", body = ErrorResponse),
268 (status = 413, description = "File exceeds the school's size limit", body = ErrorResponse),
269 ),
270)]
271async fn upload_file(
272 State(st): State<AppState>,
273 RequireStudent(user): RequireStudent,
274 Path(id): Path<String>,
275 mut multipart: Multipart,
276) -> Result<(StatusCode, Json<NoteFileResponse>), AppError> {
277 let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db)
278 .await?
279 .ok_or(AppError::NotFound)?;
280 // The 10-file cap is enforced inside `NoteFile::insert` (count and create
281 // under one lock) — checking it here too would just race.
282 let limit = Settings::load(&st.db).await?.get_max_file_bytes();
283
284 let upload = read_upload(&mut multipart, limit).await?;
285 let name = FileName::try_new(&upload.name.unwrap_or_default())?;
286 let content_type = FileContentType::try_new(&upload.content_type.unwrap_or_default())?;
287
288 // Blob first, row second — a stored row always points at a real blob. If
289 // the row insert fails, take the fresh blob back out.
290 let file = NoteFile::new(note.get_id(), name, content_type, upload.data.len() as i64);
291 let path = blob_path(&st.files_path, file.get_id().key());
292 tokio::fs::write(&path, &upload.data)
293 .await
294 .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?;
295 match file.insert(&st.db).await {
296 Ok(created) => Ok((StatusCode::CREATED, Json(NoteFileResponse::new(&created)))),
297 Err(err) => {
298 let _ = tokio::fs::remove_file(&path).await;
299 Err(err)
300 }
301 }
302}
303
304/// List a note's files (metadata only), newest first. Paged via
305/// `?limit=&offset=`.
306#[utoipa::path(
307 get,
308 path = "/{id}/files",
309 tag = "notes",
310 security(("session_cookie" = [])),
311 params(("id" = String, Path, description = "Note id"), PageParams),
312 responses(
313 (status = 200, description = "A page of the note's files", body = Page<NoteFileResponse>),
314 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
315 (status = 401, description = "Not authenticated", body = ErrorResponse),
316 (status = 403, description = "Requires the student role or higher", body = ErrorResponse),
317 (status = 404, description = "Note not found", body = ErrorResponse),
318 ),
319)]
320async fn list_files(
321 State(st): State<AppState>,
322 RequireStudent(user): RequireStudent,
323 Path(id): Path<String>,
324 Query(page): Query<PageParams>,
325) -> Result<Json<Page<NoteFileResponse>>, AppError> {
326 let (limit, offset) = page.resolve()?;
327 let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db)
328 .await?
329 .ok_or(AppError::NotFound)?;
330 let (files, total) = NoteFile::list_for(note.get_id(), limit, offset, &st.db).await?;
331 let items = files.iter().map(NoteFileResponse::new).collect();
332 Ok(Json(Page::new(items, total, limit, offset)))
333}
334
335/// Download a note file's bytes. `Content-Type` is the one declared on
336/// upload; `Content-Disposition` carries the original filename.
337#[utoipa::path(
338 get,
339 path = "/{id}/files/{file_id}",
340 tag = "notes",
341 security(("session_cookie" = [])),
342 params(
343 ("id" = String, Path, description = "Note id"),
344 ("file_id" = String, Path, description = "File id"),
345 ),
346 responses(
347 (status = 200, description = "The file bytes", content_type = "application/octet-stream"),
348 (status = 401, description = "Not authenticated", body = ErrorResponse),
349 (status = 403, description = "Requires the student role or higher", body = ErrorResponse),
350 (status = 404, description = "Note or file not found", body = ErrorResponse),
351 ),
352)]
353async fn download_file(
354 State(st): State<AppState>,
355 RequireStudent(user): RequireStudent,
356 Path((id, file_id)): Path<(String, String)>,
357) -> Result<Response, AppError> {
358 let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db)
359 .await?
360 .ok_or(AppError::NotFound)?;
361 let file = NoteFile::read_for(&NoteFileId::from_key(&file_id), note.get_id(), &st.db)
362 .await?
363 .ok_or(AppError::NotFound)?;
364 let bytes = tokio::fs::read(blob_path(&st.files_path, file.get_id().key()))
365 .await
366 .map_err(|err| {
367 // The row exists but its blob doesn't — that's server-side damage
368 // (a lost volume path), not a client 404.
369 AppError::Internal(format!(
370 "missing blob for note file {}: {err}",
371 file.get_id().key()
372 ))
373 })?;
374 // The stored content type is validated ASCII without control characters,
375 // so it always parses; the fallback is for belt and braces.
376 let content_type = HeaderValue::from_str(file.get_content_type().as_str())
377 .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"));
378 let disposition = HeaderValue::from_str(&content_disposition(file.get_name().as_str()))
379 .unwrap_or_else(|_| HeaderValue::from_static("attachment"));
380 Ok((
381 [
382 (CONTENT_TYPE, content_type),
383 (CONTENT_DISPOSITION, disposition),
384 ],
385 bytes,
386 )
387 .into_response())
388}
389
390/// Delete a note file (row first, then its blob).
391#[utoipa::path(
392 delete,
393 path = "/{id}/files/{file_id}",
394 tag = "notes",
395 security(("session_cookie" = [])),
396 params(
397 ("id" = String, Path, description = "Note id"),
398 ("file_id" = String, Path, description = "File id"),
399 ),
400 responses(
401 (status = 204, description = "Deleted"),
402 (status = 401, description = "Not authenticated", body = ErrorResponse),
403 (status = 403, description = "Requires the student role or higher", body = ErrorResponse),
404 (status = 404, description = "Note or file not found", body = ErrorResponse),
405 ),
406)]
407async fn delete_file(
408 State(st): State<AppState>,
409 RequireStudent(user): RequireStudent,
410 Path((id, file_id)): Path<(String, String)>,
411) -> Result<StatusCode, AppError> {
412 let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db)
413 .await?
414 .ok_or(AppError::NotFound)?;
415 let file = NoteFile::read_for(&NoteFileId::from_key(&file_id), note.get_id(), &st.db)
416 .await?
417 .ok_or(AppError::NotFound)?;
418 let file = file.delete(&st.db).await?;
419 remove_blob(&st.files_path, file.get_id().key()).await;
420 Ok(StatusCode::NO_CONTENT)
421}
422
423/// `Content-Disposition` for a download: an ASCII-safe `filename` fallback
424/// plus the RFC 5987 `filename*` form so non-ASCII names (`ödev.pdf`) survive.
425/// `attachment`, so an uploaded HTML/SVG never renders inline — shared with
426/// homework submission files, which take any content type.
427pub(crate) fn content_disposition(name: &str) -> String {
428 let fallback: String = name
429 .chars()
430 .map(|c| {
431 if c.is_ascii_graphic() && c != '"' && c != '\\' || c == ' ' {
432 c
433 } else {
434 '_'
435 }
436 })
437 .collect();
438 format!(
439 "attachment; filename=\"{fallback}\"; filename*=UTF-8''{}",
440 rfc5987_encode(name)
441 )
442}
443
444/// Percent-encode everything outside RFC 5987's `attr-char` set, on UTF-8
445/// bytes.
446fn rfc5987_encode(value: &str) -> String {
447 let mut out = String::with_capacity(value.len());
448 for byte in value.bytes() {
449 match byte {
450 b'a'..=b'z'
451 | b'A'..=b'Z'
452 | b'0'..=b'9'
453 | b'!'
454 | b'#'
455 | b'$'
456 | b'&'
457 | b'+'
458 | b'-'
459 | b'.'
460 | b'^'
461 | b'_'
462 | b'`'
463 | b'|'
464 | b'~' => out.push(byte as char),
465 _ => out.push_str(&format!("%{byte:02X}")),
466 }
467 }
468 out
469}
470
471#[cfg(test)]
472mod tests {
473 use super::*;
474
475 #[tokio::test]
476 async fn disposition_keeps_ascii_and_encodes_the_rest() {
477 assert_eq!(
478 content_disposition("plan.pdf"),
479 "attachment; filename=\"plan.pdf\"; filename*=UTF-8''plan.pdf"
480 );
481 // Non-ASCII survives in the RFC 5987 form; the fallback degrades.
482 assert_eq!(
483 content_disposition("ödev 1.pdf"),
484 "attachment; filename=\"_dev 1.pdf\"; filename*=UTF-8''%C3%B6dev%201.pdf"
485 );
486 // Quotes can't break out of the quoted fallback.
487 assert_eq!(
488 content_disposition("a\"b.pdf"),
489 "attachment; filename=\"a_b.pdf\"; filename*=UTF-8''a%22b.pdf"
490 );
491 }
492}