forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

messages.rs366 lines, 14.1 KiBHistoryRawDownload
1use std::collections::{HashMap, HashSet};
2
3use crate::web::tenant_state::State;
4use axum::Json;
5use axum::extract::{Path, Query};
6use axum::http::StatusCode;
7use serde::{Deserialize, Serialize};
8use utoipa::{IntoParams, ToSchema};
9use utoipa_axum::router::OpenApiRouter;
10use utoipa_axum::routes;
11
12use crate::database::Database;
13use crate::domain::message::{
14 Folder, Message, MessageBody, MessageId, MessageLabel, MessageSubject,
15};
16use crate::domain::user::{User, UserId};
17use crate::error::{AppError, ErrorResponse, ValidationError};
18use crate::service::message;
19use crate::state::AppState;
20
21use super::dto::Role;
22use super::{CurrentUser, Page, PageParams, PersonRef};
23
24pub 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)]
31struct SendMessage {
32 /// The receiving user's id (find people via `GET /users/search`).
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 /// Optional free-text tag the UI shows as a badge ("Study", "Exam", …).
40 /// Blank counts as absent.
41 #[schema(example = "Etüt", max_length = 50)]
42 label: Option<String>,
43}
44
45#[derive(Deserialize, ToSchema)]
46struct UpdateMessage {
47 /// Mark read (`true`) or unread (`false`). Recipient only.
48 read: Option<bool>,
49 /// Move the caller's copy: a recipient may file into `inbox`, `archive`,
50 /// or `trash`; a sender into `sent`, `archive`, or `trash`. Restoring is
51 /// moving back to the copy's `previous_folder`.
52 #[schema(example = "archive")]
53 folder: Option<String>,
54}
55
56#[derive(Deserialize, IntoParams)]
57struct ListFilter {
58 /// Which folder to list: `inbox` (default), `sent`, `archive`, or `trash`.
59 #[param(example = "inbox")]
60 folder: Option<String>,
61 /// Narrow by the read flag: `false` = unread only (so
62 /// `?folder=inbox&read=false&limit=1` makes `total` the unread badge),
63 /// `true` = read only. Omit for both.
64 read: Option<bool>,
65 /// Free-text search over each message's subject and body: a case- and
66 /// diacritic-insensitive substring (`etut` finds `Etüt`). Literal text —
67 /// `%` and `_` carry no special meaning. Blank means no search.
68 #[param(example = "etüt")]
69 q: Option<String>,
70}
71
72/// A message as one party sees it. `folder` is the *caller's* copy's folder;
73/// `read` is the recipient's flag (senders see it as a read receipt). The
74/// `*_role` fields are `null` only when that account has since been deleted.
75#[derive(Serialize, ToSchema)]
76struct 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 /// The sender's badge tag, if they set one.
85 #[schema(example = "Etüt")]
86 label: Option<String>,
87 /// When it was sent, UTC unix-milliseconds (server-stamped).
88 sent_at: i64,
89 read: bool,
90 #[schema(example = "inbox")]
91 folder: String,
92 /// Where the caller's copy sat before it was filed into `archive`/`trash`
93 /// — `PATCH` `folder` back to this to restore it. `null` whenever the copy
94 /// is not filed away, and on copies filed before this was recorded; both
95 /// mean "restore to `inbox`" (`sent` for the sender's copy).
96 #[schema(example = "inbox")]
97 previous_folder: Option<String>,
98}
99
100/// `PersonRef` plus role, keyed by user id — messages show *who* wrote and
101/// their role badge, so the plain `person_map` isn't enough.
102type People = HashMap<String, (PersonRef, Role)>;
103
104fn 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/// Load the two ends of every listed message into a `People` map, one query.
117async 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
128impl 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/// Send a message to another user. Messaging is upward only below staff: a
164/// student or parent may write to a teacher, manager or admin (parents
165/// included — messaging is the one place a parent acts), never to another
166/// student or parent; staff write to anyone. Messaging yourself is refused.
167/// The send is server-stamped and lands in the recipient's inbox unread.
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)]
183async 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 // A blank label is "no label", not an error — the field is a badge, and
191 // an empty badge means the sender just didn't pick one.
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/// List one of the caller's folders, newest first: `inbox` (default),
226/// `sent`, `archive`, or `trash` (`?folder=`). `?read=` narrows by the read
227/// flag; `total` counts the filtered folder, so
228/// `?folder=inbox&read=false&limit=1` is a cheap unread badge. Paged via
229/// `?limit=&offset=`.
230///
231/// `?q=` narrows further by free text: a case- and diacritic-insensitive
232/// substring of each message's subject or body, composed with `folder` and
233/// `read`; `total` counts the matches. Blank means no search.
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)]
246async 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/// Update the caller's view of a message: flip the read flag (recipient
277/// only) and/or move the caller's copy between folders. Each side files
278/// independently — archiving or trashing never touches the other party's
279/// copy. Filing into `archive`/`trash` records the folder left behind as the
280/// copy's `previous_folder`, so restoring is a move back to that value
281/// (`inbox`, or `sent` for the sender's copy, when it is `null`). Omitted
282/// fields change nothing.
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)]
299async 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 // Validate the whole patch before touching the row: a rejected folder
310 // must not leave a half-applied read flag behind.
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/// Permanently delete the caller's copy — allowed only from the trash
341/// (`PATCH` it to `folder: "trash"` first). The other party's copy lives on;
342/// the row disappears for good once both sides have deleted theirs.
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)]
356async 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}