| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | use std::collections::HashMap; |
| 12 | |
| 13 | use axum::Json; |
| 14 | use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; |
| 15 | use axum::http::StatusCode; |
| 16 | use axum::response::Response; |
| 17 | use serde::{Deserialize, Serialize}; |
| 18 | use utoipa::{IntoParams, ToSchema}; |
| 19 | use utoipa_axum::router::OpenApiRouter; |
| 20 | use utoipa_axum::routes; |
| 21 | |
| 22 | use crate::constant::{MAX_MAX_FILE_BYTES, POOL_QUESTION_STATUSES, UPLOAD_BODY_OVERHEAD_BYTES}; |
| 23 | use crate::domain::pool_question::{ |
| 24 | PoolQuestion, PoolQuestionBody, PoolQuestionId, PoolQuestionTitle, |
| 25 | }; |
| 26 | use crate::domain::pool_question_image::PoolQuestionImage; |
| 27 | use crate::domain::role::Role; |
| 28 | use crate::domain::solution::{Solution, SolutionBody, SolutionId}; |
| 29 | use crate::domain::solution_image::SolutionImage; |
| 30 | use crate::domain::user::User; |
| 31 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 32 | use crate::service::pool_question; |
| 33 | use crate::service::pool_question_image; |
| 34 | use crate::service::solution; |
| 35 | use crate::service::solution_image; |
| 36 | use crate::state::AppState; |
| 37 | use crate::web::tenant_state::State; |
| 38 | |
| 39 | use super::{ |
| 40 | CurrentUser, Page, PageParams, PersonRef, RequireStudent, RequireTeacher, UploadFileForm, |
| 41 | person_map, read_image_upload, remove_blob, serve_inline_blob, store_blob, |
| 42 | }; |
| 43 | |
| 44 | pub fn routes() -> OpenApiRouter<AppState> { |
| 45 | OpenApiRouter::new() |
| 46 | .routes(routes!(ask_question, list_questions)) |
| 47 | .routes(routes!(get_question, delete_question)) |
| 48 | .routes(routes!(approve_question)) |
| 49 | .routes(routes!(offer_solution, list_solutions)) |
| 50 | .routes(routes!(delete_solution, edit_solution)) |
| 51 | |
| 52 | |
| 53 | .merge( |
| 54 | OpenApiRouter::new() |
| 55 | .routes(routes!(upload_image, get_image, delete_image)) |
| 56 | .routes(routes!( |
| 57 | upload_solution_image, |
| 58 | get_solution_image, |
| 59 | delete_solution_image |
| 60 | )) |
| 61 | .layer(DefaultBodyLimit::max( |
| 62 | MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES, |
| 63 | )), |
| 64 | ) |
| 65 | } |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | fn ensure_visible(question: &PoolQuestion, user: &User) -> Result<(), AppError> { |
| 71 | if question.is_approved() |
| 72 | || user.get_role().at_least(Role::Teacher) |
| 73 | || question.get_asker() == user.get_id() |
| 74 | { |
| 75 | return Ok(()); |
| 76 | } |
| 77 | Err(AppError::NotFound) |
| 78 | } |
| 79 | |
| 80 | |
| 81 | |
| 82 | fn ensure_asker_editable(question: &PoolQuestion, user: &User) -> Result<(), AppError> { |
| 83 | ensure_visible(question, user)?; |
| 84 | if question.get_asker() != user.get_id() { |
| 85 | return Err(AppError::Forbidden( |
| 86 | "only the asker may change the question's image", |
| 87 | )); |
| 88 | } |
| 89 | if question.is_approved() { |
| 90 | return Err(AppError::Conflict( |
| 91 | "the question is approved — its content is frozen", |
| 92 | )); |
| 93 | } |
| 94 | Ok(()) |
| 95 | } |
| 96 | |
| 97 | async fn question_or_404(st: &AppState, id: &str) -> Result<PoolQuestion, AppError> { |
| 98 | pool_question::read(&st.db, &PoolQuestionId::from_key(id)) |
| 99 | .await? |
| 100 | .ok_or(AppError::NotFound) |
| 101 | } |
| 102 | |
| 103 | #[derive(Deserialize, ToSchema)] |
| 104 | struct AskQuestion { |
| 105 | #[schema(example = "Bu integrali çözemedim", max_length = 200)] |
| 106 | title: String, |
| 107 | #[schema(example = "∫x·eˣ dx nasıl adım adım çözülür?", max_length = 10000)] |
| 108 | body: String, |
| 109 | } |
| 110 | |
| 111 | #[derive(Deserialize, ToSchema)] |
| 112 | struct OfferSolution { |
| 113 | #[schema(example = "Kısmi integrasyon: u = x, dv = eˣ dx …", max_length = 10000)] |
| 114 | body: String, |
| 115 | } |
| 116 | |
| 117 | #[derive(Deserialize, IntoParams)] |
| 118 | struct PoolQuestionFilter { |
| 119 | |
| 120 | |
| 121 | |
| 122 | #[param(example = "pending")] |
| 123 | status: Option<String>, |
| 124 | } |
| 125 | |
| 126 | |
| 127 | |
| 128 | |
| 129 | #[derive(Serialize, ToSchema)] |
| 130 | struct PoolImageMeta { |
| 131 | #[schema(example = "image/jpeg")] |
| 132 | content_type: String, |
| 133 | |
| 134 | #[schema(example = 204_800)] |
| 135 | size: i64, |
| 136 | } |
| 137 | |
| 138 | |
| 139 | |
| 140 | #[derive(Serialize, ToSchema)] |
| 141 | struct PoolQuestionResponse { |
| 142 | id: String, |
| 143 | |
| 144 | asker: PersonRef, |
| 145 | title: String, |
| 146 | body: String, |
| 147 | #[schema(example = "approved")] |
| 148 | status: String, |
| 149 | |
| 150 | asked_at: i64, |
| 151 | |
| 152 | approved_by: Option<PersonRef>, |
| 153 | |
| 154 | |
| 155 | image: Option<PoolImageMeta>, |
| 156 | |
| 157 | |
| 158 | solution_count: i64, |
| 159 | } |
| 160 | |
| 161 | impl PoolQuestionResponse { |
| 162 | fn new( |
| 163 | question: &PoolQuestion, |
| 164 | people: &std::collections::HashMap<String, PersonRef>, |
| 165 | solution_count: i64, |
| 166 | image: Option<&PoolQuestionImage>, |
| 167 | ) -> Self { |
| 168 | Self { |
| 169 | id: question.get_id().key().to_string(), |
| 170 | asker: PersonRef::resolve(people, question.get_asker()), |
| 171 | title: question.get_title().as_str().to_string(), |
| 172 | body: question.get_body().as_str().to_string(), |
| 173 | status: question.get_status().to_string(), |
| 174 | asked_at: question.get_asked_at().as_millis(), |
| 175 | approved_by: question |
| 176 | .get_approved_by() |
| 177 | .map(|approver| PersonRef::resolve(people, approver)), |
| 178 | image: image.map(|image| PoolImageMeta { |
| 179 | content_type: image.get_content_type().as_str().to_string(), |
| 180 | size: image.get_size(), |
| 181 | }), |
| 182 | solution_count, |
| 183 | } |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | |
| 188 | #[derive(Serialize, ToSchema)] |
| 189 | struct SolutionResponse { |
| 190 | id: String, |
| 191 | |
| 192 | question: String, |
| 193 | |
| 194 | author: PersonRef, |
| 195 | body: String, |
| 196 | |
| 197 | offered_at: i64, |
| 198 | |
| 199 | |
| 200 | image: Option<PoolImageMeta>, |
| 201 | } |
| 202 | |
| 203 | impl SolutionResponse { |
| 204 | fn new( |
| 205 | solution: &Solution, |
| 206 | people: &std::collections::HashMap<String, PersonRef>, |
| 207 | image: Option<&SolutionImage>, |
| 208 | ) -> Self { |
| 209 | Self { |
| 210 | id: solution.get_id().key().to_string(), |
| 211 | question: solution.get_question().key().to_string(), |
| 212 | author: PersonRef::resolve(people, solution.get_author()), |
| 213 | body: solution.get_body().as_str().to_string(), |
| 214 | offered_at: solution.get_offered_at().as_millis(), |
| 215 | image: image.map(|image| PoolImageMeta { |
| 216 | content_type: image.get_content_type().as_str().to_string(), |
| 217 | size: image.get_size(), |
| 218 | }), |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | |
| 224 | |
| 225 | |
| 226 | async fn question_responses( |
| 227 | questions: &[PoolQuestion], |
| 228 | st: &AppState, |
| 229 | ) -> Result<Vec<PoolQuestionResponse>, AppError> { |
| 230 | let ids = questions.iter().flat_map(|question| { |
| 231 | std::iter::once(*question.get_asker()).chain(question.get_approved_by().cloned()) |
| 232 | }); |
| 233 | let people = person_map(ids, &st.db).await?; |
| 234 | let question_ids: Vec<PoolQuestionId> = questions |
| 235 | .iter() |
| 236 | .map(|question| *question.get_id()) |
| 237 | .collect(); |
| 238 | let counts = solution::counts_for(&st.db, &question_ids).await?; |
| 239 | |
| 240 | |
| 241 | let image_refs: Vec<&PoolQuestionId> = questions.iter().map(|q| q.get_id()).collect(); |
| 242 | let mut images: HashMap<String, PoolQuestionImage> = HashMap::new(); |
| 243 | for image in pool_question_image::list_for_questions(&st.db, &image_refs).await? { |
| 244 | images.insert(image.get_question().key(), image); |
| 245 | } |
| 246 | Ok(questions |
| 247 | .iter() |
| 248 | .map(|question| { |
| 249 | let count = counts.get(&question.get_id().key()).copied().unwrap_or(0); |
| 250 | let image = images.get(question.get_id().key().as_str()); |
| 251 | PoolQuestionResponse::new(question, &people, count, image) |
| 252 | }) |
| 253 | .collect()) |
| 254 | } |
| 255 | |
| 256 | |
| 257 | |
| 258 | |
| 259 | |
| 260 | |
| 261 | #[utoipa::path( |
| 262 | post, |
| 263 | path = "/", |
| 264 | tag = "questions", |
| 265 | security(("session_cookie" = [])), |
| 266 | request_body = AskQuestion, |
| 267 | responses( |
| 268 | (status = 201, description = "Question created, pending approval", body = PoolQuestionResponse), |
| 269 | (status = 400, description = "Invalid title or body", body = ErrorResponse), |
| 270 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 271 | (status = 403, description = "Requires the student role", body = ErrorResponse), |
| 272 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 273 | ), |
| 274 | )] |
| 275 | async fn ask_question( |
| 276 | State(st): State<AppState>, |
| 277 | CurrentUser(user): CurrentUser, |
| 278 | Json(req): Json<AskQuestion>, |
| 279 | ) -> Result<(StatusCode, Json<PoolQuestionResponse>), AppError> { |
| 280 | if user.get_role() != Role::Student { |
| 281 | return Err(AppError::Forbidden("only students ask pool questions")); |
| 282 | } |
| 283 | let title = PoolQuestionTitle::try_new(&req.title)?; |
| 284 | let body = PoolQuestionBody::try_new(&req.body)?; |
| 285 | let question = |
| 286 | pool_question::insert(&st.db, PoolQuestion::new(user.get_id(), title, body)).await?; |
| 287 | let responses = question_responses(std::slice::from_ref(&question), &st).await?; |
| 288 | let response = responses |
| 289 | .into_iter() |
| 290 | .next() |
| 291 | .ok_or_else(|| AppError::Internal("failed to render the created question".into()))?; |
| 292 | Ok((StatusCode::CREATED, Json(response))) |
| 293 | } |
| 294 | |
| 295 | |
| 296 | |
| 297 | |
| 298 | |
| 299 | |
| 300 | |
| 301 | |
| 302 | |
| 303 | |
| 304 | #[utoipa::path( |
| 305 | get, |
| 306 | path = "/", |
| 307 | tag = "questions", |
| 308 | security(("session_cookie" = [])), |
| 309 | params(PoolQuestionFilter, PageParams), |
| 310 | responses( |
| 311 | (status = 200, description = "A page of the questions visible to the caller", body = Page<PoolQuestionResponse>), |
| 312 | (status = 400, description = "Unknown status, or invalid limit or offset", body = ErrorResponse), |
| 313 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 314 | (status = 403, description = "Requires student role or higher", body = ErrorResponse), |
| 315 | ), |
| 316 | )] |
| 317 | async fn list_questions( |
| 318 | State(st): State<AppState>, |
| 319 | RequireStudent(user): RequireStudent, |
| 320 | Query(filter): Query<PoolQuestionFilter>, |
| 321 | Query(page): Query<PageParams>, |
| 322 | ) -> Result<Json<Page<PoolQuestionResponse>>, AppError> { |
| 323 | let (limit, offset) = page.resolve()?; |
| 324 | let status = filter.status.as_deref().map(str::trim); |
| 325 | if let Some(status) = status |
| 326 | && !POOL_QUESTION_STATUSES.contains(&status) |
| 327 | { |
| 328 | return Err(AppError::Validation(ValidationError::Invalid { |
| 329 | field: "status", |
| 330 | reason: "must be one of: pending, approved", |
| 331 | })); |
| 332 | } |
| 333 | |
| 334 | |
| 335 | |
| 336 | |
| 337 | |
| 338 | let viewer = (!user.get_role().at_least(Role::Teacher)).then_some(user.get_id()); |
| 339 | let (questions, total) = |
| 340 | pool_question::list(&st.db, viewer, status, limit, offset).await?; |
| 341 | |
| 342 | let items = question_responses(&questions, &st).await?; |
| 343 | Ok(Json(Page::new(items, total, limit, offset))) |
| 344 | } |
| 345 | |
| 346 | |
| 347 | |
| 348 | #[utoipa::path( |
| 349 | get, |
| 350 | path = "/{id}", |
| 351 | tag = "questions", |
| 352 | security(("session_cookie" = [])), |
| 353 | params(("id" = String, Path, description = "Question id")), |
| 354 | responses( |
| 355 | (status = 200, description = "The question", body = PoolQuestionResponse), |
| 356 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 357 | (status = 403, description = "Requires student role or higher", body = ErrorResponse), |
| 358 | (status = 404, description = "No such question (or pending and not yours)", body = ErrorResponse), |
| 359 | ), |
| 360 | )] |
| 361 | async fn get_question( |
| 362 | State(st): State<AppState>, |
| 363 | RequireStudent(user): RequireStudent, |
| 364 | Path(id): Path<String>, |
| 365 | ) -> Result<Json<PoolQuestionResponse>, AppError> { |
| 366 | let question = question_or_404(&st, &id).await?; |
| 367 | ensure_visible(&question, &user)?; |
| 368 | let responses = question_responses(std::slice::from_ref(&question), &st).await?; |
| 369 | let response = responses |
| 370 | .into_iter() |
| 371 | .next() |
| 372 | .ok_or_else(|| AppError::Internal("failed to render the question".into()))?; |
| 373 | Ok(Json(response)) |
| 374 | } |
| 375 | |
| 376 | |
| 377 | |
| 378 | |
| 379 | #[utoipa::path( |
| 380 | post, |
| 381 | path = "/{id}/approve", |
| 382 | tag = "questions", |
| 383 | security(("session_cookie" = [])), |
| 384 | params(("id" = String, Path, description = "Question id")), |
| 385 | responses( |
| 386 | (status = 200, description = "The question, now approved", body = PoolQuestionResponse), |
| 387 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 388 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), |
| 389 | (status = 404, description = "No such question", body = ErrorResponse), |
| 390 | (status = 409, description = "Already approved", body = ErrorResponse), |
| 391 | ), |
| 392 | )] |
| 393 | async fn approve_question( |
| 394 | State(st): State<AppState>, |
| 395 | RequireTeacher(user): RequireTeacher, |
| 396 | Path(id): Path<String>, |
| 397 | ) -> Result<Json<PoolQuestionResponse>, AppError> { |
| 398 | let question = |
| 399 | pool_question::approve(&st.db, &PoolQuestionId::from_key(&id), user.get_id()).await?; |
| 400 | |
| 401 | |
| 402 | |
| 403 | |
| 404 | |
| 405 | for earner in [user.get_id(), question.get_asker()] { |
| 406 | if let Err(err) = crate::service::badge::sync(&st.db, earner).await { |
| 407 | tracing::warn!("failed to sync badges for {}: {err}", earner.key()); |
| 408 | } |
| 409 | } |
| 410 | let responses = question_responses(std::slice::from_ref(&question), &st).await?; |
| 411 | let response = responses |
| 412 | .into_iter() |
| 413 | .next() |
| 414 | .ok_or_else(|| AppError::Internal("failed to render the approved question".into()))?; |
| 415 | Ok(Json(response)) |
| 416 | } |
| 417 | |
| 418 | |
| 419 | |
| 420 | |
| 421 | |
| 422 | #[utoipa::path( |
| 423 | delete, |
| 424 | path = "/{id}", |
| 425 | tag = "questions", |
| 426 | security(("session_cookie" = [])), |
| 427 | params(("id" = String, Path, description = "Question id")), |
| 428 | responses( |
| 429 | (status = 204, description = "Deleted, solutions included"), |
| 430 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 431 | (status = 403, description = "Not the asker (and not teacher+)", body = ErrorResponse), |
| 432 | (status = 404, description = "No such question (or pending and not yours)", body = ErrorResponse), |
| 433 | ), |
| 434 | )] |
| 435 | async fn delete_question( |
| 436 | State(st): State<AppState>, |
| 437 | RequireStudent(user): RequireStudent, |
| 438 | Path(id): Path<String>, |
| 439 | ) -> Result<StatusCode, AppError> { |
| 440 | let question = question_or_404(&st, &id).await?; |
| 441 | ensure_visible(&question, &user)?; |
| 442 | if question.get_asker() != user.get_id() && !user.get_role().at_least(Role::Teacher) { |
| 443 | return Err(AppError::Forbidden( |
| 444 | "only the asker or a teacher+ may delete a question", |
| 445 | )); |
| 446 | } |
| 447 | let removed = pool_question::delete(&st.db, question.get_id()) |
| 448 | .await? |
| 449 | .ok_or(AppError::NotFound)?; |
| 450 | |
| 451 | |
| 452 | for file in &removed.image_files { |
| 453 | remove_blob(&st.files_path, file).await; |
| 454 | } |
| 455 | Ok(StatusCode::NO_CONTENT) |
| 456 | } |
| 457 | |
| 458 | |
| 459 | |
| 460 | |
| 461 | |
| 462 | |
| 463 | |
| 464 | |
| 465 | |
| 466 | |
| 467 | |
| 468 | |
| 469 | |
| 470 | #[utoipa::path( |
| 471 | post, |
| 472 | path = "/{id}/image", |
| 473 | tag = "questions", |
| 474 | security(("session_cookie" = [])), |
| 475 | params(("id" = String, Path, description = "Question id")), |
| 476 | request_body(content = UploadFileForm, content_type = "multipart/form-data"), |
| 477 | responses( |
| 478 | (status = 201, description = "Image stored", body = PoolImageMeta), |
| 479 | (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse), |
| 480 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 481 | (status = 403, description = "Not the asker", body = ErrorResponse), |
| 482 | (status = 404, description = "No such question (or pending and not yours)", body = ErrorResponse), |
| 483 | (status = 409, description = "The question is approved — content is frozen", body = ErrorResponse), |
| 484 | (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), |
| 485 | ), |
| 486 | )] |
| 487 | async fn upload_image( |
| 488 | State(st): State<AppState>, |
| 489 | RequireStudent(user): RequireStudent, |
| 490 | Path(id): Path<String>, |
| 491 | mut multipart: Multipart, |
| 492 | ) -> Result<(StatusCode, Json<PoolImageMeta>), AppError> { |
| 493 | let question = question_or_404(&st, &id).await?; |
| 494 | ensure_asker_editable(&question, &user)?; |
| 495 | let upload = read_image_upload(&st, &mut multipart).await?; |
| 496 | let size = upload.size(); |
| 497 | |
| 498 | let file = crate::domain::monotonic_id::next_uuid().to_string(); |
| 499 | store_blob(&st, &file, &upload.data, || async { |
| 500 | match pool_question::set_image(&st.db, question.get_id(), &file, &upload.content_type, size) |
| 501 | .await? |
| 502 | { |
| 503 | |
| 504 | |
| 505 | Some(replaced) => Ok(((), replaced)), |
| 506 | |
| 507 | None => Err(AppError::Conflict("the question is no longer pending")), |
| 508 | } |
| 509 | }) |
| 510 | .await?; |
| 511 | Ok(( |
| 512 | StatusCode::CREATED, |
| 513 | Json(PoolImageMeta { |
| 514 | content_type: upload.content_type.as_str().to_string(), |
| 515 | size, |
| 516 | }), |
| 517 | )) |
| 518 | } |
| 519 | |
| 520 | |
| 521 | |
| 522 | #[utoipa::path( |
| 523 | get, |
| 524 | path = "/{id}/image", |
| 525 | tag = "questions", |
| 526 | security(("session_cookie" = [])), |
| 527 | params(("id" = String, Path, description = "Question id")), |
| 528 | responses( |
| 529 | (status = 200, description = "The image bytes", content_type = "image/*"), |
| 530 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 531 | (status = 403, description = "Requires student role or higher", body = ErrorResponse), |
| 532 | (status = 404, description = "No such question or image (or pending and not yours)", body = ErrorResponse), |
| 533 | ), |
| 534 | )] |
| 535 | async fn get_image( |
| 536 | State(st): State<AppState>, |
| 537 | RequireStudent(user): RequireStudent, |
| 538 | Path(id): Path<String>, |
| 539 | ) -> Result<Response, AppError> { |
| 540 | let question = question_or_404(&st, &id).await?; |
| 541 | ensure_visible(&question, &user)?; |
| 542 | let image = pool_question_image::read(&st.db, question.get_id()).await?; |
| 543 | match image { |
| 544 | Some(image) => { |
| 545 | serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await |
| 546 | } |
| 547 | None => Err(AppError::NotFound), |
| 548 | } |
| 549 | } |
| 550 | |
| 551 | |
| 552 | |
| 553 | #[utoipa::path( |
| 554 | delete, |
| 555 | path = "/{id}/image", |
| 556 | tag = "questions", |
| 557 | security(("session_cookie" = [])), |
| 558 | params(("id" = String, Path, description = "Question id")), |
| 559 | responses( |
| 560 | (status = 204, description = "Image removed"), |
| 561 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 562 | (status = 403, description = "Not the asker", body = ErrorResponse), |
| 563 | (status = 404, description = "No such question or image (or pending and not yours)", body = ErrorResponse), |
| 564 | (status = 409, description = "The question is approved — content is frozen", body = ErrorResponse), |
| 565 | ), |
| 566 | )] |
| 567 | async fn delete_image( |
| 568 | State(st): State<AppState>, |
| 569 | RequireStudent(user): RequireStudent, |
| 570 | Path(id): Path<String>, |
| 571 | ) -> Result<StatusCode, AppError> { |
| 572 | let question = question_or_404(&st, &id).await?; |
| 573 | ensure_asker_editable(&question, &user)?; |
| 574 | match pool_question::clear_image(&st.db, question.get_id()).await? { |
| 575 | |
| 576 | Some(Some(file)) => { |
| 577 | remove_blob(&st.files_path, &file).await; |
| 578 | Ok(StatusCode::NO_CONTENT) |
| 579 | } |
| 580 | |
| 581 | Some(None) => Err(AppError::NotFound), |
| 582 | |
| 583 | None => Err(AppError::Conflict("the question is no longer pending")), |
| 584 | } |
| 585 | } |
| 586 | |
| 587 | |
| 588 | |
| 589 | |
| 590 | |
| 591 | |
| 592 | async fn visible_solution( |
| 593 | st: &AppState, |
| 594 | user: &User, |
| 595 | id: &str, |
| 596 | sid: &str, |
| 597 | ) -> Result<Solution, AppError> { |
| 598 | let question = question_or_404(st, id).await?; |
| 599 | ensure_visible(&question, user)?; |
| 600 | solution::read_for(&st.db, &SolutionId::from_key(sid), question.get_id()) |
| 601 | .await? |
| 602 | .ok_or(AppError::NotFound) |
| 603 | } |
| 604 | |
| 605 | |
| 606 | |
| 607 | |
| 608 | |
| 609 | |
| 610 | async fn author_solution( |
| 611 | st: &AppState, |
| 612 | user: &User, |
| 613 | id: &str, |
| 614 | sid: &str, |
| 615 | ) -> Result<Solution, AppError> { |
| 616 | let solution = visible_solution(st, user, id, sid).await?; |
| 617 | if solution.get_author() != user.get_id() { |
| 618 | return Err(AppError::Forbidden("only the author may edit a solution")); |
| 619 | } |
| 620 | Ok(solution) |
| 621 | } |
| 622 | |
| 623 | |
| 624 | |
| 625 | |
| 626 | #[utoipa::path( |
| 627 | post, |
| 628 | path = "/{id}/solutions", |
| 629 | tag = "questions", |
| 630 | security(("session_cookie" = [])), |
| 631 | params(("id" = String, Path, description = "Question id")), |
| 632 | request_body = OfferSolution, |
| 633 | responses( |
| 634 | (status = 201, description = "Solution offered", body = SolutionResponse), |
| 635 | (status = 400, description = "Invalid body", body = ErrorResponse), |
| 636 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 637 | (status = 403, description = "Requires student role or higher", body = ErrorResponse), |
| 638 | (status = 404, description = "No such question (or pending and not yours)", body = ErrorResponse), |
| 639 | (status = 409, description = "The question is not approved yet", body = ErrorResponse), |
| 640 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 641 | ), |
| 642 | )] |
| 643 | async fn offer_solution( |
| 644 | State(st): State<AppState>, |
| 645 | RequireStudent(user): RequireStudent, |
| 646 | Path(id): Path<String>, |
| 647 | Json(req): Json<OfferSolution>, |
| 648 | ) -> Result<(StatusCode, Json<SolutionResponse>), AppError> { |
| 649 | let question = question_or_404(&st, &id).await?; |
| 650 | ensure_visible(&question, &user)?; |
| 651 | if !question.is_approved() { |
| 652 | return Err(AppError::Conflict( |
| 653 | "the question is not approved yet — solutions open with the pool", |
| 654 | )); |
| 655 | } |
| 656 | let body = SolutionBody::try_new(&req.body)?; |
| 657 | let solution = solution::insert( |
| 658 | &st.db, |
| 659 | Solution::new(question.get_id(), user.get_id(), body), |
| 660 | ) |
| 661 | .await?; |
| 662 | let people = person_map([*user.get_id()], &st.db).await?; |
| 663 | Ok(( |
| 664 | StatusCode::CREATED, |
| 665 | Json(SolutionResponse::new(&solution, &people, None)), |
| 666 | )) |
| 667 | } |
| 668 | |
| 669 | |
| 670 | |
| 671 | #[utoipa::path( |
| 672 | get, |
| 673 | path = "/{id}/solutions", |
| 674 | tag = "questions", |
| 675 | security(("session_cookie" = [])), |
| 676 | params(("id" = String, Path, description = "Question id"), PageParams), |
| 677 | responses( |
| 678 | (status = 200, description = "A page of the question's solutions", body = Page<SolutionResponse>), |
| 679 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 680 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 681 | (status = 403, description = "Requires student role or higher", body = ErrorResponse), |
| 682 | (status = 404, description = "No such question (or pending and not yours)", body = ErrorResponse), |
| 683 | ), |
| 684 | )] |
| 685 | async fn list_solutions( |
| 686 | State(st): State<AppState>, |
| 687 | RequireStudent(user): RequireStudent, |
| 688 | Path(id): Path<String>, |
| 689 | Query(page): Query<PageParams>, |
| 690 | ) -> Result<Json<Page<SolutionResponse>>, AppError> { |
| 691 | let (limit, offset) = page.resolve()?; |
| 692 | let question = question_or_404(&st, &id).await?; |
| 693 | ensure_visible(&question, &user)?; |
| 694 | let (solutions, total) = solution::list_for(&st.db, question.get_id(), limit, offset).await?; |
| 695 | let slice = solutions.as_slice(); |
| 696 | let people = person_map(slice.iter().map(|solution| *solution.get_author()), &st.db).await?; |
| 697 | let solution_refs: Vec<&SolutionId> = slice.iter().map(|s| s.get_id()).collect(); |
| 698 | let mut images: HashMap<String, SolutionImage> = HashMap::new(); |
| 699 | for image in solution_image::list_for_solutions(&st.db, &solution_refs).await? { |
| 700 | images.insert(image.get_solution().key(), image); |
| 701 | } |
| 702 | let items = slice |
| 703 | .iter() |
| 704 | .map(|solution| { |
| 705 | let image = images.get(solution.get_id().key().as_str()); |
| 706 | SolutionResponse::new(solution, &people, image) |
| 707 | }) |
| 708 | .collect(); |
| 709 | Ok(Json(Page::new(items, total, limit, offset))) |
| 710 | } |
| 711 | |
| 712 | |
| 713 | |
| 714 | #[utoipa::path( |
| 715 | delete, |
| 716 | path = "/{id}/solutions/{sid}", |
| 717 | tag = "questions", |
| 718 | security(("session_cookie" = [])), |
| 719 | params( |
| 720 | ("id" = String, Path, description = "Question id"), |
| 721 | ("sid" = String, Path, description = "Solution id"), |
| 722 | ), |
| 723 | responses( |
| 724 | (status = 204, description = "Solution deleted"), |
| 725 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 726 | (status = 403, description = "Not the author (and not teacher+)", body = ErrorResponse), |
| 727 | (status = 404, description = "No such question or solution", body = ErrorResponse), |
| 728 | ), |
| 729 | )] |
| 730 | async fn delete_solution( |
| 731 | State(st): State<AppState>, |
| 732 | RequireStudent(user): RequireStudent, |
| 733 | Path((id, sid)): Path<(String, String)>, |
| 734 | ) -> Result<StatusCode, AppError> { |
| 735 | let solution = visible_solution(&st, &user, &id, &sid).await?; |
| 736 | if solution.get_author() != user.get_id() && !user.get_role().at_least(Role::Teacher) { |
| 737 | return Err(AppError::Forbidden( |
| 738 | "only the author or a teacher+ may delete a solution", |
| 739 | )); |
| 740 | } |
| 741 | |
| 742 | |
| 743 | let (_, image) = solution::delete(&st.db, solution) |
| 744 | .await? |
| 745 | .ok_or(AppError::NotFound)?; |
| 746 | if let Some(file) = image { |
| 747 | remove_blob(&st.files_path, &file).await; |
| 748 | } |
| 749 | Ok(StatusCode::NO_CONTENT) |
| 750 | } |
| 751 | |
| 752 | |
| 753 | |
| 754 | |
| 755 | |
| 756 | |
| 757 | #[utoipa::path( |
| 758 | patch, |
| 759 | path = "/{id}/solutions/{sid}", |
| 760 | tag = "questions", |
| 761 | security(("session_cookie" = [])), |
| 762 | params( |
| 763 | ("id" = String, Path, description = "Question id"), |
| 764 | ("sid" = String, Path, description = "Solution id"), |
| 765 | ), |
| 766 | request_body = OfferSolution, |
| 767 | responses( |
| 768 | (status = 200, description = "The updated solution", body = SolutionResponse), |
| 769 | (status = 400, description = "Invalid body", body = ErrorResponse), |
| 770 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 771 | (status = 403, description = "Not the author", body = ErrorResponse), |
| 772 | (status = 404, description = "No such question or solution", body = ErrorResponse), |
| 773 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 774 | ), |
| 775 | )] |
| 776 | async fn edit_solution( |
| 777 | State(st): State<AppState>, |
| 778 | RequireStudent(user): RequireStudent, |
| 779 | Path((id, sid)): Path<(String, String)>, |
| 780 | Json(req): Json<OfferSolution>, |
| 781 | ) -> Result<Json<SolutionResponse>, AppError> { |
| 782 | let solution = author_solution(&st, &user, &id, &sid).await?; |
| 783 | let body = SolutionBody::try_new(&req.body)?; |
| 784 | let updated = solution::set_body(&st.db, solution.get_id(), &body) |
| 785 | .await? |
| 786 | .ok_or(AppError::NotFound)?; |
| 787 | let people = person_map([*user.get_id()], &st.db).await?; |
| 788 | let image = solution_image::read(&st.db, updated.get_id()).await?; |
| 789 | Ok(Json(SolutionResponse::new( |
| 790 | &updated, |
| 791 | &people, |
| 792 | image.as_ref(), |
| 793 | ))) |
| 794 | } |
| 795 | |
| 796 | |
| 797 | |
| 798 | |
| 799 | |
| 800 | |
| 801 | |
| 802 | |
| 803 | |
| 804 | |
| 805 | |
| 806 | |
| 807 | |
| 808 | #[utoipa::path( |
| 809 | post, |
| 810 | path = "/{id}/solutions/{sid}/image", |
| 811 | tag = "questions", |
| 812 | security(("session_cookie" = [])), |
| 813 | params( |
| 814 | ("id" = String, Path, description = "Question id"), |
| 815 | ("sid" = String, Path, description = "Solution id"), |
| 816 | ), |
| 817 | request_body(content = UploadFileForm, content_type = "multipart/form-data"), |
| 818 | responses( |
| 819 | (status = 201, description = "Image stored", body = PoolImageMeta), |
| 820 | (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse), |
| 821 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 822 | (status = 403, description = "Not the author", body = ErrorResponse), |
| 823 | (status = 404, description = "No such question or solution", body = ErrorResponse), |
| 824 | (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), |
| 825 | ), |
| 826 | )] |
| 827 | async fn upload_solution_image( |
| 828 | State(st): State<AppState>, |
| 829 | RequireStudent(user): RequireStudent, |
| 830 | Path((id, sid)): Path<(String, String)>, |
| 831 | mut multipart: Multipart, |
| 832 | ) -> Result<(StatusCode, Json<PoolImageMeta>), AppError> { |
| 833 | let solution = author_solution(&st, &user, &id, &sid).await?; |
| 834 | let upload = read_image_upload(&st, &mut multipart).await?; |
| 835 | let size = upload.size(); |
| 836 | |
| 837 | let file = crate::domain::monotonic_id::next_uuid().to_string(); |
| 838 | store_blob(&st, &file, &upload.data, || async { |
| 839 | match solution::set_image(&st.db, solution.get_id(), &file, &upload.content_type, size) |
| 840 | .await? |
| 841 | { |
| 842 | |
| 843 | Some(replaced) => Ok(((), replaced)), |
| 844 | |
| 845 | None => Err(AppError::NotFound), |
| 846 | } |
| 847 | }) |
| 848 | .await?; |
| 849 | Ok(( |
| 850 | StatusCode::CREATED, |
| 851 | Json(PoolImageMeta { |
| 852 | content_type: upload.content_type.as_str().to_string(), |
| 853 | size, |
| 854 | }), |
| 855 | )) |
| 856 | } |
| 857 | |
| 858 | |
| 859 | |
| 860 | |
| 861 | #[utoipa::path( |
| 862 | get, |
| 863 | path = "/{id}/solutions/{sid}/image", |
| 864 | tag = "questions", |
| 865 | security(("session_cookie" = [])), |
| 866 | params( |
| 867 | ("id" = String, Path, description = "Question id"), |
| 868 | ("sid" = String, Path, description = "Solution id"), |
| 869 | ), |
| 870 | responses( |
| 871 | (status = 200, description = "The image bytes", content_type = "image/*"), |
| 872 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 873 | (status = 403, description = "Requires student role or higher", body = ErrorResponse), |
| 874 | (status = 404, description = "No such question, solution, or image", body = ErrorResponse), |
| 875 | ), |
| 876 | )] |
| 877 | async fn get_solution_image( |
| 878 | State(st): State<AppState>, |
| 879 | RequireStudent(user): RequireStudent, |
| 880 | Path((id, sid)): Path<(String, String)>, |
| 881 | ) -> Result<Response, AppError> { |
| 882 | let solution = visible_solution(&st, &user, &id, &sid).await?; |
| 883 | let image = solution_image::read(&st.db, solution.get_id()).await?; |
| 884 | match image { |
| 885 | Some(image) => { |
| 886 | serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await |
| 887 | } |
| 888 | None => Err(AppError::NotFound), |
| 889 | } |
| 890 | } |
| 891 | |
| 892 | |
| 893 | |
| 894 | #[utoipa::path( |
| 895 | delete, |
| 896 | path = "/{id}/solutions/{sid}/image", |
| 897 | tag = "questions", |
| 898 | security(("session_cookie" = [])), |
| 899 | params( |
| 900 | ("id" = String, Path, description = "Question id"), |
| 901 | ("sid" = String, Path, description = "Solution id"), |
| 902 | ), |
| 903 | responses( |
| 904 | (status = 204, description = "Image removed"), |
| 905 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 906 | (status = 403, description = "Not the author", body = ErrorResponse), |
| 907 | (status = 404, description = "No such question, solution, or image", body = ErrorResponse), |
| 908 | ), |
| 909 | )] |
| 910 | async fn delete_solution_image( |
| 911 | State(st): State<AppState>, |
| 912 | RequireStudent(user): RequireStudent, |
| 913 | Path((id, sid)): Path<(String, String)>, |
| 914 | ) -> Result<StatusCode, AppError> { |
| 915 | let solution = author_solution(&st, &user, &id, &sid).await?; |
| 916 | match solution::clear_image(&st.db, solution.get_id()).await? { |
| 917 | |
| 918 | Some(Some(file)) => { |
| 919 | remove_blob(&st.files_path, &file).await; |
| 920 | Ok(StatusCode::NO_CONTENT) |
| 921 | } |
| 922 | |
| 923 | _ => Err(AppError::NotFound), |
| 924 | } |
| 925 | } |