forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBaf331ecAhmet Kaan Gümüş2 months ago451 commits

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