forge
Explore
Log in

Don't you dare go Hollow

Images on questions and choice options

Browse files at this commit

dbeb12287aee26a27d5f0b4bfd55fb1f91fd4898Ahmet Kaan GümüşParent: 7d8df31
  • feat
    • images on questions and choice options
Show full message
✨ feat(exams): images on questions and choice options

Teachers pin one illustration to any question (the map above the
prompt) and one picture per option on choice questions — the options
themselves can be images. Multipart upload per slot, replace by
re-upload, frozen with the question once attempts exist.

- rows in question_image (deterministic id per slot, UPSERT = replace);
  blobs beside note files under FILES_PATH, capped by max_file_bytes
- raster allowlist png/jpeg/webp/gif — SVG can script and these bytes
  render inline to students; served with nosniff + private, no-store
- students fetch bytes behind the sitting wall (enrollment + started
  attempt, no early peek); course managers anytime
- replacing a question's choices drops its option pictures (the
  illustration stays) — old pictures belong to the old options
- blob cleanup wired into image replace/delete and question, exam,
  and course deletes (exam cascade result slot shifted 5 -> 6)

15 changed files +1413 -139

README.mdmodified+44 -12
@@ -30,7 +30,11 @@ fixed window), **async** (start anytime inside the window, with a personal
30 time budget), or **open** (sit anytime, optionally timed per attempt);30 time budget), or **open** (sit anytime, optionally timed per attempt);
31 students *sit* them via attempts — retakes metered by a per-exam limit31 students *sit* them via attempts — retakes metered by a per-exam limit
32 (`0` = unlimited), leaving the exam room governed by a teacher-controlled32 (`0` = unlimited), leaving the exam room governed by a teacher-controlled
33-rejoin door — and teachers watch attendance, per-student remaining time,33+rejoin door. Questions can carry **images**: any question may hold one
34+illustration (a map above the prompt), and each option of a choice question
35+may be a picture of its own (pick the right city off the map) — raster
36+uploads capped by the same `max_file_bytes` policy as note files. Teachers
37+watch attendance, per-student remaining time,
34 sittings, walk-outs, no-shows (`absent` once the window closes), submissions,38 sittings, walk-outs, no-shows (`absent` once the window closes), submissions,
35 and marks land live on a monitor endpoint (snapshot or SSE stream). Courses also carry **lesson39 and marks land live on a monitor endpoint (snapshot or SSE stream). Courses also carry **lesson
36 sessions** with teacher-taken roll call (students never self-mark a lesson),40 sessions** with teacher-taken roll call (students never self-mark a lesson),
@@ -197,7 +201,7 @@ effect on the user's very next call (no re-login).
197 | View **visible** courses/exams and a course's subjects; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created; `manager`+: all) |201 | View **visible** courses/exams and a course's subjects; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created; `manager`+: all) |
198 | Sit a sittable exam (`sync`/`async`/`open`): start / resume / retake / read / submit **own** attempt | student | **Students only** — staff never sit; must be enrolled; window (where one exists) and `max_attempts` enforced by the server |202 | Sit a sittable exam (`sync`/`async`/`open`): start / resume / retake / read / submit **own** attempt | student | **Students only** — staff never sit; must be enrolled; window (where one exists) and `max_attempts` enforced by the server |
199 | Answer questions inside **own** attempt (REST autosave or the exam-room WebSocket) | student | **Students only**; attempt must be `in_progress`; deadline judged by the server clock; blocked after leaving the room while `allow_rejoin` is off |203 | Answer questions inside **own** attempt (REST autosave or the exam-room WebSocket) | student | **Students only**; attempt must be `in_progress`; deadline judged by the server clock; blocked after leaving the room while `allow_rejoin` is off |
200-| Author an exam's questions (add/edit/delete) | teacher | Course-management rights; frozen once anyone has an attempt |204+| Author an exam's questions (add/edit/delete, incl. question + option images) | teacher | Course-management rights; frozen once anyone has an attempt |
201 | Read a question list (with `correct`) or a student's answer sheet | teacher | Course-management rights — one teacher can't read another's answer key |205 | Read a question list (with `correct`) or a student's answer sheet | teacher | Course-management rights — one teacher can't read another's answer key |
202 | Watch an exam's live monitor (snapshot or SSE stream) | teacher | Course-management rights |206 | Watch an exam's live monitor (snapshot or SSE stream) | teacher | Course-management rights |
203 | Create courses | teacher | The creator manages the course |207 | Create courses | teacher | The creator manages the course |
@@ -340,7 +344,7 @@ their existing shapes: the student exam-room reads
340 | GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all) · paged |344 | GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all) · paged |
341 | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+) |345 | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+) |
342 | PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin` (course manager; `course` immutable, `mode` frozen once attempted — the rest stays live) |346 | PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin` (course manager; `course` immutable, `mode` frozen once attempted — the rest stays live) |
343-| DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, and answers (course manager) |347+| DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question images (course manager) |
344 | POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled student** (upsert; course manager; students only) |348 | POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled student** (upsert; course manager; students only) |
345 | GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) · paged |349 | GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) · paged |
346 | GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |350 | GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |
@@ -353,7 +357,13 @@ their existing shapes: the student exam-room reads
353 | GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) · paged |357 | GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) · paged |
354 | PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question — the kind bundle revalidates as a unit (course manager; frozen once attempted) |358 | PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question — the kind bundle revalidates as a unit (course manager; frozen once attempted) |
355 | DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) |359 | DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) |
356-| GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded (requires enrollment + an attempt) |360+| GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded, image metadata included (requires enrollment + an attempt) |
361+| POST | `/exams/{id}/questions/{qid}/image` | teacher | Attach/replace the question's illustration: `multipart/form-data`, one `file` part — raster images only (`png`/`jpeg`/`webp`/`gif`), ≤ `max_file_bytes` (course manager; frozen once attempted) |
362+| GET | `/exams/{id}/questions/{qid}/image` | student | The illustration bytes (course manager anytime; students enrolled + attempt started) |
363+| DELETE | `/exams/{id}/questions/{qid}/image` | teacher | Remove the illustration (course manager; frozen once attempted) |
364+| POST | `/exams/{id}/questions/{qid}/choices/{index}/image` | teacher | Attach/replace option `index`'s picture (`choice` questions; same form and limits as above) |
365+| GET | `/exams/{id}/questions/{qid}/choices/{index}/image` | student | The option picture's bytes (same access as the illustration) |
366+| DELETE | `/exams/{id}/questions/{qid}/choices/{index}/image` | teacher | Remove one option picture (course manager; frozen once attempted) |
357 | POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \| text?}` — autosave one answer while a student, enrolled, and `in_progress` (and not locked out by a closed rejoin door) |367 | POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \| text?}` — autosave one answer while a student, enrolled, and `in_progress` (and not locked out by a closed rejoin door) |
358 | GET | `/exams/{id}/attempts/{user}/answers` | teacher | A student's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |368 | GET | `/exams/{id}/attempts/{user}/answers` | teacher | A student's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |
359 | GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see "Taking an exam") |369 | GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see "Taking an exam") |
@@ -487,10 +497,10 @@ editable `settings` singleton (`GET /settings` for any signed-in user,
487 averaging stay `0`–`100` forever — bands only add `grade`,497 averaging stay `0`–`100` forever — bands only add `grade`,
488 `average_grade`, and `overall_grade` labels to the mark report, so a school498 `average_grade`, and `overall_grade` labels to the mark report, so a school
489 can switch display scales without touching a single stored mark.499 can switch display scales without touching a single stored mark.
490-- **`max_file_bytes`** — the per-file size cap for note uploads, in bytes:500+- **`max_file_bytes`** — the per-file size cap for uploads (note files and
491- `1024` (1 KiB) to `26214400` (25 MiB; a server hard cap — uploads buffer in501+ exam question images alike), in bytes: `1024` (1 KiB) to `26214400` (25 MiB;
492- memory), default `5242880` (5 MiB). Checked at upload time only:502+ a server hard cap — uploads buffer in memory), default `5242880` (5 MiB).
493- lowering it never touches already-stored files.503+ Checked at upload time only: lowering it never touches already-stored files.
494 504
495 A `PATCH` replaces only the fields it carries, each wholesale, and validation505 A `PATCH` replaces only the fields it carries, each wholesale, and validation
496 is all-or-nothing. Concurrent edits are safe: each save applies only if the506 is all-or-nothing. Concurrent edits are safe: each save applies only if the
@@ -590,9 +600,10 @@ const es = new EventSource(`${BASE}/exams/${id}/live/stream`, { withCredentials:
590 es.addEventListener("snapshot", (e) => render(JSON.parse(e.data)));600 es.addEventListener("snapshot", (e) => render(JSON.parse(e.data)));
591 ```601 ```
592 602
593-Deleting an exam (or its course) cascades attempts, questions, and answers603+Deleting an exam (or its course) cascades attempts, questions, answers, and
594-along with results; unenrolling mid-exam hides the student from the monitor604+question images (blobs included) along with results; unenrolling mid-exam
595-roster but keeps the attempt and mark rows, mirroring the marks report.605+hides the student from the monitor roster but keeps the attempt and mark
606+rows, mirroring the marks report.
596 607
597 > **Upgrading a pre-course database**: `exam` rows created before courses608 > **Upgrading a pre-course database**: `exam` rows created before courses
598 > existed lack the now-required `course` field and will fail to deserialize.609 > existed lack the now-required `course` field and will fail to deserialize.
@@ -635,7 +646,28 @@ switching a question to `text` needs explicit `"choices": null, "correct":
635 null`, switching to `choice` must bring both along. Presentation order is646 null`, switching to `choice` must bring both along. Presentation order is
636 creation order. The whole list **freezes once anyone has started an attempt**647 creation order. The whole list **freezes once anyone has started an attempt**
637 (`409` on create/edit/delete) — editing questions under a sitting student648 (`409` on create/edit/delete) — editing questions under a sitting student
638-would fork what "the exam" means. Deleting a question cascades its answers.649+would fork what "the exam" means. Deleting a question cascades its answers
650+and images.
651+
652+**Question images**: any question may carry one **illustration** (`POST
653+/exams/{id}/questions/{qid}/image` — the map the prompt asks about, on
654+`choice` and `text` questions alike), and each option of a `choice` question
655+may carry a **picture** of its own (`POST .../choices/{index}/image` — so
656+the options themselves can be images: four map crops, pick the right one).
657+Uploads are `multipart/form-data` with a single `file` part, capped by the
658+school's `max_file_bytes`; the declared content type must be `image/png`,
659+`image/jpeg`, `image/webp`, or `image/gif` (rasters only — SVG can script,
660+and these bytes render inline for the whole class). One image per slot:
661+re-uploading replaces, `DELETE` on the same paths removes, and replacing a
662+question's `choices` list drops all its option pictures (the illustration
663+stays — re-upload against the new list). Image writes follow question
664+authoring exactly: course-management rights, frozen once attempts exist.
665+Both question views (`GET /exams/{id}/questions` and the sitting view)
666+embed the metadata as `image: {content_type, size} | null` and
667+`choice_images: [...|null]` aligned with `choices`; the bytes come from the
668+`GET` endpoints above — course managers anytime, students through the same
669+enrollment + started-attempt wall as the sitting view (no early peek at the
670+pictures either), served with `Cache-Control: private, no-store`.
639 671
640 **Answering** (student, attempt `in_progress`, deadline judged by the server672 **Answering** (student, attempt `in_progress`, deadline judged by the server
641 clock on every save):673 clock on every save):
src/constant.rsmodified+6 -0
@@ -55,6 +55,12 @@ pub const MAX_MAX_FILE_BYTES: i64 = 25 * 1024 * 1024;
55 /// the file bytes themselves.55 /// the file bytes themselves.
56 pub const UPLOAD_BODY_OVERHEAD_BYTES: usize = 64 * 1024;56 pub const UPLOAD_BODY_OVERHEAD_BYTES: usize = 64 * 1024;
57 57
58+/// The content types a question image may declare — raster formats only. SVG
59+/// is deliberately out: it can carry scripts, and these bytes are served for
60+/// inline display to everyone sitting the exam.
61+pub const QUESTION_IMAGE_CONTENT_TYPES: [&str; 4] =
62+ ["image/png", "image/jpeg", "image/webp", "image/gif"];
63+
58 pub const MAX_EVENT_TITLE_LEN: usize = 200;64 pub const MAX_EVENT_TITLE_LEN: usize = 200;
59 pub const MAX_EVENT_DESCRIPTION_LEN: usize = 2_000;65 pub const MAX_EVENT_DESCRIPTION_LEN: usize = 2_000;
60 66
src/database.rsmodified+11 -0
@@ -19,6 +19,7 @@ pub const EXAM_TABLE: &str = "exam";
19 pub const EXAM_RESULT_TABLE: &str = "exam_result";19 pub const EXAM_RESULT_TABLE: &str = "exam_result";
20 pub const EXAM_ATTEMPT_TABLE: &str = "exam_attempt";20 pub const EXAM_ATTEMPT_TABLE: &str = "exam_attempt";
21 pub const EXAM_QUESTION_TABLE: &str = "exam_question";21 pub const EXAM_QUESTION_TABLE: &str = "exam_question";
22+pub const QUESTION_IMAGE_TABLE: &str = "question_image";
22 pub const EXAM_ANSWER_TABLE: &str = "exam_answer";23 pub const EXAM_ANSWER_TABLE: &str = "exam_answer";
23 pub const COURSE_TABLE: &str = "course";24 pub const COURSE_TABLE: &str = "course";
24 pub const ENROLLMENT_TABLE: &str = "enrollment";25 pub const ENROLLMENT_TABLE: &str = "enrollment";
@@ -184,6 +185,16 @@ const MIGRATION: &str = "
184 DEFINE INDEX IF NOT EXISTS exam_question_exam ON exam_question FIELDS exam;185 DEFINE INDEX IF NOT EXISTS exam_question_exam ON exam_question FIELDS exam;
185 DEFINE INDEX IF NOT EXISTS exam_question_subject ON exam_question FIELDS subject;186 DEFINE INDEX IF NOT EXISTS exam_question_subject ON exam_question FIELDS subject;
186 187
188+ DEFINE TABLE IF NOT EXISTS question_image SCHEMAFULL;
189+ DEFINE FIELD IF NOT EXISTS exam ON question_image TYPE record<exam>;
190+ DEFINE FIELD IF NOT EXISTS question ON question_image TYPE record<exam_question>;
191+ DEFINE FIELD IF NOT EXISTS slot ON question_image TYPE option<int>;
192+ DEFINE FIELD IF NOT EXISTS file ON question_image TYPE string;
193+ DEFINE FIELD IF NOT EXISTS content_type ON question_image TYPE string;
194+ DEFINE FIELD IF NOT EXISTS size ON question_image TYPE int;
195+ DEFINE INDEX IF NOT EXISTS question_image_exam ON question_image FIELDS exam;
196+ DEFINE INDEX IF NOT EXISTS question_image_question ON question_image FIELDS question;
197+
187 DEFINE TABLE IF NOT EXISTS exam_answer SCHEMAFULL;198 DEFINE TABLE IF NOT EXISTS exam_answer SCHEMAFULL;
188 DEFINE FIELD IF NOT EXISTS exam ON exam_answer TYPE record<exam>;199 DEFINE FIELD IF NOT EXISTS exam ON exam_answer TYPE record<exam>;
189 DEFINE FIELD IF NOT EXISTS question ON exam_answer TYPE record<exam_question>;200 DEFINE FIELD IF NOT EXISTS question ON exam_answer TYPE record<exam_question>;
src/domain/course.rsmodified+7 -4
@@ -213,16 +213,19 @@ impl Course {
213 updated.ok_or(AppError::NotFound)213 updated.ok_or(AppError::NotFound)
214 }214 }
215 215
216- /// Delete the course and cascade-remove everything inside it: results and216+ /// Delete the course and cascade-remove everything inside it: results,
217- /// attempts of its exams, its enrollments, its sessions with their roll217+ /// attempts, and question images of its exams, its enrollments, its
218- /// call, its subjects, and the exams themselves. The children go in one218+ /// sessions with their roll call, its subjects, and the exams themselves.
219- /// transaction so a crash can't leave an exam pointing at a deleted course.219+ /// The children go in one transaction so a crash can't leave an exam
220+ /// pointing at a deleted course. The image *blobs* are the web layer's to
221+ /// remove — it collects their names before calling this.
220 pub async fn delete(self, db: &Database) -> Result<Course, AppError> {222 pub async fn delete(self, db: &Database) -> Result<Course, AppError> {
221 db.query(223 db.query(
222 "BEGIN TRANSACTION;224 "BEGIN TRANSACTION;
223 DELETE exam_result WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);225 DELETE exam_result WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
224 DELETE exam_attempt WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);226 DELETE exam_attempt WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
225 DELETE exam_answer WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);227 DELETE exam_answer WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
228+ DELETE question_image WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
226 DELETE exam_question WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);229 DELETE exam_question WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
227 DELETE session_attendance WHERE course = $course;230 DELETE session_attendance WHERE course = $course;
228 DELETE course_session WHERE course = $course;231 DELETE course_session WHERE course = $course;
src/domain/exam.rsmodified+7 -5
@@ -428,9 +428,10 @@ impl Exam {
428 updated.ok_or(AppError::NotFound)428 updated.ok_or(AppError::NotFound)
429 }429 }
430 430
431- /// Delete the exam and cascade-remove its result, attempt, question, and431+ /// Delete the exam and cascade-remove its result, attempt, question,
432- /// answer rows — all in one transaction, so a failure can't leave an432+ /// answer, and question-image rows — all in one transaction, so a failure
433- /// emptied-out exam shell behind.433+ /// can't leave an emptied-out exam shell behind. The image *blobs* are the
434+ /// web layer's to remove — it collects their names before calling this.
434 pub async fn delete(self, db: &Database) -> Result<Exam, AppError> {435 pub async fn delete(self, db: &Database) -> Result<Exam, AppError> {
435 let mut result = db436 let mut result = db
436 .query(437 .query(
@@ -438,6 +439,7 @@ impl Exam {
438 DELETE exam_result WHERE exam = $ex;439 DELETE exam_result WHERE exam = $ex;
439 DELETE exam_attempt WHERE exam = $ex;440 DELETE exam_attempt WHERE exam = $ex;
440 DELETE exam_answer WHERE exam = $ex;441 DELETE exam_answer WHERE exam = $ex;
442+ DELETE question_image WHERE exam = $ex;
441 DELETE exam_question WHERE exam = $ex;443 DELETE exam_question WHERE exam = $ex;
442 DELETE $ex RETURN BEFORE;444 DELETE $ex RETURN BEFORE;
443 COMMIT TRANSACTION;",445 COMMIT TRANSACTION;",
@@ -446,8 +448,8 @@ impl Exam {
446 .await?448 .await?
447 .check()?;449 .check()?;
448 // Statement slots count BEGIN and the child deletes: the exam's own450 // Statement slots count BEGIN and the child deletes: the exam's own
449- // DELETE is slot 5.451+ // DELETE is slot 6.
450- let deleted: Option<Exam> = result.take::<Vec<Exam>>(5)?.into_iter().next();452+ let deleted: Option<Exam> = result.take::<Vec<Exam>>(6)?.into_iter().next();
451 deleted.ok_or(AppError::NotFound)453 deleted.ok_or(AppError::NotFound)
452 }454 }
453 }455 }
src/domain/exam_question.rsmodified+10 -6
@@ -293,13 +293,17 @@ impl ExamQuestion {
293 updated.ok_or(AppError::NotFound)293 updated.ok_or(AppError::NotFound)
294 }294 }
295 295
296- /// Delete the question and cascade-remove its answers, so no answer row296+ /// Delete the question and cascade-remove its answers and image rows, so
297- /// can point at a missing question.297+ /// neither can point at a missing question. The image *blobs* are the web
298+ /// layer's to remove — it collects their names before calling this.
298 pub async fn delete(self, db: &Database) -> Result<ExamQuestion, AppError> {299 pub async fn delete(self, db: &Database) -> Result<ExamQuestion, AppError> {
299- db.query("DELETE exam_answer WHERE question = $q")300+ db.query(
300- .bind(("q", self.id.record()))301+ "DELETE exam_answer WHERE question = $q;
301- .await?302+ DELETE question_image WHERE question = $q;",
302- .check()?;303+ )
304+ .bind(("q", self.id.record()))
305+ .await?
306+ .check()?;
303 let deleted: Option<ExamQuestion> = db.delete(self.id.record()).await?;307 let deleted: Option<ExamQuestion> = db.delete(self.id.record()).await?;
304 deleted.ok_or(AppError::NotFound)308 deleted.ok_or(AppError::NotFound)
305 }309 }
src/domain/mod.rsmodified+1 -0
@@ -16,6 +16,7 @@ pub mod note;
16 pub mod note_file;16 pub mod note_file;
17 pub mod preferences;17 pub mod preferences;
18 pub mod profile;18 pub mod profile;
19+pub mod question_image;
19 pub mod registration;20 pub mod registration;
20 pub mod role;21 pub mod role;
21 pub mod session;22 pub mod session;
src/domain/question_image.rsadded+291 -0
@@ -0,0 +1,291 @@
1+//! An image pinned to an exam question — the question's own illustration
2+//! (`slot = NONE`, any kind: a map above the prompt) or one choice's picture
3+//! (`slot = i`, choice questions only). The row carries metadata; the bytes
4+//! live on disk under [`crate::config::Config::files_path`] in a file named by
5+//! `file` — a fresh server-generated ULID per upload, so no user input ever
6+//! shapes a disk path and a replace never overwrites bytes in place. The row
7+//! id is *deterministic* per (question, slot), so "one image per slot" holds
8+//! by construction and a replace is a plain UPSERT. The web layer owns the
9+//! blob I/O and its ordering (new blob before row, row before old blob);
10+//! this module owns the rows.
11+
12+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
13+use ulid::Ulid;
14+
15+use crate::database::{Database, QUESTION_IMAGE_TABLE};
16+use crate::domain::course::CourseId;
17+use crate::domain::exam::ExamId;
18+use crate::domain::exam_question::ExamQuestionId;
19+use crate::domain::note_file::FileContentType;
20+use crate::error::AppError;
21+
22+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
23+pub struct QuestionImageId(RecordId);
24+
25+impl QuestionImageId {
26+ /// The one id a (question, slot) pair can have: `{qid}_q` for the
27+ /// question's own image, `{qid}_{i}` for choice `i` — uniqueness per slot
28+ /// needs no index this way.
29+ pub fn for_slot(question: &ExamQuestionId, slot: Option<i64>) -> Self {
30+ let suffix = match slot {
31+ None => "q".to_string(),
32+ Some(index) => index.to_string(),
33+ };
34+ Self(RecordId::new(
35+ QUESTION_IMAGE_TABLE,
36+ format!("{}_{suffix}", question.key()),
37+ ))
38+ }
39+
40+ pub fn record(&self) -> RecordId {
41+ self.0.clone()
42+ }
43+
44+ pub fn key(&self) -> &str {
45+ match &self.0.key {
46+ RecordIdKey::String(key) => key,
47+ _ => "",
48+ }
49+ }
50+}
51+
52+#[derive(Debug, Clone, SurrealValue)]
53+pub struct QuestionImage {
54+ id: QuestionImageId,
55+ exam: ExamId,
56+ question: ExamQuestionId,
57+ /// `NONE` = the question's illustration; `i` = the picture of choice `i`.
58+ slot: Option<i64>,
59+ /// The blob's on-disk name — a fresh ULID every upload.
60+ file: String,
61+ content_type: FileContentType,
62+ size: i64,
63+}
64+
65+impl QuestionImage {
66+ /// Assemble a row (fresh blob name generated here) without persisting it.
67+ /// The caller writes the blob under [`Self::get_file`] first, then calls
68+ /// [`Self::upsert`] — so a stored row always points at a real blob.
69+ pub fn new(
70+ exam: &ExamId,
71+ question: &ExamQuestionId,
72+ slot: Option<i64>,
73+ content_type: FileContentType,
74+ size: i64,
75+ ) -> Self {
76+ Self {
77+ id: QuestionImageId::for_slot(question, slot),
78+ exam: exam.clone(),
79+ question: question.clone(),
80+ slot,
81+ file: Ulid::new().to_string(),
82+ content_type,
83+ size,
84+ }
85+ }
86+
87+ pub fn get_question(&self) -> &ExamQuestionId {
88+ &self.question
89+ }
90+
91+ pub fn get_slot(&self) -> Option<i64> {
92+ self.slot
93+ }
94+
95+ pub fn get_file(&self) -> &str {
96+ &self.file
97+ }
98+
99+ pub fn get_content_type(&self) -> &FileContentType {
100+ &self.content_type
101+ }
102+
103+ pub fn get_size(&self) -> i64 {
104+ self.size
105+ }
106+
107+ /// Create or replace the slot's image row — the deterministic id makes
108+ /// this the whole "one image per slot" story.
109+ pub async fn upsert(self, db: &Database) -> Result<QuestionImage, AppError> {
110+ let written: Option<QuestionImage> = db.upsert(self.id.record()).content(self).await?;
111+ written.ok_or_else(|| AppError::Internal("failed to store question image".into()))
112+ }
113+
114+ pub async fn read_slot(
115+ question: &ExamQuestionId,
116+ slot: Option<i64>,
117+ db: &Database,
118+ ) -> Result<Option<QuestionImage>, AppError> {
119+ Ok(db
120+ .select(QuestionImageId::for_slot(question, slot).record())
121+ .await?)
122+ }
123+
124+ /// Every image of the exam's questions — one query for the list views.
125+ pub async fn list_for_exam(
126+ exam: &ExamId,
127+ db: &Database,
128+ ) -> Result<Vec<QuestionImage>, AppError> {
129+ let mut result = db
130+ .query("SELECT * FROM question_image WHERE exam = $ex")
131+ .bind(("ex", exam.record()))
132+ .await?
133+ .check()?;
134+ Ok(result.take::<Vec<QuestionImage>>(0)?)
135+ }
136+
137+ pub async fn list_for_question(
138+ question: &ExamQuestionId,
139+ db: &Database,
140+ ) -> Result<Vec<QuestionImage>, AppError> {
141+ let mut result = db
142+ .query("SELECT * FROM question_image WHERE question = $q")
143+ .bind(("q", question.record()))
144+ .await?
145+ .check()?;
146+ Ok(result.take::<Vec<QuestionImage>>(0)?)
147+ }
148+
149+ /// Drop every *choice* image of the question (the question's own
150+ /// illustration stays), returning the removed rows so the caller can take
151+ /// their blobs off disk. Runs when a PATCH replaces the choice list — the
152+ /// old pictures belong to the old options.
153+ pub async fn delete_choices_for(
154+ question: &ExamQuestionId,
155+ db: &Database,
156+ ) -> Result<Vec<QuestionImage>, AppError> {
157+ let mut result = db
158+ .query("DELETE question_image WHERE question = $q AND slot != NONE RETURN BEFORE")
159+ .bind(("q", question.record()))
160+ .await?
161+ .check()?;
162+ Ok(result.take::<Vec<QuestionImage>>(0)?)
163+ }
164+
165+ /// The blob names behind every image of every exam of `course` — collected
166+ /// *before* the course-delete cascade wipes the rows.
167+ pub async fn file_keys_for_course(
168+ course: &CourseId,
169+ db: &Database,
170+ ) -> Result<Vec<String>, AppError> {
171+ let mut result = db
172+ .query(
173+ "SELECT VALUE file FROM question_image \
174+ WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course)",
175+ )
176+ .bind(("course", course.record()))
177+ .await?
178+ .check()?;
179+ Ok(result.take::<Vec<String>>(0)?)
180+ }
181+
182+ pub async fn delete(self, db: &Database) -> Result<QuestionImage, AppError> {
183+ let deleted: Option<QuestionImage> = db.delete(self.id.record()).await?;
184+ deleted.ok_or(AppError::NotFound)
185+ }
186+}
187+
188+#[cfg(test)]
189+mod tests {
190+ use super::*;
191+
192+ fn png() -> FileContentType {
193+ FileContentType::try_new("image/png").unwrap()
194+ }
195+
196+ #[tokio::test]
197+ async fn upsert_replaces_per_slot() {
198+ let db = crate::database::init_mem().await.unwrap();
199+ let exam = ExamId::generate();
200+ let question = ExamQuestionId::generate();
201+
202+ let first = QuestionImage::new(&exam, &question, None, png(), 3)
203+ .upsert(&db)
204+ .await
205+ .unwrap();
206+ let second = QuestionImage::new(&exam, &question, None, png(), 5)
207+ .upsert(&db)
208+ .await
209+ .unwrap();
210+ // Same slot, same row — the replace swapped the blob pointer.
211+ assert_ne!(first.get_file(), second.get_file());
212+ let rows = QuestionImage::list_for_question(&question, &db)
213+ .await
214+ .unwrap();
215+ assert_eq!(rows.len(), 1);
216+ assert_eq!(rows[0].get_size(), 5);
217+
218+ // A choice slot is its own row.
219+ QuestionImage::new(&exam, &question, Some(0), png(), 7)
220+ .upsert(&db)
221+ .await
222+ .unwrap();
223+ assert_eq!(
224+ QuestionImage::list_for_question(&question, &db)
225+ .await
226+ .unwrap()
227+ .len(),
228+ 2
229+ );
230+ let choice = QuestionImage::read_slot(&question, Some(0), &db)
231+ .await
232+ .unwrap()
233+ .unwrap();
234+ assert_eq!(choice.get_slot(), Some(0));
235+ assert!(
236+ QuestionImage::read_slot(&question, Some(1), &db)
237+ .await
238+ .unwrap()
239+ .is_none()
240+ );
241+ }
242+
243+ #[tokio::test]
244+ async fn choice_wipe_spares_the_question_image() {
245+ let db = crate::database::init_mem().await.unwrap();
246+ let exam = ExamId::generate();
247+ let question = ExamQuestionId::generate();
248+ for slot in [None, Some(0), Some(1)] {
249+ QuestionImage::new(&exam, &question, slot, png(), 1)
250+ .upsert(&db)
251+ .await
252+ .unwrap();
253+ }
254+
255+ let dropped = QuestionImage::delete_choices_for(&question, &db)
256+ .await
257+ .unwrap();
258+ assert_eq!(dropped.len(), 2);
259+ assert!(dropped.iter().all(|image| image.get_slot().is_some()));
260+
261+ let left = QuestionImage::list_for_question(&question, &db)
262+ .await
263+ .unwrap();
264+ assert_eq!(left.len(), 1);
265+ assert_eq!(left[0].get_slot(), None);
266+ }
267+
268+ #[tokio::test]
269+ async fn exam_listing_scopes_by_exam() {
270+ let db = crate::database::init_mem().await.unwrap();
271+ let exam_a = ExamId::generate();
272+ let exam_b = ExamId::generate();
273+ QuestionImage::new(&exam_a, &ExamQuestionId::generate(), None, png(), 1)
274+ .upsert(&db)
275+ .await
276+ .unwrap();
277+ assert_eq!(
278+ QuestionImage::list_for_exam(&exam_a, &db)
279+ .await
280+ .unwrap()
281+ .len(),
282+ 1
283+ );
284+ assert!(
285+ QuestionImage::list_for_exam(&exam_b, &db)
286+ .await
287+ .unwrap()
288+ .is_empty()
289+ );
290+ }
291+}
src/domain/user.rsmodified+5 -1
@@ -470,7 +470,11 @@ mod tests {
470 Role::Teacher,470 Role::Teacher,
471 "the role change must survive the racing profile write"471 "the role change must survive the racing profile write"
472 );472 );
473- assert_eq!(after.get_name(), Some(&name), "the profile edit itself lands");473+ assert_eq!(
474+ after.get_name(),
475+ Some(&name),
476+ "the profile edit itself lands"
477+ );
474 }478 }
475 479
476 #[tokio::test]480 #[tokio::test]
src/lib.rsmodified+3 -3
@@ -32,7 +32,7 @@ use crate::state::AppState;
32 info(32 info(
33 title = "Hezarfen Backend API",33 title = "Hezarfen Backend API",
34 version = env!("CARGO_PKG_VERSION"),34 version = env!("CARGO_PKG_VERSION"),
35- description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in two behaviorally identical kinds — `course` (a regular class) and `study` (a supervised study session — etüt) — and carry lesson sessions with teacher-taken roll call; each course also owns its curriculum as a list of subjects, and every exam question must be tagged with one of its course's subjects (a subject still referenced by questions cannot be deleted); staff clock in/out on a server-stamped work log; attendance reports tally events and per-course roll call with rates. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`) and language (`tr`/`en`) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count.",35+ description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images — an illustration on any question, and per-option pictures on choice questions. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in two behaviorally identical kinds — `course` (a regular class) and `study` (a supervised study session — etüt) — and carry lesson sessions with teacher-taken roll call; each course also owns its curriculum as a list of subjects, and every exam question must be tagged with one of its course's subjects (a subject still referenced by questions cannot be deleted); staff clock in/out on a server-stamped work log; attendance reports tally events and per-course roll call with rates. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`) and language (`tr`/`en`) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count.",
36 ),36 ),
37 modifiers(&SecurityAddon),37 modifiers(&SecurityAddon),
38 tags(38 tags(
@@ -45,9 +45,9 @@ use crate::state::AppState;
45 (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"),45 (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"),
46 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),46 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),
47 (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"),47 (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"),
48- (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). A modeless exam is an offline-graded draft — attempts on it are a 409. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"),48+ (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. A modeless exam is an offline-graded draft — attempts on it are a 409. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"),
49 (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings)"),49 (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings)"),
50- (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file note-upload size limit (`max_file_bytes`). Read: any authenticated user; edit: manager+"),50+ (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). Read: any authenticated user; edit: manager+"),
51 (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (enrolled users, creator, manager+); edit follows course management rights"),51 (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (enrolled users, creator, manager+); edit follows course management rights"),
52 (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses may link to one. Read: any authenticated user; edit: manager+"),52 (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses may link to one. Read: any authenticated user; edit: manager+"),
53 ),53 ),
src/web/courses.rsmodified+11 -3
@@ -16,6 +16,7 @@ use crate::domain::exam::{
16 Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule,16 Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule,
17 ExamTitle,17 ExamTitle,
18 };18 };
19+use crate::domain::question_image::QuestionImage;
19 use crate::domain::role::Role;20 use crate::domain::role::Role;
20 use crate::domain::settings::Settings;21 use crate::domain::settings::Settings;
21 use crate::domain::subject::{Subject, SubjectDescription, SubjectName};22 use crate::domain::subject::{Subject, SubjectDescription, SubjectName};
@@ -29,7 +30,7 @@ use super::terms::resolve_term;
29 use super::{30 use super::{
30 CourseResponse, CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher,31 CourseResponse, CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher,
31 SessionResponse, SubjectResponse, check_not_past, check_time_range, paginate, person_map,32 SessionResponse, SubjectResponse, check_not_past, check_time_range, paginate, person_map,
32- set_or_clear,33+ remove_blob, set_or_clear,
33 };34 };
34 35
35 pub fn routes() -> OpenApiRouter<AppState> {36 pub fn routes() -> OpenApiRouter<AppState> {
@@ -362,8 +363,9 @@ async fn update_course(
362 }363 }
363 364
364 /// Delete a course. Requires teacher+; the creator may delete their own course365 /// Delete a course. Requires teacher+; the creator may delete their own course
365-/// and managers/admins may delete anyone's. Cascades the course's exams, their366+/// and managers/admins may delete anyone's. Cascades the course's exams (with
366-/// results, and all enrollments.367+/// their results, questions, answers, and question images), its sessions and
368+/// roll call, its subjects, and all enrollments.
367 #[utoipa::path(369 #[utoipa::path(
368 delete,370 delete,
369 path = "/{id}",371 path = "/{id}",
@@ -390,7 +392,13 @@ async fn delete_course(
390 "only the course creator or a manager/admin can delete this course",392 "only the course creator or a manager/admin can delete this course",
391 ));393 ));
392 }394 }
395+ // Rows go first (the delete cascades them), blobs after — a crash in
396+ // between strands at worst an unreachable blob.
397+ let image_files = QuestionImage::file_keys_for_course(course.get_id(), &st.db).await?;
393 course.delete(&st.db).await?;398 course.delete(&st.db).await?;
399+ for file in &image_files {
400+ remove_blob(&st.files_path, file).await;
401+ }
394 Ok(StatusCode::NO_CONTENT)402 Ok(StatusCode::NO_CONTENT)
395 }403 }
396 404
src/web/exams.rsmodified+535 -23
@@ -2,9 +2,11 @@ use std::collections::HashMap;
2 use std::time::Duration;2 use std::time::Duration;
3 3
4 use axum::Json;4 use axum::Json;
5-use axum::extract::{Path, Query, State};5+use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State};
6-use axum::http::StatusCode;6+use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS};
7+use axum::http::{HeaderValue, StatusCode};
7 use axum::response::sse::{Event, KeepAlive, Sse};8 use axum::response::sse::{Event, KeepAlive, Sse};
9+use axum::response::{IntoResponse, Response};
8 use serde::{Deserialize, Serialize};10 use serde::{Deserialize, Serialize};
9 use tokio_stream::wrappers::IntervalStream;11 use tokio_stream::wrappers::IntervalStream;
10 use tokio_stream::{Stream, StreamExt};12 use tokio_stream::{Stream, StreamExt};
@@ -12,7 +14,10 @@ use utoipa::ToSchema;
12 use utoipa_axum::router::OpenApiRouter;14 use utoipa_axum::router::OpenApiRouter;
13 use utoipa_axum::routes;15 use utoipa_axum::routes;
14 16
15-use crate::constant::EXAM_LIVE_STREAM_INTERVAL_SECS;17+use crate::constant::{
18+ EXAM_LIVE_STREAM_INTERVAL_SECS, MAX_MAX_FILE_BYTES, QUESTION_IMAGE_CONTENT_TYPES,
19+ UPLOAD_BODY_OVERHEAD_BYTES,
20+};
16 use crate::database::Database;21 use crate::database::Database;
17 use crate::domain::course::Course;22 use crate::domain::course::Course;
18 use crate::domain::enrollment::Enrollment;23 use crate::domain::enrollment::Enrollment;
@@ -26,6 +31,8 @@ use crate::domain::exam_question::{
26 ExamQuestion, ExamQuestionId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,31 ExamQuestion, ExamQuestionId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
27 };32 };
28 use crate::domain::exam_result::{ExamResult, Mark};33 use crate::domain::exam_result::{ExamResult, Mark};
34+use crate::domain::note_file::FileContentType;
35+use crate::domain::question_image::QuestionImage;
29 use crate::domain::role::Role;36 use crate::domain::role::Role;
30 use crate::domain::settings::Settings;37 use crate::domain::settings::Settings;
31 use crate::domain::timestamp::Timestamp;38 use crate::domain::timestamp::Timestamp;
@@ -36,8 +43,8 @@ use crate::state::AppState;
36 use super::courses::{can_manage_course, can_view_course, visible_courses};43 use super::courses::{can_manage_course, can_view_course, visible_courses};
37 use super::subjects::subject_in_course;44 use super::subjects::subject_in_course;
38 use super::{45 use super::{
39- CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, check_not_past,46+ CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, UploadFileForm,
40- paginate, person_map, set_or_clear,47+ blob_path, check_not_past, paginate, person_map, read_upload, remove_blob, set_or_clear,
41 };48 };
42 49
43 /// Serializes the exam subsystem's cross-record check-then-writes, which50 /// Serializes the exam subsystem's cross-record check-then-writes, which
@@ -77,6 +84,24 @@ pub fn routes() -> OpenApiRouter<AppState> {
77 .routes(routes!(attempt_questions))84 .routes(routes!(attempt_questions))
78 .routes(routes!(save_answer))85 .routes(routes!(save_answer))
79 .routes(routes!(attempt_answers))86 .routes(routes!(attempt_answers))
87+ // The image routes get their own HTTP body cap, like the note-file
88+ // ones: the server-wide hard ceiling plus multipart framing headroom.
89+ .merge(
90+ OpenApiRouter::new()
91+ .routes(routes!(
92+ upload_question_image,
93+ get_question_image,
94+ delete_question_image
95+ ))
96+ .routes(routes!(
97+ upload_choice_image,
98+ get_choice_image,
99+ delete_choice_image
100+ ))
101+ .layer(DefaultBodyLimit::max(
102+ MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES,
103+ )),
104+ )
80 }105 }
81 106
82 #[derive(Deserialize, ToSchema)]107 #[derive(Deserialize, ToSchema)]
@@ -368,8 +393,8 @@ async fn update_exam(
368 }393 }
369 394
370 /// Delete an exam. Requires teacher+ and management rights over the exam's395 /// Delete an exam. Requires teacher+ and management rights over the exam's
371-/// course (its creator, or manager/admin). Cascades the exam's result and396+/// course (its creator, or manager/admin). Cascades the exam's results,
372-/// attempt rows.397+/// attempts, questions, answers, and question images (blobs included).
373 #[utoipa::path(398 #[utoipa::path(
374 delete,399 delete,
375 path = "/{id}",400 path = "/{id}",
@@ -397,7 +422,13 @@ async fn delete_exam(
397 "only the course creator or a manager/admin can delete this exam",422 "only the course creator or a manager/admin can delete this exam",
398 ));423 ));
399 }424 }
425+ // Rows go first (the delete cascades them), blobs after — a crash in
426+ // between strands at worst an unreachable blob.
427+ let images = QuestionImage::list_for_exam(exam.get_id(), &st.db).await?;
400 exam.delete(&st.db).await?;428 exam.delete(&st.db).await?;
429+ for image in &images {
430+ remove_blob(&st.files_path, image.get_file()).await;
431+ }
401 Ok(StatusCode::NO_CONTENT)432 Ok(StatusCode::NO_CONTENT)
402 }433 }
403 434
@@ -1260,7 +1291,8 @@ struct UpdateQuestion {
1260 /// when moving to `text`.1291 /// when moving to `text`.
1261 kind: Option<String>,1292 kind: Option<String>,
1262 /// Omit to keep the stored options; send `null` to drop them (text1293 /// Omit to keep the stored options; send `null` to drop them (text
1263- /// questions only).1294+ /// questions only). Replacing or clearing the list also drops every
1295+ /// option picture — the old images belong to the old options.
1264 #[serde(default, deserialize_with = "set_or_clear")]1296 #[serde(default, deserialize_with = "set_or_clear")]
1265 #[schema(value_type = Option<Vec<String>>)]1297 #[schema(value_type = Option<Vec<String>>)]
1266 choices: Option<Option<Vec<String>>>,1298 choices: Option<Option<Vec<String>>>,
@@ -1270,6 +1302,64 @@ struct UpdateQuestion {
1270 correct: Option<Option<i64>>,1302 correct: Option<Option<i64>>,
1271 }1303 }
1272 1304
1305+/// A stored question image's metadata; the bytes come from the image
1306+/// endpoints (`GET .../image`, `GET .../choices/{index}/image`).
1307+#[derive(Serialize, ToSchema)]
1308+struct ImageMetaResponse {
1309+ /// MIME type as declared on upload (always one of the raster allowlist).
1310+ #[schema(example = "image/png")]
1311+ content_type: String,
1312+ /// Image size in bytes.
1313+ #[schema(example = 24_576)]
1314+ size: i64,
1315+}
1316+
1317+impl ImageMetaResponse {
1318+ fn new(image: &QuestionImage) -> Self {
1319+ Self {
1320+ content_type: image.get_content_type().as_str().to_string(),
1321+ size: image.get_size(),
1322+ }
1323+ }
1324+}
1325+
1326+/// The question's slot out of its image rows.
1327+fn image_meta(images: &[QuestionImage], slot: Option<i64>) -> Option<ImageMetaResponse> {
1328+ images
1329+ .iter()
1330+ .find(|image| image.get_slot() == slot)
1331+ .map(ImageMetaResponse::new)
1332+}
1333+
1334+/// The per-choice metas, aligned index-for-index with `choices` (`None`
1335+/// entries = that option has no picture); `None` whole for text questions.
1336+fn choice_image_metas(
1337+ question: &ExamQuestion,
1338+ images: &[QuestionImage],
1339+) -> Option<Vec<Option<ImageMetaResponse>>> {
1340+ question.get_choices().map(|choices| {
1341+ (0..choices.len() as i64)
1342+ .map(|index| image_meta(images, Some(index)))
1343+ .collect()
1344+ })
1345+}
1346+
1347+/// `exam`'s image rows bucketed by question key — one query feeding a whole
1348+/// question list.
1349+async fn images_by_question(
1350+ exam: &ExamId,
1351+ db: &Database,
1352+) -> Result<HashMap<String, Vec<QuestionImage>>, AppError> {
1353+ let mut buckets: HashMap<String, Vec<QuestionImage>> = HashMap::new();
1354+ for image in QuestionImage::list_for_exam(exam, db).await? {
1355+ buckets
1356+ .entry(image.get_question().key().to_string())
1357+ .or_default()
1358+ .push(image);
1359+ }
1360+ Ok(buckets)
1361+}
1362+
1273 /// A question as its author sees it — including the `correct` index. Never1363 /// A question as its author sees it — including the `correct` index. Never
1274 /// serialized to students; they get [`AttemptQuestionResponse`].1364 /// serialized to students; they get [`AttemptQuestionResponse`].
1275 #[derive(Serialize, ToSchema)]1365 #[derive(Serialize, ToSchema)]
@@ -1286,10 +1376,14 @@ struct QuestionResponse {
1286 choices: Option<Vec<String>>,1376 choices: Option<Vec<String>>,
1287 /// Zero-based index of the right option (`choice` questions only).1377 /// Zero-based index of the right option (`choice` questions only).
1288 correct: Option<i64>,1378 correct: Option<i64>,
1379+ /// The question's illustration, if one was uploaded (any kind).
1380+ image: Option<ImageMetaResponse>,
1381+ /// Per-option pictures, aligned with `choices` (`choice` questions only).
1382+ choice_images: Option<Vec<Option<ImageMetaResponse>>>,
1289 }1383 }
1290 1384
1291 impl QuestionResponse {1385 impl QuestionResponse {
1292- fn new(question: &ExamQuestion) -> Self {1386+ fn new(question: &ExamQuestion, images: &[QuestionImage]) -> Self {
1293 Self {1387 Self {
1294 id: question.get_id().key().to_string(),1388 id: question.get_id().key().to_string(),
1295 exam: question.get_exam().key().to_string(),1389 exam: question.get_exam().key().to_string(),
@@ -1301,6 +1395,8 @@ impl QuestionResponse {
1301 .get_choices()1395 .get_choices()
1302 .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()),1396 .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()),
1303 correct: question.get_correct(),1397 correct: question.get_correct(),
1398+ image: image_meta(images, None),
1399+ choice_images: choice_image_metas(question, images),
1304 }1400 }
1305 }1401 }
1306 }1402 }
@@ -1379,7 +1475,11 @@ async fn create_question(
1379 let points = QuestionPoints::try_new(req.points)?;1475 let points = QuestionPoints::try_new(req.points)?;
1380 let spec = QuestionSpec::try_new(QuestionKind::try_new(&req.kind)?, req.choices, req.correct)?;1476 let spec = QuestionSpec::try_new(QuestionKind::try_new(&req.kind)?, req.choices, req.correct)?;
1381 let question = ExamQuestion::create(exam.get_id(), subject, text, points, spec, &st.db).await?;1477 let question = ExamQuestion::create(exam.get_id(), subject, text, points, spec, &st.db).await?;
1382- Ok((StatusCode::CREATED, Json(QuestionResponse::new(&question))))1478+ // A question is born imageless — uploads come after, against its id.
1479+ Ok((
1480+ StatusCode::CREATED,
1481+ Json(QuestionResponse::new(&question, &[])),
1482+ ))
1383 }1483 }
1384 1484
1385 /// The exam's question list, `correct` indexes included — the answer key,1485 /// The exam's question list, `correct` indexes included — the answer key,
@@ -1418,10 +1518,18 @@ async fn list_questions(
1418 ));1518 ));
1419 }1519 }
1420 let questions = ExamQuestion::list_for_exam(exam.get_id(), &st.db).await?;1520 let questions = ExamQuestion::list_for_exam(exam.get_id(), &st.db).await?;
1521+ let images = images_by_question(exam.get_id(), &st.db).await?;
1421 let total = questions.len() as i64;1522 let total = questions.len() as i64;
1422 let items = paginate(&questions, limit, offset)1523 let items = paginate(&questions, limit, offset)
1423 .iter()1524 .iter()
1424- .map(QuestionResponse::new)1525+ .map(|question| {
1526+ QuestionResponse::new(
1527+ question,
1528+ images
1529+ .get(question.get_id().key())
1530+ .map_or(&[][..], Vec::as_slice),
1531+ )
1532+ })
1425 .collect();1533 .collect();
1426 Ok(Json(Page::new(items, total, limit, offset)))1534 Ok(Json(Page::new(items, total, limit, offset)))
1427 }1535 }
@@ -1489,6 +1597,7 @@ async fn update_question(
1489 Some(ref kind) => QuestionKind::try_new(kind)?,1597 Some(ref kind) => QuestionKind::try_new(kind)?,
1490 None => question.get_kind().clone(),1598 None => question.get_kind().clone(),
1491 };1599 };
1600+ let choices_replaced = req.choices.is_some();
1492 let choices = match req.choices {1601 let choices = match req.choices {
1493 Some(update) => update,1602 Some(update) => update,
1494 None => question1603 None => question
@@ -1502,7 +1611,16 @@ async fn update_question(
1502 let spec = QuestionSpec::try_new(kind, choices, correct)?;1611 let spec = QuestionSpec::try_new(kind, choices, correct)?;
1503 1612
1504 let updated = question.update(subject, text, points, spec, &st.db).await?;1613 let updated = question.update(subject, text, points, spec, &st.db).await?;
1505- Ok(Json(QuestionResponse::new(&updated)))1614+ // A replaced (or cleared) choice list orphans the old options' pictures —
1615+ // drop them all; the question's own illustration stays. Uploads re-attach
1616+ // against the new list.
1617+ if choices_replaced {
1618+ for image in QuestionImage::delete_choices_for(updated.get_id(), &st.db).await? {
1619+ remove_blob(&st.files_path, image.get_file()).await;
1620+ }
1621+ }
1622+ let images = QuestionImage::list_for_question(updated.get_id(), &st.db).await?;
1623+ Ok(Json(QuestionResponse::new(&updated, &images)))
1506 }1624 }
1507 1625
1508 /// Remove a question (and every answer to it). Requires teacher+ and1626 /// Remove a question (and every answer to it). Requires teacher+ and
@@ -1544,7 +1662,387 @@ async fn delete_question(
1544 let _guard = EXAM_LOCK.write().await;1662 let _guard = EXAM_LOCK.write().await;
1545 ensure_questions_editable(exam.get_id(), &st.db).await?;1663 ensure_questions_editable(exam.get_id(), &st.db).await?;
1546 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;1664 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
1665+ // Rows go first (the delete cascades them), blobs after — a crash in
1666+ // between strands at worst an unreachable blob.
1667+ let images = QuestionImage::list_for_question(question.get_id(), &st.db).await?;
1547 question.delete(&st.db).await?;1668 question.delete(&st.db).await?;
1669+ for image in &images {
1670+ remove_blob(&st.files_path, image.get_file()).await;
1671+ }
1672+ Ok(StatusCode::NO_CONTENT)
1673+}
1674+
1675+// ---- question images ----------------------------------------------------------
1676+// A question may carry one illustration (any kind — the map above the prompt)
1677+// and, on choice questions, one picture per option (pick the right city off
1678+// the map). Uploads are teacher authoring and freeze with the rest of the
1679+// question once attempts exist; metadata rides on the question DTOs, bytes
1680+// flow through the GET endpoints below, whose access follows the question's
1681+// own visibility (author side and sitting side alike).
1682+
1683+/// The exam, provided the caller may author its questions — the shared front
1684+/// half of every image write.
1685+async fn image_managed_exam(st: &AppState, user: &User, id: &str) -> Result<Exam, AppError> {
1686+ let exam = Exam::read(&ExamId::from_key(id), &st.db)
1687+ .await?
1688+ .ok_or(AppError::NotFound)?;
1689+ let course = course_of(&exam, &st.db).await?;
1690+ if !can_manage_course(&course, user) {
1691+ return Err(AppError::Forbidden(
1692+ "only the course creator or a manager/admin can manage question images",
1693+ ));
1694+ }
1695+ Ok(exam)
1696+}
1697+
1698+/// A 403/404 unless the caller may see the exam's question content: course
1699+/// managers always, students through the same wall as
1700+/// `GET /exams/{id}/attempt/questions` — enrollment plus a started attempt,
1701+/// so there is no early peek at the pictures either.
1702+async fn ensure_question_content_visible(
1703+ st: &AppState,
1704+ exam: &Exam,
1705+ user: &User,
1706+) -> Result<(), AppError> {
1707+ let course = course_of(exam, &st.db).await?;
1708+ if can_manage_course(&course, user) {
1709+ return Ok(());
1710+ }
1711+ ensure_enrolled(exam, user.get_id(), &st.db).await?;
1712+ ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db)
1713+ .await?
1714+ .ok_or(AppError::NotFound)?;
1715+ Ok(())
1716+}
1717+
1718+/// The declared content type, held to the raster allowlist — SVG stays out
1719+/// (it can script) since these bytes are rendered inline to whole classes.
1720+fn image_content_type(raw: &str) -> Result<FileContentType, AppError> {
1721+ let content_type = FileContentType::try_new(raw)?;
1722+ if !QUESTION_IMAGE_CONTENT_TYPES.contains(&content_type.as_str()) {
1723+ return Err(AppError::Validation(ValidationError::Invalid {
1724+ field: "content_type",
1725+ reason: "must be image/png, image/jpeg, image/webp, or image/gif",
1726+ }));
1727+ }
1728+ Ok(content_type)
1729+}
1730+
1731+/// The whole image write tail, shared by both upload endpoints: new blob to
1732+/// disk, row UPSERT (the deterministic per-slot id makes it a replace), then
1733+/// the replaced blob off disk. A failed row write takes the fresh blob back
1734+/// out; a stored row always points at a real blob.
1735+async fn store_image(
1736+ st: &AppState,
1737+ exam: &Exam,
1738+ question: &ExamQuestion,
1739+ slot: Option<i64>,
1740+ content_type: FileContentType,
1741+ data: &[u8],
1742+) -> Result<QuestionImage, AppError> {
1743+ let replaced = QuestionImage::read_slot(question.get_id(), slot, &st.db).await?;
1744+ let image = QuestionImage::new(
1745+ exam.get_id(),
1746+ question.get_id(),
1747+ slot,
1748+ content_type,
1749+ data.len() as i64,
1750+ );
1751+ let path = blob_path(&st.files_path, image.get_file());
1752+ tokio::fs::write(&path, data)
1753+ .await
1754+ .map_err(|err| AppError::Internal(format!("failed to store the image blob: {err}")))?;
1755+ match image.upsert(&st.db).await {
1756+ Ok(stored) => {
1757+ if let Some(replaced) = replaced {
1758+ remove_blob(&st.files_path, replaced.get_file()).await;
1759+ }
1760+ Ok(stored)
1761+ }
1762+ Err(err) => {
1763+ let _ = tokio::fs::remove_file(&path).await;
1764+ Err(err)
1765+ }
1766+ }
1767+}
1768+
1769+/// The stored bytes as an inline-displayable response: the declared (and
1770+/// allowlisted) content type, `nosniff`, and `no-store` — exam content has no
1771+/// business in shared caches, and a replaced image must not linger.
1772+async fn serve_image(st: &AppState, image: &QuestionImage) -> Result<Response, AppError> {
1773+ let bytes = tokio::fs::read(blob_path(&st.files_path, image.get_file()))
1774+ .await
1775+ .map_err(|err| {
1776+ // The row exists but its blob doesn't — server-side damage (a
1777+ // lost volume path), not a client 404.
1778+ AppError::Internal(format!(
1779+ "missing blob for question image {}: {err}",
1780+ image.get_file()
1781+ ))
1782+ })?;
1783+ let content_type = HeaderValue::from_str(image.get_content_type().as_str())
1784+ .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"));
1785+ Ok((
1786+ [
1787+ (CONTENT_TYPE, content_type),
1788+ (X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")),
1789+ (CACHE_CONTROL, HeaderValue::from_static("private, no-store")),
1790+ ],
1791+ bytes,
1792+ )
1793+ .into_response())
1794+}
1795+
1796+/// Attach (or replace) a question's illustration — any question kind may
1797+/// carry one, e.g. the map the prompt asks about. `multipart/form-data` with
1798+/// the image under a `file` field; the declared content type must be
1799+/// `image/png`, `image/jpeg`, `image/webp`, or `image/gif` (rasters only —
1800+/// no SVG), the bytes at most the school's `max_file_bytes` (settings).
1801+/// Requires teacher+ and management rights over the exam's course; frozen
1802+/// once attempts exist, like every other question edit.
1803+#[utoipa::path(
1804+ post,
1805+ path = "/{id}/questions/{qid}/image",
1806+ tag = "exams",
1807+ security(("session_cookie" = [])),
1808+ params(
1809+ ("id" = String, Path, description = "Exam id"),
1810+ ("qid" = String, Path, description = "Question id"),
1811+ ),
1812+ request_body(content = UploadFileForm, content_type = "multipart/form-data"),
1813+ responses(
1814+ (status = 201, description = "Image stored", body = ImageMetaResponse),
1815+ (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse),
1816+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1817+ (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
1818+ (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse),
1819+ (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
1820+ (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse),
1821+ ),
1822+)]
1823+async fn upload_question_image(
1824+ State(st): State<AppState>,
1825+ RequireTeacher(user): RequireTeacher,
1826+ Path((id, qid)): Path<(String, String)>,
1827+ mut multipart: Multipart,
1828+) -> Result<(StatusCode, Json<ImageMetaResponse>), AppError> {
1829+ let exam = image_managed_exam(&st, &user, &id).await?;
1830+ let limit = Settings::load(&st.db).await?.get_max_file_bytes();
1831+ // The body is consumed before the lock — a client's slow upload must not
1832+ // stall the exam subsystem.
1833+ let upload = read_upload(&mut multipart, limit).await?;
1834+ let content_type = image_content_type(&upload.content_type.unwrap_or_default())?;
1835+ // Writer lease of [`EXAM_LOCK`]: freeze gate + write are one unit, like
1836+ // every other question edit — see `create_question`.
1837+ let _guard = EXAM_LOCK.write().await;
1838+ ensure_questions_editable(exam.get_id(), &st.db).await?;
1839+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
1840+ let stored = store_image(&st, &exam, &question, None, content_type, &upload.data).await?;
1841+ Ok((StatusCode::CREATED, Json(ImageMetaResponse::new(&stored))))
1842+}
1843+
1844+/// The question's illustration bytes. Course managers read anytime; students
1845+/// through the same wall as the sitting view — enrollment plus a started
1846+/// attempt (404 before that, like the question list itself).
1847+#[utoipa::path(
1848+ get,
1849+ path = "/{id}/questions/{qid}/image",
1850+ tag = "exams",
1851+ security(("session_cookie" = [])),
1852+ params(
1853+ ("id" = String, Path, description = "Exam id"),
1854+ ("qid" = String, Path, description = "Question id"),
1855+ ),
1856+ responses(
1857+ (status = 200, description = "The image bytes", content_type = "image/*"),
1858+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1859+ (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse),
1860+ (status = 404, description = "No such exam, question, or image — or no attempt yet", body = ErrorResponse),
1861+ ),
1862+)]
1863+async fn get_question_image(
1864+ State(st): State<AppState>,
1865+ CurrentUser(user): CurrentUser,
1866+ Path((id, qid)): Path<(String, String)>,
1867+) -> Result<Response, AppError> {
1868+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
1869+ .await?
1870+ .ok_or(AppError::NotFound)?;
1871+ ensure_question_content_visible(&st, &exam, &user).await?;
1872+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
1873+ let image = QuestionImage::read_slot(question.get_id(), None, &st.db)
1874+ .await?
1875+ .ok_or(AppError::NotFound)?;
1876+ serve_image(&st, &image).await
1877+}
1878+
1879+/// Remove a question's illustration. Requires teacher+ and management rights
1880+/// over the exam's course; frozen once attempts exist.
1881+#[utoipa::path(
1882+ delete,
1883+ path = "/{id}/questions/{qid}/image",
1884+ tag = "exams",
1885+ security(("session_cookie" = [])),
1886+ params(
1887+ ("id" = String, Path, description = "Exam id"),
1888+ ("qid" = String, Path, description = "Question id"),
1889+ ),
1890+ responses(
1891+ (status = 204, description = "Deleted"),
1892+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1893+ (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
1894+ (status = 404, description = "No such exam, question, or image", body = ErrorResponse),
1895+ (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
1896+ ),
1897+)]
1898+async fn delete_question_image(
1899+ State(st): State<AppState>,
1900+ RequireTeacher(user): RequireTeacher,
1901+ Path((id, qid)): Path<(String, String)>,
1902+) -> Result<StatusCode, AppError> {
1903+ let exam = image_managed_exam(&st, &user, &id).await?;
1904+ let _guard = EXAM_LOCK.write().await;
1905+ ensure_questions_editable(exam.get_id(), &st.db).await?;
1906+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
1907+ let image = QuestionImage::read_slot(question.get_id(), None, &st.db)
1908+ .await?
1909+ .ok_or(AppError::NotFound)?;
1910+ let image = image.delete(&st.db).await?;
1911+ remove_blob(&st.files_path, image.get_file()).await;
1912+ Ok(StatusCode::NO_CONTENT)
1913+}
1914+
1915+/// Attach (or replace) one option's picture on a `choice` question — so the
1916+/// options themselves can be images (four map crops, pick the right one).
1917+/// Same form, limits, and rights as the question-image upload; `index` is the
1918+/// option's zero-based position. Replacing the question's `choices` list
1919+/// drops all its option pictures — re-upload against the new list.
1920+#[utoipa::path(
1921+ post,
1922+ path = "/{id}/questions/{qid}/choices/{index}/image",
1923+ tag = "exams",
1924+ security(("session_cookie" = [])),
1925+ params(
1926+ ("id" = String, Path, description = "Exam id"),
1927+ ("qid" = String, Path, description = "Question id"),
1928+ ("index" = i64, Path, description = "Zero-based choice index"),
1929+ ),
1930+ request_body(content = UploadFileForm, content_type = "multipart/form-data"),
1931+ responses(
1932+ (status = 201, description = "Image stored", body = ImageMetaResponse),
1933+ (status = 400, description = "Missing file field, empty file, a content type outside the image allowlist, a text question, or an index past the choices", body = ErrorResponse),
1934+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1935+ (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
1936+ (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse),
1937+ (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
1938+ (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse),
1939+ ),
1940+)]
1941+async fn upload_choice_image(
1942+ State(st): State<AppState>,
1943+ RequireTeacher(user): RequireTeacher,
1944+ Path((id, qid, index)): Path<(String, String, i64)>,
1945+ mut multipart: Multipart,
1946+) -> Result<(StatusCode, Json<ImageMetaResponse>), AppError> {
1947+ let exam = image_managed_exam(&st, &user, &id).await?;
1948+ let limit = Settings::load(&st.db).await?.get_max_file_bytes();
1949+ let upload = read_upload(&mut multipart, limit).await?;
1950+ let content_type = image_content_type(&upload.content_type.unwrap_or_default())?;
1951+ let _guard = EXAM_LOCK.write().await;
1952+ ensure_questions_editable(exam.get_id(), &st.db).await?;
1953+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
1954+ let Some(choices) = question.get_choices() else {
1955+ return Err(AppError::Validation(ValidationError::Invalid {
1956+ field: "index",
1957+ reason: "only choice questions take option pictures",
1958+ }));
1959+ };
1960+ if !(0..choices.len() as i64).contains(&index) {
1961+ return Err(AppError::Validation(ValidationError::Invalid {
1962+ field: "index",
1963+ reason: "must index one of the choices",
1964+ }));
1965+ }
1966+ let stored = store_image(
1967+ &st,
1968+ &exam,
1969+ &question,
1970+ Some(index),
1971+ content_type,
1972+ &upload.data,
1973+ )
1974+ .await?;
1975+ Ok((StatusCode::CREATED, Json(ImageMetaResponse::new(&stored))))
1976+}
1977+
1978+/// One option's picture bytes. Same access wall as the question-image read.
1979+#[utoipa::path(
1980+ get,
1981+ path = "/{id}/questions/{qid}/choices/{index}/image",
1982+ tag = "exams",
1983+ security(("session_cookie" = [])),
1984+ params(
1985+ ("id" = String, Path, description = "Exam id"),
1986+ ("qid" = String, Path, description = "Question id"),
1987+ ("index" = i64, Path, description = "Zero-based choice index"),
1988+ ),
1989+ responses(
1990+ (status = 200, description = "The image bytes", content_type = "image/*"),
1991+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1992+ (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse),
1993+ (status = 404, description = "No such exam, question, or image — or no attempt yet", body = ErrorResponse),
1994+ ),
1995+)]
1996+async fn get_choice_image(
1997+ State(st): State<AppState>,
1998+ CurrentUser(user): CurrentUser,
1999+ Path((id, qid, index)): Path<(String, String, i64)>,
2000+) -> Result<Response, AppError> {
2001+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
2002+ .await?
2003+ .ok_or(AppError::NotFound)?;
2004+ ensure_question_content_visible(&st, &exam, &user).await?;
2005+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
2006+ let image = QuestionImage::read_slot(question.get_id(), Some(index), &st.db)
2007+ .await?
2008+ .ok_or(AppError::NotFound)?;
2009+ serve_image(&st, &image).await
2010+}
2011+
2012+/// Remove one option's picture. Requires teacher+ and management rights over
2013+/// the exam's course; frozen once attempts exist.
2014+#[utoipa::path(
2015+ delete,
2016+ path = "/{id}/questions/{qid}/choices/{index}/image",
2017+ tag = "exams",
2018+ security(("session_cookie" = [])),
2019+ params(
2020+ ("id" = String, Path, description = "Exam id"),
2021+ ("qid" = String, Path, description = "Question id"),
2022+ ("index" = i64, Path, description = "Zero-based choice index"),
2023+ ),
2024+ responses(
2025+ (status = 204, description = "Deleted"),
2026+ (status = 401, description = "Not authenticated", body = ErrorResponse),
2027+ (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
2028+ (status = 404, description = "No such exam, question, or image", body = ErrorResponse),
2029+ (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
2030+ ),
2031+)]
2032+async fn delete_choice_image(
2033+ State(st): State<AppState>,
2034+ RequireTeacher(user): RequireTeacher,
2035+ Path((id, qid, index)): Path<(String, String, i64)>,
2036+) -> Result<StatusCode, AppError> {
2037+ let exam = image_managed_exam(&st, &user, &id).await?;
2038+ let _guard = EXAM_LOCK.write().await;
2039+ ensure_questions_editable(exam.get_id(), &st.db).await?;
2040+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
2041+ let image = QuestionImage::read_slot(question.get_id(), Some(index), &st.db)
2042+ .await?
2043+ .ok_or(AppError::NotFound)?;
2044+ let image = image.delete(&st.db).await?;
2045+ remove_blob(&st.files_path, image.get_file()).await;
1548 Ok(StatusCode::NO_CONTENT)2046 Ok(StatusCode::NO_CONTENT)
1549 }2047 }
1550 2048
@@ -1587,6 +2085,12 @@ struct AttemptQuestionResponse {
1587 kind: String,2085 kind: String,
1588 points: i64,2086 points: i64,
1589 choices: Option<Vec<String>>,2087 choices: Option<Vec<String>>,
2088+ /// The question's illustration, if any — bytes at
2089+ /// `GET /exams/{id}/questions/{qid}/image`.
2090+ image: Option<ImageMetaResponse>,
2091+ /// Per-option pictures aligned with `choices`, if any — bytes at
2092+ /// `GET /exams/{id}/questions/{qid}/choices/{index}/image`.
2093+ choice_images: Option<Vec<Option<ImageMetaResponse>>>,
1590 /// The caller's saved answer; `null` while unanswered.2094 /// The caller's saved answer; `null` while unanswered.
1591 answer: Option<AnswerStateResponse>,2095 answer: Option<AnswerStateResponse>,
1592 }2096 }
@@ -1763,6 +2267,7 @@ async fn attempt_questions(
1763 .ok_or(AppError::NotFound)?;2267 .ok_or(AppError::NotFound)?;
1764 2268
1765 let questions = ExamQuestion::list_for_exam(exam.get_id(), &st.db).await?;2269 let questions = ExamQuestion::list_for_exam(exam.get_id(), &st.db).await?;
2270+ let images = images_by_question(exam.get_id(), &st.db).await?;
1766 let answers: HashMap<String, ExamAnswer> =2271 let answers: HashMap<String, ExamAnswer> =
1767 ExamAnswer::list_for_exam_user(exam.get_id(), user.get_id(), &st.db)2272 ExamAnswer::list_for_exam_user(exam.get_id(), user.get_id(), &st.db)
1768 .await?2273 .await?
@@ -1772,18 +2277,25 @@ async fn attempt_questions(
1772 Ok(Json(2277 Ok(Json(
1773 questions2278 questions
1774 .iter()2279 .iter()
1775- .map(|question| AttemptQuestionResponse {2280+ .map(|question| {
1776- id: question.get_id().key().to_string(),2281+ let question_images = images
1777- subject: question.get_subject().key().to_string(),
1778- text: question.get_text().as_str().to_string(),
1779- kind: question.get_kind().as_str().to_string(),
1780- points: question.get_points().as_i64(),
1781- choices: question
1782- .get_choices()
1783- .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()),
1784- answer: answers
1785 .get(question.get_id().key())2282 .get(question.get_id().key())
1786- .map(AnswerStateResponse::new),2283+ .map_or(&[][..], Vec::as_slice);
2284+ AttemptQuestionResponse {
2285+ id: question.get_id().key().to_string(),
2286+ subject: question.get_subject().key().to_string(),
2287+ text: question.get_text().as_str().to_string(),
2288+ kind: question.get_kind().as_str().to_string(),
2289+ points: question.get_points().as_i64(),
2290+ choices: question
2291+ .get_choices()
2292+ .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()),
2293+ image: image_meta(question_images, None),
2294+ choice_images: choice_image_metas(question, question_images),
2295+ answer: answers
2296+ .get(question.get_id().key())
2297+ .map(AnswerStateResponse::new),
2298+ }
1787 })2299 })
1788 .collect(),2300 .collect(),
1789 ))2301 ))
src/web/mod.rsmodified+105 -0
@@ -29,7 +29,13 @@ pub use dto::{
29 pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireTeacher};29 pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireTeacher};
30 pub use page::{Page, PageParams, paginate};30 pub use page::{Page, PageParams, paginate};
31 31
32+use std::path::{Path as FsPath, PathBuf};
33+
34+use axum::extract::Multipart;
35+use axum::extract::multipart::MultipartError;
36+use axum::http::StatusCode;
32 use serde::{Deserialize, Deserializer};37 use serde::{Deserialize, Deserializer};
38+use utoipa::ToSchema;
33 39
34 use crate::constant::SCHEDULE_PAST_GRACE_MS;40 use crate::constant::SCHEDULE_PAST_GRACE_MS;
35 use crate::domain::timestamp::Timestamp;41 use crate::domain::timestamp::Timestamp;
@@ -73,6 +79,105 @@ pub(crate) fn check_not_past(
73 Ok(())79 Ok(())
74 }80 }
75 81
82+// ---- uploaded blobs ---------------------------------------------------------
83+// Note files and question images share one story: bytes on disk under the
84+// configured directory in a file named by a server-generated ULID (user input
85+// never shapes a path), metadata in a row. Upload writes the blob before the
86+// row; delete removes the row before the blob — so a stored row always points
87+// at a real blob and a crash strands at worst an unreachable file.
88+
89+/// Where a stored row's blob lives: one file under the configured directory,
90+/// named by the row's server-generated key.
91+pub(crate) fn blob_path(files_path: &FsPath, key: &str) -> PathBuf {
92+ files_path.join(key)
93+}
94+
95+/// Best-effort blob removal after its row is gone. Failure only strands an
96+/// unreachable file on disk, so it is logged rather than surfaced.
97+pub(crate) async fn remove_blob(files_path: &FsPath, key: &str) {
98+ let path = blob_path(files_path, key);
99+ if let Err(err) = tokio::fs::remove_file(&path).await
100+ && err.kind() != std::io::ErrorKind::NotFound
101+ {
102+ tracing::warn!("failed to remove blob {}: {err}", path.display());
103+ }
104+}
105+
106+/// Multipart read failures: the route-level body cap maps to 413 like the
107+/// school-limit check; anything else is a malformed body.
108+pub(crate) fn multipart_error(err: MultipartError) -> AppError {
109+ if err.status() == StatusCode::PAYLOAD_TOO_LARGE {
110+ AppError::PayloadTooLarge("the upload exceeds the server's absolute body cap".to_string())
111+ } else {
112+ AppError::Validation(ValidationError::Invalid {
113+ field: "file",
114+ reason: "malformed multipart body",
115+ })
116+ }
117+}
118+
119+/// Schema-only mirror of an upload form; the handlers read the multipart
120+/// stream directly.
121+#[derive(ToSchema)]
122+#[allow(dead_code)]
123+pub(crate) struct UploadFileForm {
124+ /// The file part. Its `Content-Type` (and, where required, `filename`)
125+ /// are stored alongside the bytes.
126+ #[schema(value_type = String, format = Binary)]
127+ file: String,
128+}
129+
130+/// One uploaded file's raw parts, as the client sent them — the caller
131+/// validates what it cares about (notes need a filename, images an
132+/// allowlisted content type).
133+pub(crate) struct UploadedFile {
134+ pub name: Option<String>,
135+ pub content_type: Option<String>,
136+ pub data: Vec<u8>,
137+}
138+
139+/// Pull the `file` field out of a multipart body, reading it chunkwise so an
140+/// oversized upload dies at `limit`, not after buffering whole — the check is
141+/// on real bytes received, so a lying `Content-Length` can't sneak past it.
142+/// Empty files are refused; stray extra fields are ignored.
143+pub(crate) async fn read_upload(
144+ multipart: &mut Multipart,
145+ limit: i64,
146+) -> Result<UploadedFile, AppError> {
147+ let mut field = loop {
148+ match multipart.next_field().await.map_err(multipart_error)? {
149+ Some(field) if field.name() == Some("file") => break field,
150+ Some(_) => continue,
151+ None => {
152+ return Err(AppError::Validation(ValidationError::Invalid {
153+ field: "file",
154+ reason: "the multipart body must carry a 'file' field",
155+ }));
156+ }
157+ }
158+ };
159+ let name = field.file_name().map(str::to_string);
160+ let content_type = field.content_type().map(str::to_string);
161+
162+ let mut data = Vec::new();
163+ while let Some(chunk) = field.chunk().await.map_err(multipart_error)? {
164+ if data.len() + chunk.len() > limit as usize {
165+ return Err(AppError::PayloadTooLarge(format!(
166+ "the file exceeds the school's limit of {limit} bytes"
167+ )));
168+ }
169+ data.extend_from_slice(&chunk);
170+ }
171+ if data.is_empty() {
172+ return Err(AppError::Validation(ValidationError::Empty("file")));
173+ }
174+ Ok(UploadedFile {
175+ name,
176+ content_type,
177+ data,
178+ })
179+}
180+
76 /// Distinguishes an *absent* PATCH field from an explicit `null`: absent never181 /// Distinguishes an *absent* PATCH field from an explicit `null`: absent never
77 /// reaches the deserializer and stays `None` via `#[serde(default)]` (keep the182 /// reaches the deserializer and stays `None` via `#[serde(default)]` (keep the
78 /// stored value); `null` or a value lands here as `Some(inner)` (clear or set).183 /// stored value); `null` or a value lands here as `Some(inner)` (clear or set).
src/web/notes.rsmodified+13 -82
@@ -1,7 +1,4 @@
1-use std::path::{Path as FsPath, PathBuf};
2-
3 use axum::Json;1 use axum::Json;
4-use axum::extract::multipart::MultipartError;
5 use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State};2 use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State};
6 use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE};3 use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE};
7 use axum::http::{HeaderValue, StatusCode};4 use axum::http::{HeaderValue, StatusCode};
@@ -15,10 +12,12 @@ use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};
15 use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle};12 use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle};
16 use crate::domain::note_file::{FileContentType, FileName, NoteFile, NoteFileId};13 use crate::domain::note_file::{FileContentType, FileName, NoteFile, NoteFileId};
17 use crate::domain::settings::Settings;14 use crate::domain::settings::Settings;
18-use crate::error::{AppError, ErrorResponse, ValidationError};15+use crate::error::{AppError, ErrorResponse};
19 use crate::state::AppState;16 use crate::state::AppState;
20 17
21-use super::{CurrentUser, Page, PageParams, paginate};18+use super::{
19+ CurrentUser, Page, PageParams, UploadFileForm, blob_path, paginate, read_upload, remove_blob,
20+};
22 21
23 pub fn routes() -> OpenApiRouter<AppState> {22 pub fn routes() -> OpenApiRouter<AppState> {
24 // The file routes get their own HTTP body cap: the server-wide hard23 // The file routes get their own HTTP body cap: the server-wide hard
@@ -211,7 +210,7 @@ async fn delete_one(
211 let files = NoteFile::list_for(note.get_id(), &st.db).await?;210 let files = NoteFile::list_for(note.get_id(), &st.db).await?;
212 note.delete(&st.db).await?;211 note.delete(&st.db).await?;
213 for file in &files {212 for file in &files {
214- remove_blob(&st.files_path, file.get_id()).await;213+ remove_blob(&st.files_path, file.get_id().key()).await;
215 }214 }
216 Ok(StatusCode::NO_CONTENT)215 Ok(StatusCode::NO_CONTENT)
217 }216 }
@@ -243,17 +242,6 @@ impl NoteFileResponse {
243 }242 }
244 }243 }
245 244
246-/// Schema-only mirror of the upload form; the handler reads the multipart
247-/// stream directly.
248-#[derive(ToSchema)]
249-#[allow(dead_code)]
250-struct UploadFileForm {
251- /// The file part. Its `filename` (required) and `Content-Type` are stored
252- /// alongside the bytes.
253- #[schema(value_type = String, format = Binary)]
254- file: String,
255-}
256-
257 /// Attach a file to a note owned by the current user. `multipart/form-data`245 /// Attach a file to a note owned by the current user. `multipart/form-data`
258 /// with the file under a `file` field; its `filename` is required. At most246 /// with the file under a `file` field; its `filename` is required. At most
259 /// 10 files per note; each file at most the school's `max_file_bytes`247 /// 10 files per note; each file at most the school's `max_file_bytes`
@@ -287,42 +275,15 @@ async fn upload_file(
287 // under one lock) — checking it here too would just race.275 // under one lock) — checking it here too would just race.
288 let limit = Settings::load(&st.db).await?.get_max_file_bytes();276 let limit = Settings::load(&st.db).await?.get_max_file_bytes();
289 277
290- let mut field = loop {278+ let upload = read_upload(&mut multipart, limit).await?;
291- match multipart.next_field().await.map_err(multipart_error)? {279+ let name = FileName::try_new(&upload.name.unwrap_or_default())?;
292- Some(field) if field.name() == Some("file") => break field,280+ let content_type = FileContentType::try_new(&upload.content_type.unwrap_or_default())?;
293- Some(_) => continue, // ignore stray extra fields
294- None => {
295- return Err(AppError::Validation(ValidationError::Invalid {
296- field: "file",
297- reason: "the multipart body must carry a 'file' field",
298- }));
299- }
300- }
301- };
302- let name = FileName::try_new(field.file_name().unwrap_or_default())?;
303- let content_type = FileContentType::try_new(field.content_type().unwrap_or_default())?;
304-
305- // Read the part chunkwise so an oversized upload dies at the limit, not
306- // after buffering whole. The check is on real bytes received — a lying
307- // Content-Length can't sneak past it.
308- let mut data = Vec::new();
309- while let Some(chunk) = field.chunk().await.map_err(multipart_error)? {
310- if data.len() + chunk.len() > limit as usize {
311- return Err(AppError::PayloadTooLarge(format!(
312- "the file exceeds the school's limit of {limit} bytes"
313- )));
314- }
315- data.extend_from_slice(&chunk);
316- }
317- if data.is_empty() {
318- return Err(AppError::Validation(ValidationError::Empty("file")));
319- }
320 281
321 // Blob first, row second — a stored row always points at a real blob. If282 // Blob first, row second — a stored row always points at a real blob. If
322 // the row insert fails, take the fresh blob back out.283 // the row insert fails, take the fresh blob back out.
323- let file = NoteFile::new(note.get_id(), name, content_type, data.len() as i64);284+ let file = NoteFile::new(note.get_id(), name, content_type, upload.data.len() as i64);
324- let path = blob_path(&st.files_path, file.get_id());285+ let path = blob_path(&st.files_path, file.get_id().key());
325- tokio::fs::write(&path, &data)286+ tokio::fs::write(&path, &upload.data)
326 .await287 .await
327 .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?;288 .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?;
328 match file.insert(&st.db).await {289 match file.insert(&st.db).await {
@@ -396,7 +357,7 @@ async fn download_file(
396 let file = NoteFile::read_for(&NoteFileId::from_key(&file_id), note.get_id(), &st.db)357 let file = NoteFile::read_for(&NoteFileId::from_key(&file_id), note.get_id(), &st.db)
397 .await?358 .await?
398 .ok_or(AppError::NotFound)?;359 .ok_or(AppError::NotFound)?;
399- let bytes = tokio::fs::read(blob_path(&st.files_path, file.get_id()))360+ let bytes = tokio::fs::read(blob_path(&st.files_path, file.get_id().key()))
400 .await361 .await
401 .map_err(|err| {362 .map_err(|err| {
402 // The row exists but its blob doesn't — that's server-side damage363 // The row exists but its blob doesn't — that's server-side damage
@@ -450,40 +411,10 @@ async fn delete_file(
450 .await?411 .await?
451 .ok_or(AppError::NotFound)?;412 .ok_or(AppError::NotFound)?;
452 let file = file.delete(&st.db).await?;413 let file = file.delete(&st.db).await?;
453- remove_blob(&st.files_path, file.get_id()).await;414+ remove_blob(&st.files_path, file.get_id().key()).await;
454 Ok(StatusCode::NO_CONTENT)415 Ok(StatusCode::NO_CONTENT)
455 }416 }
456 417
457-/// Where a file row's blob lives: one file under the configured directory,
458-/// named by the row's server-generated key — user input never shapes a path.
459-fn blob_path(files_path: &FsPath, id: &NoteFileId) -> PathBuf {
460- files_path.join(id.key())
461-}
462-
463-/// Best-effort blob removal after its row is gone. Failure only strands an
464-/// unreachable file on disk, so it is logged rather than surfaced.
465-async fn remove_blob(files_path: &FsPath, id: &NoteFileId) {
466- let path = blob_path(files_path, id);
467- if let Err(err) = tokio::fs::remove_file(&path).await
468- && err.kind() != std::io::ErrorKind::NotFound
469- {
470- tracing::warn!("failed to remove blob {}: {err}", path.display());
471- }
472-}
473-
474-/// Multipart read failures: the route-level body cap maps to 413 like the
475-/// school-limit check; anything else is a malformed body.
476-fn multipart_error(err: MultipartError) -> AppError {
477- if err.status() == StatusCode::PAYLOAD_TOO_LARGE {
478- AppError::PayloadTooLarge("the upload exceeds the server's absolute body cap".to_string())
479- } else {
480- AppError::Validation(ValidationError::Invalid {
481- field: "file",
482- reason: "malformed multipart body",
483- })
484- }
485-}
486-
487 /// `Content-Disposition` for a download: an ASCII-safe `filename` fallback418 /// `Content-Disposition` for a download: an ASCII-safe `filename` fallback
488 /// plus the RFC 5987 `filename*` form so non-ASCII names (`ödev.pdf`) survive.419 /// plus the RFC 5987 `filename*` form so non-ASCII names (`ödev.pdf`) survive.
489 fn content_disposition(name: &str) -> String {420 fn content_disposition(name: &str) -> String {
tests/integration.rsmodified+364 -0
@@ -209,6 +209,12 @@ async fn protected_routes_require_session() {
209 ("GET", "/exams/x/attempt/questions"),209 ("GET", "/exams/x/attempt/questions"),
210 ("POST", "/exams/x/attempt/answers"),210 ("POST", "/exams/x/attempt/answers"),
211 ("GET", "/exams/x/attempts/u/answers"),211 ("GET", "/exams/x/attempts/u/answers"),
212+ ("POST", "/exams/x/questions/y/image"),
213+ ("GET", "/exams/x/questions/y/image"),
214+ ("DELETE", "/exams/x/questions/y/image"),
215+ ("POST", "/exams/x/questions/y/choices/0/image"),
216+ ("GET", "/exams/x/questions/y/choices/0/image"),
217+ ("DELETE", "/exams/x/questions/y/choices/0/image"),
212 // The WebSocket room authenticates before it upgrades.218 // The WebSocket room authenticates before it upgrades.
213 ("GET", "/exams/x/attempt/ws"),219 ("GET", "/exams/x/attempt/ws"),
214 ("POST", "/courses/x/sessions"),220 ("POST", "/courses/x/sessions"),
@@ -10058,3 +10064,361 @@ async fn settings_accept_admin_edits_trim_entries_and_noop_on_empty_patch() {
10058 ])10064 ])
10059 );10065 );
10060 }10066 }
10067+
10068+// --- question images ---------------------------------------------------------
10069+
10070+/// POST `bytes` as a multipart image upload to `path`; returns (status, json).
10071+async fn post_image(
10072+ app: &axum::Router,
10073+ cookie: &str,
10074+ path: &str,
10075+ content_type: &str,
10076+ bytes: &[u8],
10077+) -> (StatusCode, serde_json::Value) {
10078+ let (status, _, body) = common::send_raw(
10079+ app,
10080+ "POST",
10081+ path,
10082+ Some(cookie),
10083+ Some("multipart/form-data; boundary=hezarfen-test-boundary"),
10084+ common::multipart_file("pic.png", content_type, bytes),
10085+ )
10086+ .await;
10087+ let body = if body.is_empty() {
10088+ serde_json::Value::Null
10089+ } else {
10090+ serde_json::from_slice(&body).unwrap_or(serde_json::Value::Null)
10091+ };
10092+ (status, body)
10093+}
10094+
10095+/// Every stored question-image blob name, straight from the table.
10096+async fn image_blob_keys(db: &hezarfen_backend::database::Database) -> Vec<String> {
10097+ let mut result = db
10098+ .query("SELECT VALUE file FROM question_image")
10099+ .await
10100+ .unwrap()
10101+ .check()
10102+ .unwrap();
10103+ result.take::<Vec<String>>(0).unwrap()
10104+}
10105+
10106+/// The full life of question images: teacher uploads (question + choice slots,
10107+/// rasters only, choice slots bounded), metadata on both question views,
10108+/// bytes behind the sitting wall, replace swaps the blob, a choices PATCH
10109+/// drops the option pictures, and every delete path takes the blobs with it.
10110+#[tokio::test]
10111+async fn question_images_author_serve_and_cascade() {
10112+ let (app, db) = app_and_db().await;
10113+ let teacher = login_as(&app, &db, "img_t", "teacher").await;
10114+ let student = login(&app, "img_s").await;
10115+ let student_id = me_id(&app, &student).await;
10116+ let outsider = login(&app, "img_o").await;
10117+
10118+ let course = create_course(&app, &teacher, "geography").await;
10119+ let subject = create_subject(&app, &teacher, &course, "maps").await;
10120+ enroll(&app, &teacher, &course, &student_id).await;
10121+ let exam = scheduled_exam(
10122+ &app,
10123+ &teacher,
10124+ &course,
10125+ json!({ "title": "map quiz", "kind": "quiz", "mode": "open" }),
10126+ )
10127+ .await;
10128+ let question = create_question(
10129+ &app,
10130+ &teacher,
10131+ &exam,
10132+ &subject,
10133+ json!({ "text": "Which city is marked?", "kind": "choice", "points": 10,
10134+ "choices": ["Ankara", "İzmir"], "correct": 0 }),
10135+ )
10136+ .await;
10137+ let essay = create_question(
10138+ &app,
10139+ &teacher,
10140+ &exam,
10141+ &subject,
10142+ json!({ "text": "Describe the marked region.", "kind": "text", "points": 10 }),
10143+ )
10144+ .await;
10145+
10146+ let q_image = format!("/exams/{exam}/questions/{question}/image");
10147+ let png = b"png-bytes-question".as_slice();
10148+
10149+ // SVG is out (script risk); unknown types are out; rasters land.
10150+ let (status, body) = post_image(&app, &teacher, &q_image, "image/svg+xml", b"<svg/>").await;
10151+ assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
10152+ let (status, body) = post_image(&app, &teacher, &q_image, "application/pdf", b"%PDF").await;
10153+ assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
10154+ let (status, body) = post_image(&app, &teacher, &q_image, "image/png", png).await;
10155+ assert_eq!(status, StatusCode::CREATED, "{body}");
10156+ assert_eq!(body["content_type"], "image/png");
10157+ assert_eq!(body["size"], png.len() as i64);
10158+
10159+ // A classical (text) question takes an illustration too — but no option
10160+ // pictures, and no out-of-range slot anywhere.
10161+ let (status, body) = post_image(
10162+ &app,
10163+ &teacher,
10164+ &format!("/exams/{exam}/questions/{essay}/image"),
10165+ "image/jpeg",
10166+ b"jpeg-essay",
10167+ )
10168+ .await;
10169+ assert_eq!(status, StatusCode::CREATED, "{body}");
10170+ let (status, _) = post_image(
10171+ &app,
10172+ &teacher,
10173+ &format!("/exams/{exam}/questions/{essay}/choices/0/image"),
10174+ "image/png",
10175+ b"x",
10176+ )
10177+ .await;
10178+ assert_eq!(
10179+ status,
10180+ StatusCode::BAD_REQUEST,
10181+ "text questions take no option pictures"
10182+ );
10183+ let (status, _) = post_image(
10184+ &app,
10185+ &teacher,
10186+ &format!("/exams/{exam}/questions/{question}/choices/2/image"),
10187+ "image/png",
10188+ b"x",
10189+ )
10190+ .await;
10191+ assert_eq!(status, StatusCode::BAD_REQUEST, "slot must index a choice");
10192+
10193+ // Option picture on choice 1, and the author view carries all the metas.
10194+ let choice_image = format!("/exams/{exam}/questions/{question}/choices/1/image");
10195+ let (status, _) = post_image(&app, &teacher, &choice_image, "image/webp", b"webp-choice").await;
10196+ assert_eq!(status, StatusCode::CREATED);
10197+ let res = send(
10198+ &app,
10199+ "GET",
10200+ &format!("/exams/{exam}/questions"),
10201+ Some(&teacher),
10202+ None,
10203+ )
10204+ .await;
10205+ assert_eq!(res.status, StatusCode::OK);
10206+ let listed = &common::items(&res.body)[0];
10207+ assert_eq!(listed["image"]["content_type"], "image/png");
10208+ assert!(listed["choice_images"][0].is_null());
10209+ assert_eq!(listed["choice_images"][1]["content_type"], "image/webp");
10210+
10211+ // Replace swaps the blob under the same slot: one row, fresh bytes.
10212+ let keys_before = image_blob_keys(&db).await;
10213+ let png2 = b"png-bytes-question-v2".as_slice();
10214+ let (status, body) = post_image(&app, &teacher, &q_image, "image/png", png2).await;
10215+ assert_eq!(status, StatusCode::CREATED);
10216+ assert_eq!(body["size"], png2.len() as i64);
10217+ let keys_after = image_blob_keys(&db).await;
10218+ assert_eq!(keys_before.len(), keys_after.len(), "replace adds no row");
10219+ for stale in keys_before.iter().filter(|k| !keys_after.contains(k)) {
10220+ assert!(
10221+ !common::files_dir().join(stale).exists(),
10222+ "replaced blob lingers on disk"
10223+ );
10224+ }
10225+
10226+ // The bytes sit behind the sitting wall: outsiders 403, enrolled students
10227+ // 404 until an attempt exists, then 200 with the guard headers on.
10228+ let (status, _, _) =
10229+ common::send_raw(&app, "GET", &q_image, Some(&outsider), None, Vec::new()).await;
10230+ assert_eq!(status, StatusCode::FORBIDDEN);
10231+ let (status, _, _) =
10232+ common::send_raw(&app, "GET", &q_image, Some(&student), None, Vec::new()).await;
10233+ assert_eq!(
10234+ status,
10235+ StatusCode::NOT_FOUND,
10236+ "no early peek before the attempt"
10237+ );
10238+ let res = send(
10239+ &app,
10240+ "POST",
10241+ &format!("/exams/{exam}/attempt"),
10242+ Some(&student),
10243+ None,
10244+ )
10245+ .await;
10246+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
10247+ let (status, headers, bytes) =
10248+ common::send_raw(&app, "GET", &q_image, Some(&student), None, Vec::new()).await;
10249+ assert_eq!(status, StatusCode::OK);
10250+ assert_eq!(bytes, png2);
10251+ assert_eq!(headers["content-type"], "image/png");
10252+ assert_eq!(headers["x-content-type-options"], "nosniff");
10253+ assert_eq!(headers["cache-control"], "private, no-store");
10254+ let (status, _, bytes) =
10255+ common::send_raw(&app, "GET", &choice_image, Some(&student), None, Vec::new()).await;
10256+ assert_eq!(status, StatusCode::OK);
10257+ assert_eq!(bytes, b"webp-choice");
10258+
10259+ // The sitting view embeds the same metadata the author sees (sans key).
10260+ let res = send(
10261+ &app,
10262+ "GET",
10263+ &format!("/exams/{exam}/attempt/questions"),
10264+ Some(&student),
10265+ None,
10266+ )
10267+ .await;
10268+ assert_eq!(res.status, StatusCode::OK);
10269+ assert_eq!(res.body[0]["image"]["content_type"], "image/png");
10270+ assert_eq!(
10271+ res.body[0]["choice_images"][1]["content_type"],
10272+ "image/webp"
10273+ );
10274+ assert_eq!(res.body[1]["image"]["content_type"], "image/jpeg");
10275+ assert!(res.body[1]["choice_images"].is_null());
10276+
10277+ // Images freeze with the rest of the question once attempts exist.
10278+ let (status, body) = post_image(&app, &teacher, &q_image, "image/png", b"late").await;
10279+ assert_eq!(status, StatusCode::CONFLICT, "{body}");
10280+ let res = send(&app, "DELETE", &q_image, Some(&teacher), None).await;
10281+ assert_eq!(res.status, StatusCode::CONFLICT);
10282+
10283+ // Deleting the exam takes every image row and blob with it.
10284+ let keys = image_blob_keys(&db).await;
10285+ assert_eq!(keys.len(), 3);
10286+ let res = send(
10287+ &app,
10288+ "DELETE",
10289+ &format!("/exams/{exam}"),
10290+ Some(&teacher),
10291+ None,
10292+ )
10293+ .await;
10294+ assert_eq!(res.status, StatusCode::NO_CONTENT);
10295+ assert!(
10296+ image_blob_keys(&db).await.is_empty(),
10297+ "rows survived the cascade"
10298+ );
10299+ for key in &keys {
10300+ assert!(
10301+ !common::files_dir().join(key).exists(),
10302+ "blob {key} survived the exam delete"
10303+ );
10304+ }
10305+}
10306+
10307+/// The authoring edits that reshape a question also groom its images: a
10308+/// replaced `choices` list drops the option pictures (the illustration
10309+/// stays), an explicit image DELETE removes row + blob, and deleting the
10310+/// question sweeps the rest.
10311+#[tokio::test]
10312+async fn question_image_edits_follow_the_choices() {
10313+ let (app, db) = app_and_db().await;
10314+ let teacher = login_as(&app, &db, "imge_t", "teacher").await;
10315+ let course = create_course(&app, &teacher, "history").await;
10316+ let subject = create_subject(&app, &teacher, &course, "eras").await;
10317+ let exam = scheduled_exam(
10318+ &app,
10319+ &teacher,
10320+ &course,
10321+ json!({ "title": "eras", "kind": "quiz", "mode": "open" }),
10322+ )
10323+ .await;
10324+ let question = create_question(
10325+ &app,
10326+ &teacher,
10327+ &exam,
10328+ &subject,
10329+ json!({ "text": "Pick the era.", "kind": "choice", "points": 5,
10330+ "choices": ["Bronze", "Iron"], "correct": 1 }),
10331+ )
10332+ .await;
10333+ let base = format!("/exams/{exam}/questions/{question}");
10334+ for (path, bytes) in [
10335+ (format!("{base}/image"), b"illustration".as_slice()),
10336+ (format!("{base}/choices/0/image"), b"bronze".as_slice()),
10337+ (format!("{base}/choices/1/image"), b"iron".as_slice()),
10338+ ] {
10339+ let (status, body) = post_image(&app, &teacher, &path, "image/png", bytes).await;
10340+ assert_eq!(status, StatusCode::CREATED, "{body}");
10341+ }
10342+
10343+ // A points-only PATCH touches no images.
10344+ let res = send(
10345+ &app,
10346+ "PATCH",
10347+ &base,
10348+ Some(&teacher),
10349+ Some(json!({ "points": 7 })),
10350+ )
10351+ .await;
10352+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
10353+ assert!(res.body["image"].is_object());
10354+ assert!(res.body["choice_images"][0].is_object());
10355+ assert!(res.body["choice_images"][1].is_object());
10356+
10357+ // Replacing the choices drops the option pictures, keeps the illustration.
10358+ let keys_before = image_blob_keys(&db).await;
10359+ let res = send(
10360+ &app,
10361+ "PATCH",
10362+ &base,
10363+ Some(&teacher),
10364+ Some(json!({ "choices": ["Stone", "Bronze", "Iron"], "correct": 2 })),
10365+ )
10366+ .await;
10367+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
10368+ assert!(res.body["image"].is_object(), "illustration must survive");
10369+ assert_eq!(
10370+ res.body["choice_images"],
10371+ json!([null, null, null]),
10372+ "option pictures must not follow a replaced list"
10373+ );
10374+ let keys_after = image_blob_keys(&db).await;
10375+ assert_eq!(keys_after.len(), 1);
10376+ for dropped in keys_before.iter().filter(|k| !keys_after.contains(k)) {
10377+ assert!(
10378+ !common::files_dir().join(dropped).exists(),
10379+ "dropped option blob lingers"
10380+ );
10381+ }
10382+
10383+ // Explicit image DELETE: 204 once, 404 after, blob gone.
10384+ let (status, _) = post_image(
10385+ &app,
10386+ &teacher,
10387+ &format!("{base}/choices/0/image"),
10388+ "image/gif",
10389+ b"gif",
10390+ )
10391+ .await;
10392+ assert_eq!(status, StatusCode::CREATED);
10393+ let res = send(
10394+ &app,
10395+ "DELETE",
10396+ &format!("{base}/choices/0/image"),
10397+ Some(&teacher),
10398+ None,
10399+ )
10400+ .await;
10401+ assert_eq!(res.status, StatusCode::NO_CONTENT);
10402+ let res = send(
10403+ &app,
10404+ "DELETE",
10405+ &format!("{base}/choices/0/image"),
10406+ Some(&teacher),
10407+ None,
10408+ )
10409+ .await;
10410+ assert_eq!(res.status, StatusCode::NOT_FOUND);
10411+
10412+ // Deleting the question sweeps its remaining image rows and blobs.
10413+ let keys = image_blob_keys(&db).await;
10414+ assert_eq!(keys.len(), 1);
10415+ let res = send(&app, "DELETE", &base, Some(&teacher), None).await;
10416+ assert_eq!(res.status, StatusCode::NO_CONTENT);
10417+ assert!(image_blob_keys(&db).await.is_empty());
10418+ for key in &keys {
10419+ assert!(
10420+ !common::files_dir().join(key).exists(),
10421+ "blob {key} survived the question delete"
10422+ );
10423+ }
10424+}