forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB08aa13eAhmet Kaan Gümüş2 months ago378 commits

notes.rs485 lines, 17.8 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 `NoteFile::insert` (count and create
276 // under one lock) — checking it here too would just race.
277 let limit = service::settings::load(&st.db).await?.get_max_file_bytes();
278
279 let upload = read_upload(&mut multipart, limit).await?;
280 let name = FileName::try_new(&upload.name.unwrap_or_default())?;
281 let content_type = FileContentType::try_new(&upload.content_type.unwrap_or_default())?;
282
283 // Blob first, row second — a stored row always points at a real blob. If
284 // the row insert fails, take the fresh blob back out.
285 let file = NoteFile::new(note.get_id(), name, content_type, upload.data.len() as i64);
286 let path = blob_path(&st.files_path, file.get_id().key());
287 crate::web::ensure_files_dir(&st.files_path).await?;
288 tokio::fs::write(&path, &upload.data)
289 .await
290 .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?;
291 match file.insert(&st.db).await {
292 Ok(created) => Ok((StatusCode::CREATED, Json(NoteFileResponse::new(&created)))),
293 Err(err) => {
294 let _ = tokio::fs::remove_file(&path).await;
295 Err(err)
296 }
297 }
298}
299
300/// List a note's files (metadata only), newest first. Paged via
301/// `?limit=&offset=`.
302#[utoipa::path(
303 get,
304 path = "/{id}/files",
305 tag = "notes",
306 security(("session_cookie" = [])),
307 params(("id" = String, Path, description = "Note id"), PageParams),
308 responses(
309 (status = 200, description = "A page of the note's files", body = Page<NoteFileResponse>),
310 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
311 (status = 401, description = "Not authenticated", body = ErrorResponse),
312 (status = 404, description = "Note not found", body = ErrorResponse),
313 ),
314)]
315async fn list_files(
316 State(st): State<AppState>,
317 CurrentUser(user): CurrentUser,
318 Path(id): Path<String>,
319 Query(page): Query<PageParams>,
320) -> Result<Json<Page<NoteFileResponse>>, AppError> {
321 let (limit, offset) = page.resolve()?;
322 let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id())
323 .await?
324 .ok_or(AppError::NotFound)?;
325 let (files, total) = NoteFile::list_for(note.get_id(), limit, offset, &st.db).await?;
326 let items = files.iter().map(NoteFileResponse::new).collect();
327 Ok(Json(Page::new(items, total, limit, offset)))
328}
329
330/// Download a note file's bytes. `Content-Type` is the one declared on
331/// upload; `Content-Disposition` carries the original filename.
332#[utoipa::path(
333 get,
334 path = "/{id}/files/{file_id}",
335 tag = "notes",
336 security(("session_cookie" = [])),
337 params(
338 ("id" = String, Path, description = "Note id"),
339 ("file_id" = String, Path, description = "File id"),
340 ),
341 responses(
342 (status = 200, description = "The file bytes", content_type = "application/octet-stream"),
343 (status = 401, description = "Not authenticated", body = ErrorResponse),
344 (status = 404, description = "Note or file not found", body = ErrorResponse),
345 ),
346)]
347async fn download_file(
348 State(st): State<AppState>,
349 CurrentUser(user): CurrentUser,
350 Path((id, file_id)): Path<(String, String)>,
351) -> Result<Response, AppError> {
352 let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id())
353 .await?
354 .ok_or(AppError::NotFound)?;
355 let file = NoteFile::read_for(&NoteFileId::from_key(&file_id), note.get_id(), &st.db)
356 .await?
357 .ok_or(AppError::NotFound)?;
358 let bytes = tokio::fs::read(blob_path(&st.files_path, file.get_id().key()))
359 .await
360 .map_err(|err| {
361 // The row exists but its blob doesn't — that's server-side damage
362 // (a lost volume path), not a client 404.
363 AppError::Internal(format!(
364 "missing blob for note file {}: {err}",
365 file.get_id().key()
366 ))
367 })?;
368 // The stored content type is validated ASCII without control characters,
369 // so it always parses; the fallback is for belt and braces.
370 let content_type = HeaderValue::from_str(file.get_content_type().as_str())
371 .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"));
372 let disposition = HeaderValue::from_str(&content_disposition(file.get_name().as_str()))
373 .unwrap_or_else(|_| HeaderValue::from_static("attachment"));
374 Ok((
375 [
376 (CONTENT_TYPE, content_type),
377 (CONTENT_DISPOSITION, disposition),
378 ],
379 bytes,
380 )
381 .into_response())
382}
383
384/// Delete a note file (row first, then its blob).
385#[utoipa::path(
386 delete,
387 path = "/{id}/files/{file_id}",
388 tag = "notes",
389 security(("session_cookie" = [])),
390 params(
391 ("id" = String, Path, description = "Note id"),
392 ("file_id" = String, Path, description = "File id"),
393 ),
394 responses(
395 (status = 204, description = "Deleted"),
396 (status = 401, description = "Not authenticated", body = ErrorResponse),
397 (status = 404, description = "Note or file not found", body = ErrorResponse),
398 ),
399)]
400async fn delete_file(
401 State(st): State<AppState>,
402 CurrentUser(user): CurrentUser,
403 Path((id, file_id)): Path<(String, String)>,
404) -> Result<StatusCode, AppError> {
405 let note = service::note::read_owned(&st.db, &NoteId::from_key(&id), user.get_id())
406 .await?
407 .ok_or(AppError::NotFound)?;
408 let file = NoteFile::read_for(&NoteFileId::from_key(&file_id), note.get_id(), &st.db)
409 .await?
410 .ok_or(AppError::NotFound)?;
411 let file = file.delete(&st.db).await?;
412 remove_blob(&st.files_path, file.get_id().key()).await;
413 Ok(StatusCode::NO_CONTENT)
414}
415
416/// `Content-Disposition` for a download: an ASCII-safe `filename` fallback
417/// plus the RFC 5987 `filename*` form so non-ASCII names (`ödev.pdf`) survive.
418/// `attachment`, so an uploaded HTML/SVG never renders inline — shared with
419/// homework submission files, which take any content type.
420pub(crate) fn content_disposition(name: &str) -> String {
421 let fallback: String = name
422 .chars()
423 .map(|c| {
424 if c.is_ascii_graphic() && c != '"' && c != '\\' || c == ' ' {
425 c
426 } else {
427 '_'
428 }
429 })
430 .collect();
431 format!(
432 "attachment; filename=\"{fallback}\"; filename*=UTF-8''{}",
433 rfc5987_encode(name)
434 )
435}
436
437/// Percent-encode everything outside RFC 5987's `attr-char` set, on UTF-8
438/// bytes.
439fn rfc5987_encode(value: &str) -> String {
440 let mut out = String::with_capacity(value.len());
441 for byte in value.bytes() {
442 match byte {
443 b'a'..=b'z'
444 | b'A'..=b'Z'
445 | b'0'..=b'9'
446 | b'!'
447 | b'#'
448 | b'$'
449 | b'&'
450 | b'+'
451 | b'-'
452 | b'.'
453 | b'^'
454 | b'_'
455 | b'`'
456 | b'|'
457 | b'~' => out.push(byte as char),
458 _ => out.push_str(&format!("%{byte:02X}")),
459 }
460 }
461 out
462}
463
464#[cfg(test)]
465mod tests {
466 use super::*;
467
468 #[tokio::test]
469 async fn disposition_keeps_ascii_and_encodes_the_rest() {
470 assert_eq!(
471 content_disposition("plan.pdf"),
472 "attachment; filename=\"plan.pdf\"; filename*=UTF-8''plan.pdf"
473 );
474 // Non-ASCII survives in the RFC 5987 form; the fallback degrades.
475 assert_eq!(
476 content_disposition("ödev 1.pdf"),
477 "attachment; filename=\"_dev 1.pdf\"; filename*=UTF-8''%C3%B6dev%201.pdf"
478 );
479 // Quotes can't break out of the quoted fallback.
480 assert_eq!(
481 content_disposition("a\"b.pdf"),
482 "attachment; filename=\"a_b.pdf\"; filename*=UTF-8''a%22b.pdf"
483 );
484 }
485}