| 1 | use std::collections::{HashMap, HashSet}; |
| 2 | |
| 3 | use crate::web::tenant_state::State; |
| 4 | use axum::Json; |
| 5 | use axum::extract::{Path, Query}; |
| 6 | use axum::http::StatusCode; |
| 7 | use serde::{Deserialize, Serialize}; |
| 8 | use utoipa::{IntoParams, ToSchema}; |
| 9 | use utoipa_axum::router::OpenApiRouter; |
| 10 | use utoipa_axum::routes; |
| 11 | |
| 12 | use crate::database::Database; |
| 13 | use crate::domain::message::{ |
| 14 | Folder, Message, MessageBody, MessageId, MessageLabel, MessageSubject, |
| 15 | }; |
| 16 | use crate::domain::user::{User, UserId}; |
| 17 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 18 | use crate::service::message; |
| 19 | use crate::state::AppState; |
| 20 | |
| 21 | use super::dto::Role; |
| 22 | use super::{CurrentUser, Page, PageParams, PersonRef}; |
| 23 | |
| 24 | pub fn routes() -> OpenApiRouter<AppState> { |
| 25 | OpenApiRouter::new() |
| 26 | .routes(routes!(send_message, list)) |
| 27 | .routes(routes!(update_message, delete_message)) |
| 28 | } |
| 29 | |
| 30 | #[derive(Deserialize, ToSchema)] |
| 31 | struct SendMessage { |
| 32 | |
| 33 | #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] |
| 34 | recipient_id: String, |
| 35 | #[schema(example = "About today's study session", max_length = 200)] |
| 36 | subject: String, |
| 37 | #[schema(example = "I may be 10 minutes late.", max_length = 10000)] |
| 38 | body: Option<String>, |
| 39 | |
| 40 | |
| 41 | #[schema(example = "Etüt", max_length = 50)] |
| 42 | label: Option<String>, |
| 43 | } |
| 44 | |
| 45 | #[derive(Deserialize, ToSchema)] |
| 46 | struct UpdateMessage { |
| 47 | |
| 48 | read: Option<bool>, |
| 49 | |
| 50 | |
| 51 | |
| 52 | #[schema(example = "archive")] |
| 53 | folder: Option<String>, |
| 54 | } |
| 55 | |
| 56 | #[derive(Deserialize, IntoParams)] |
| 57 | struct ListFilter { |
| 58 | |
| 59 | #[param(example = "inbox")] |
| 60 | folder: Option<String>, |
| 61 | |
| 62 | |
| 63 | |
| 64 | read: Option<bool>, |
| 65 | |
| 66 | |
| 67 | |
| 68 | #[param(example = "etüt")] |
| 69 | q: Option<String>, |
| 70 | } |
| 71 | |
| 72 | |
| 73 | |
| 74 | |
| 75 | #[derive(Serialize, ToSchema)] |
| 76 | struct MessageResponse { |
| 77 | id: String, |
| 78 | sender: PersonRef, |
| 79 | sender_role: Option<Role>, |
| 80 | recipient: PersonRef, |
| 81 | recipient_role: Option<Role>, |
| 82 | subject: String, |
| 83 | body: String, |
| 84 | |
| 85 | #[schema(example = "Etüt")] |
| 86 | label: Option<String>, |
| 87 | |
| 88 | sent_at: i64, |
| 89 | read: bool, |
| 90 | #[schema(example = "inbox")] |
| 91 | folder: String, |
| 92 | |
| 93 | |
| 94 | |
| 95 | |
| 96 | #[schema(example = "inbox")] |
| 97 | previous_folder: Option<String>, |
| 98 | } |
| 99 | |
| 100 | |
| 101 | |
| 102 | type People = HashMap<String, (PersonRef, Role)>; |
| 103 | |
| 104 | fn people_of<'a>(users: impl IntoIterator<Item = &'a User>) -> People { |
| 105 | users |
| 106 | .into_iter() |
| 107 | .map(|user| { |
| 108 | ( |
| 109 | user.get_id().key().to_string(), |
| 110 | (PersonRef::new(user), user.get_role().into()), |
| 111 | ) |
| 112 | }) |
| 113 | .collect() |
| 114 | } |
| 115 | |
| 116 | |
| 117 | async fn load_people(messages: &[Message], db: &Database) -> Result<People, AppError> { |
| 118 | let mut seen = HashSet::new(); |
| 119 | let ids: Vec<UserId> = messages |
| 120 | .iter() |
| 121 | .flat_map(|message| [*message.get_sender(), *message.get_recipient()]) |
| 122 | .filter(|id| seen.insert(id.key().to_string())) |
| 123 | .collect(); |
| 124 | let users = crate::service::user::list_by_ids(db, &ids).await?; |
| 125 | Ok(people_of(&users)) |
| 126 | } |
| 127 | |
| 128 | impl MessageResponse { |
| 129 | fn new(message: &Message, caller: &UserId, people: &People) -> Self { |
| 130 | let resolve = |id: &UserId| match people.get(id.key().as_str()) { |
| 131 | Some((person, role)) => (person.clone(), Some(*role)), |
| 132 | None => ( |
| 133 | PersonRef { |
| 134 | id: id.key().to_string(), |
| 135 | username: id.key().to_string(), |
| 136 | display_name: None, |
| 137 | student_number: None, |
| 138 | }, |
| 139 | None, |
| 140 | ), |
| 141 | }; |
| 142 | let (sender, sender_role) = resolve(message.get_sender()); |
| 143 | let (recipient, recipient_role) = resolve(message.get_recipient()); |
| 144 | Self { |
| 145 | id: message.get_id().key().to_string(), |
| 146 | sender, |
| 147 | sender_role, |
| 148 | recipient, |
| 149 | recipient_role, |
| 150 | subject: message.get_subject().as_str().to_string(), |
| 151 | body: message.get_body().as_str().to_string(), |
| 152 | label: message.get_label().map(|label| label.as_str().to_string()), |
| 153 | sent_at: message.get_sent_at().as_millis(), |
| 154 | read: message.is_read(), |
| 155 | folder: message.folder_of(caller).as_str().to_string(), |
| 156 | previous_folder: message |
| 157 | .origin_of(caller) |
| 158 | .map(|folder| folder.as_str().to_string()), |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | |
| 164 | |
| 165 | |
| 166 | |
| 167 | |
| 168 | #[utoipa::path( |
| 169 | post, |
| 170 | path = "/", |
| 171 | tag = "messages", |
| 172 | security(("session_cookie" = [])), |
| 173 | request_body = SendMessage, |
| 174 | responses( |
| 175 | (status = 201, description = "Message sent", body = MessageResponse), |
| 176 | (status = 400, description = "Invalid subject or body, or the recipient is yourself", body = ErrorResponse), |
| 177 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 178 | (status = 403, description = "A student or parent wrote to someone who is not staff", body = ErrorResponse), |
| 179 | (status = 404, description = "No such recipient", body = ErrorResponse), |
| 180 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 181 | ), |
| 182 | )] |
| 183 | async fn send_message( |
| 184 | State(st): State<AppState>, |
| 185 | CurrentUser(user): CurrentUser, |
| 186 | Json(req): Json<SendMessage>, |
| 187 | ) -> Result<(StatusCode, Json<MessageResponse>), AppError> { |
| 188 | let subject = MessageSubject::try_new(&req.subject)?; |
| 189 | let body = MessageBody::try_new(&req.body.unwrap_or_default())?; |
| 190 | |
| 191 | |
| 192 | let label = match req.label.as_deref().map(str::trim).unwrap_or_default() { |
| 193 | "" => None, |
| 194 | value => Some(MessageLabel::try_new(value)?), |
| 195 | }; |
| 196 | if req.recipient_id == user.get_id().key() { |
| 197 | return Err(AppError::Validation(ValidationError::Invalid { |
| 198 | field: "recipient_id", |
| 199 | reason: "cannot message yourself", |
| 200 | })); |
| 201 | } |
| 202 | let recipient = crate::service::user::read(&st.db, &UserId::from_key(&req.recipient_id)) |
| 203 | .await? |
| 204 | .ok_or(AppError::NotFound)?; |
| 205 | if !user.get_role().may_message(recipient.get_role()) { |
| 206 | return Err(AppError::Forbidden( |
| 207 | "students and parents may only message staff (teacher or higher)", |
| 208 | )); |
| 209 | } |
| 210 | |
| 211 | let message = message::send( |
| 212 | &st.db, |
| 213 | user.get_id(), |
| 214 | recipient.get_id(), |
| 215 | subject, |
| 216 | body, |
| 217 | label, |
| 218 | ) |
| 219 | .await?; |
| 220 | let people = people_of([&user, &recipient]); |
| 221 | let response = MessageResponse::new(&message, user.get_id(), &people); |
| 222 | Ok((StatusCode::CREATED, Json(response))) |
| 223 | } |
| 224 | |
| 225 | |
| 226 | |
| 227 | |
| 228 | |
| 229 | |
| 230 | |
| 231 | |
| 232 | |
| 233 | |
| 234 | #[utoipa::path( |
| 235 | get, |
| 236 | path = "/", |
| 237 | tag = "messages", |
| 238 | security(("session_cookie" = [])), |
| 239 | params(ListFilter, PageParams), |
| 240 | responses( |
| 241 | (status = 200, description = "A page of the folder's messages", body = Page<MessageResponse>), |
| 242 | (status = 400, description = "Unknown folder, or invalid limit or offset", body = ErrorResponse), |
| 243 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 244 | ), |
| 245 | )] |
| 246 | async fn list( |
| 247 | State(st): State<AppState>, |
| 248 | CurrentUser(user): CurrentUser, |
| 249 | Query(filter): Query<ListFilter>, |
| 250 | Query(page): Query<PageParams>, |
| 251 | ) -> Result<Json<Page<MessageResponse>>, AppError> { |
| 252 | let (limit, offset) = page.resolve()?; |
| 253 | let folder = match filter.folder { |
| 254 | Some(ref folder) => Folder::try_new(folder)?, |
| 255 | None => Folder::Inbox, |
| 256 | }; |
| 257 | |
| 258 | let (messages, total) = message::list_folder( |
| 259 | &st.db, |
| 260 | user.get_id(), |
| 261 | folder, |
| 262 | filter.read, |
| 263 | filter.q.as_deref(), |
| 264 | limit, |
| 265 | offset, |
| 266 | ) |
| 267 | .await?; |
| 268 | let people = load_people(&messages, &st.db).await?; |
| 269 | let items = messages |
| 270 | .iter() |
| 271 | .map(|message| MessageResponse::new(message, user.get_id(), &people)) |
| 272 | .collect(); |
| 273 | Ok(Json(Page::new(items, total, limit, offset))) |
| 274 | } |
| 275 | |
| 276 | |
| 277 | |
| 278 | |
| 279 | |
| 280 | |
| 281 | |
| 282 | |
| 283 | #[utoipa::path( |
| 284 | patch, |
| 285 | path = "/{id}", |
| 286 | tag = "messages", |
| 287 | security(("session_cookie" = [])), |
| 288 | params(("id" = String, Path, description = "Message id")), |
| 289 | request_body = UpdateMessage, |
| 290 | responses( |
| 291 | (status = 200, description = "The updated message", body = MessageResponse), |
| 292 | (status = 400, description = "A folder this side of the message cannot move to", body = ErrorResponse), |
| 293 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 294 | (status = 403, description = "Only the recipient can change the read flag", body = ErrorResponse), |
| 295 | (status = 404, description = "Not found (or not a party to it)", body = ErrorResponse), |
| 296 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 297 | ), |
| 298 | )] |
| 299 | async fn update_message( |
| 300 | State(st): State<AppState>, |
| 301 | CurrentUser(user): CurrentUser, |
| 302 | Path(id): Path<String>, |
| 303 | Json(req): Json<UpdateMessage>, |
| 304 | ) -> Result<Json<MessageResponse>, AppError> { |
| 305 | let mut message = message::read_for(&st.db, &MessageId::from_key(&id), user.get_id()) |
| 306 | .await? |
| 307 | .ok_or(AppError::NotFound)?; |
| 308 | |
| 309 | |
| 310 | |
| 311 | if req.read.is_some() && message.is_sender(user.get_id()) { |
| 312 | return Err(AppError::Forbidden( |
| 313 | "only the recipient can change the read flag", |
| 314 | )); |
| 315 | } |
| 316 | let folder = match req.folder { |
| 317 | Some(ref folder) => { |
| 318 | let folder = Folder::try_new(folder)?; |
| 319 | if !Folder::allowed_for(message.is_sender(user.get_id())).contains(&folder) { |
| 320 | return Err(AppError::Validation(ValidationError::Invalid { |
| 321 | field: "folder", |
| 322 | reason: "not a folder this side of the message can move to", |
| 323 | })); |
| 324 | } |
| 325 | Some(folder) |
| 326 | } |
| 327 | None => None, |
| 328 | }; |
| 329 | if let Some(read) = req.read { |
| 330 | message = message::set_read(&st.db, message, read).await?; |
| 331 | } |
| 332 | if let Some(folder) = folder { |
| 333 | message = message::move_to(&st.db, message, user.get_id(), folder).await?; |
| 334 | } |
| 335 | |
| 336 | let people = load_people(std::slice::from_ref(&message), &st.db).await?; |
| 337 | Ok(Json(MessageResponse::new(&message, user.get_id(), &people))) |
| 338 | } |
| 339 | |
| 340 | |
| 341 | |
| 342 | |
| 343 | #[utoipa::path( |
| 344 | delete, |
| 345 | path = "/{id}", |
| 346 | tag = "messages", |
| 347 | security(("session_cookie" = [])), |
| 348 | params(("id" = String, Path, description = "Message id")), |
| 349 | responses( |
| 350 | (status = 204, description = "Deleted for the caller"), |
| 351 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 352 | (status = 404, description = "Not found (or not a party to it)", body = ErrorResponse), |
| 353 | (status = 409, description = "The message is not in the caller's trash", body = ErrorResponse), |
| 354 | ), |
| 355 | )] |
| 356 | async fn delete_message( |
| 357 | State(st): State<AppState>, |
| 358 | CurrentUser(user): CurrentUser, |
| 359 | Path(id): Path<String>, |
| 360 | ) -> Result<StatusCode, AppError> { |
| 361 | let message = message::read_for(&st.db, &MessageId::from_key(&id), user.get_id()) |
| 362 | .await? |
| 363 | .ok_or(AppError::NotFound)?; |
| 364 | message::delete_for(&st.db, message, user.get_id()).await?; |
| 365 | Ok(StatusCode::NO_CONTENT) |
| 366 | } |