Files
sorsfonalak/services/forum/src/routes/messages.rs
T

518 lines
19 KiB
Rust
Raw Normal View History

//! Private messages. Nobody can just write to someone: first a request with
//! a short introduction (from the Kereső rank, after writing in public; at
//! most a few a day), which the recipient accepts, declines (silently: the
//! sender keeps seeing "sent" until it expires) or blocks. Then one-to-one
//! text. Moderators never read conversations, only a reported message.
use axum::Json;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum_extra::extract::WithRejection;
use serde::Deserialize;
use serde_json::{Value, json};
use sqlx::PgPool;
use time::OffsetDateTime;
use uuid::Uuid;
use super::{Body, IdPath, St, authors, rfc3339};
use crate::auth::{Member, Viewer};
use crate::error::{ApiError, ApiResult};
use crate::text;
/// A request not answered in this many days expires.
const REQUEST_DAYS: i64 = 14;
/// After a decline (or an expired request) a new request may come this much later.
const RETRY_DAYS: i64 = 30;
/// New requests one member may send in 24 hours.
const REQUESTS_PER_DAY: i64 = 3;
const INTRO_MIN: usize = 3;
const INTRO_MAX: usize = 200;
const MESSAGE_MAX: usize = 4000;
/// Messages one member may send in 24 hours (all conversations).
const MESSAGES_PER_DAY: i64 = 300;
/// Messages shown in a conversation.
const MESSAGES_SHOWN: i64 = 200;
#[derive(Debug, Clone, sqlx::FromRow)]
struct Conversation {
id: i64,
user_a: Uuid,
user_b: Uuid,
requested_by: Uuid,
intro: String,
status: String,
blocked_by: Option<Uuid>,
created_at: OffsetDateTime,
responded_at: Option<OffsetDateTime>,
last_message_at: Option<OffsetDateTime>,
}
const CONVERSATION_COLUMNS: &str =
"id, user_a, user_b, requested_by, intro, status, blocked_by, created_at, responded_at, last_message_at";
impl Conversation {
fn other(&self, me: Uuid) -> Uuid {
if self.user_a == me { self.user_b } else { self.user_a }
}
fn expired(&self, now: OffsetDateTime) -> bool {
now - self.created_at > time::Duration::days(REQUEST_DAYS)
}
/// How the conversation looks to `me`. A decline, or a block by the
/// other, looks like a request still waiting (then expired).
fn state_for(&self, me: Uuid, now: OffsetDateTime) -> &'static str {
match self.status.as_str() {
"accepted" => "accepted",
"blocked" if self.blocked_by == Some(me) => "blocked_by_me",
_ if self.requested_by == me => {
if self.expired(now) {
"expired"
} else {
"outgoing"
}
}
"pending" if !self.expired(now) => "incoming",
_ => "closed",
}
}
}
fn pair(a: Uuid, b: Uuid) -> (Uuid, Uuid) {
if a < b { (a, b) } else { (b, a) }
}
/// Whether a member may start conversations: any member for now, from the
/// first day (the user decided on 2026-11-26; a newcomers' limit, such as the
/// Kereső rank, may come back later here).
fn may_request(_viewer: &Viewer, _member: &Member) -> bool {
true
}
/// The viewer's relation to another member, for the profile page.
pub async fn relation(db: &PgPool, viewer: &Viewer, other: Uuid) -> ApiResult<Value> {
let Some(member) = &viewer.member else { return Ok(Value::Null) };
if member.user_id == other {
return Ok(Value::Null);
}
let (a, b) = pair(member.user_id, other);
let conversation: Option<Conversation> = sqlx::query_as(&format!(
"SELECT {CONVERSATION_COLUMNS} FROM forum.conversations WHERE user_a = $1 AND user_b = $2"
))
.bind(a)
.bind(b)
.fetch_optional(db)
.await?;
let now = OffsetDateTime::now_utc();
let state = conversation.as_ref().map(|c| c.state_for(member.user_id, now));
let can_request =
!member.banned(now) && may_request(viewer, member) && matches!(state, None | Some("expired") | Some("closed"));
Ok(json!({
"conversation_id": conversation.as_ref().map(|c| c.id),
"state": state,
"can_request": can_request,
"eligible": may_request(viewer, member),
}))
}
fn intro_text(raw: &str) -> ApiResult<String> {
let intro: String = raw.split_whitespace().collect::<Vec<_>>().join(" ");
let len = intro.chars().count();
if !(INTRO_MIN..=INTRO_MAX).contains(&len) {
return Err(ApiError::bad(format!("A bemutatkozás {INTRO_MIN}–{INTRO_MAX} karakter legyen.")));
}
let lower = intro.to_lowercase();
if lower.contains("http") || lower.contains("www.") {
return Err(ApiError::bad("A kérésbe nem tehetsz linket."));
}
text::body(&intro)
}
#[derive(Deserialize)]
pub struct NewRequest {
/// The other member's nickname.
to: String,
intro: String,
}
/// Sends a conversation request.
pub async fn request(
State(state): St,
viewer: Viewer,
WithRejection(Json(req), _): Body<NewRequest>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let me = viewer.require_writer()?;
if !may_request(&viewer, me) {
return Err(ApiError::Forbidden(
"Most nem kezdeményezhetsz beszélgetést. A neked küldött kéréseket elfogadhatod.".into(),
));
}
let other: Uuid = sqlx::query_scalar("SELECT user_id FROM forum.members WHERE nickname_key = $1")
.bind(text::nickname_key(&req.to))
.fetch_optional(&state.db)
.await?
.ok_or(ApiError::NotFound("member"))?;
if other == me.user_id {
return Err(ApiError::bad("Magaddal nem kezdeményezhetsz beszélgetést."));
}
let intro = intro_text(&req.intro)?;
let sent_today: i64 = sqlx::query_scalar(
"SELECT count(*) FROM forum.conversations WHERE requested_by = $1 AND created_at > now() - interval '24 hours'",
)
.bind(me.user_id)
.fetch_one(&state.db)
.await?;
if sent_today >= REQUESTS_PER_DAY && !viewer.is_moderator() {
return Err(ApiError::Limited(format!("Naponta legfeljebb {REQUESTS_PER_DAY} kérést küldhetsz.")));
}
let (a, b) = pair(me.user_id, other);
let now = OffsetDateTime::now_utc();
let mut tx = state.db.begin().await?;
let existing: Option<Conversation> = sqlx::query_as(&format!(
"SELECT {CONVERSATION_COLUMNS} FROM forum.conversations WHERE user_a = $1 AND user_b = $2 FOR UPDATE"
))
.bind(a)
.bind(b)
.fetch_optional(&mut *tx)
.await?;
let waiting = || ApiError::conflict("request_pending", "Már elküldted a kérésedet.");
let id = match existing {
None => {
sqlx::query_scalar(
"INSERT INTO forum.conversations (user_a, user_b, requested_by, intro) VALUES ($1, $2, $3, $4) RETURNING id",
)
.bind(a)
.bind(b)
.bind(me.user_id)
.bind(&intro)
.fetch_one(&mut *tx)
.await?
}
Some(c) => {
match c.state_for(me.user_id, now) {
"accepted" => return Err(ApiError::conflict("conversation_open", "Már beszélgettek.")),
"incoming" => {
return Err(ApiError::conflict("request_incoming", "Ő már küldött neked kérést: nézd meg az üzeneteidnél."));
}
"blocked_by_me" => {
return Err(ApiError::conflict("blocked", "Letiltottad őt. Előbb oldd fel a tiltást az üzeneteidnél."));
}
"outgoing" => return Err(waiting()),
_ => {}
}
// Blocked by the other: looks like a request still waiting.
if c.status == "blocked" {
return Err(waiting());
}
// After one's own declined or expired request, a new one only
// after a while (the one who declined may write at once).
let since = c.responded_at.unwrap_or(c.created_at);
if c.requested_by == me.user_id && now - since < time::Duration::days(RETRY_DAYS) {
return Err(waiting());
}
sqlx::query(
"UPDATE forum.conversations SET requested_by = $2, intro = $3, status = 'pending', blocked_by = NULL, \
created_at = now(), responded_at = NULL WHERE id = $1",
)
.bind(c.id)
.bind(me.user_id)
.bind(&intro)
.execute(&mut *tx)
.await?;
c.id
}
};
tx.commit().await?;
crate::mail::after_message(&state, id, me.user_id, true, Some(&intro)).await;
2026-11-26 11:41:45 +00:00
crate::live::emit(
&state.db,
crate::live::Event { conversation: Some(id), ..Default::default() }.for_users(vec![other]),
)
.await;
Ok((StatusCode::CREATED, Json(json!({ "id": id }))))
}
/// A conversation of the viewer (any state), or 404.
async fn own(db: &PgPool, me: Uuid, id: i64) -> ApiResult<Conversation> {
sqlx::query_as(&format!(
"SELECT {CONVERSATION_COLUMNS} FROM forum.conversations WHERE id = $1 AND $2 IN (user_a, user_b)"
))
.bind(id)
.bind(me)
.fetch_optional(db)
.await?
.ok_or(ApiError::NotFound("conversation"))
}
#[derive(sqlx::FromRow)]
struct LastMessage {
conversation_id: i64,
sender_id: Option<Uuid>,
body: String,
}
/// The viewer's conversations and requests, and how many messages are unread.
pub async fn list(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
let me = viewer.require_member()?.user_id;
let rows: Vec<Conversation> = sqlx::query_as(&format!(
"SELECT {CONVERSATION_COLUMNS} FROM forum.conversations WHERE $1 IN (user_a, user_b) \
ORDER BY COALESCE(last_message_at, created_at) DESC LIMIT 200"
))
.bind(me)
.fetch_all(&state.db)
.await?;
let ids: Vec<i64> = rows.iter().map(|c| c.id).collect();
let last: Vec<LastMessage> = sqlx::query_as(
"SELECT DISTINCT ON (conversation_id) conversation_id, sender_id, left(body, 120) AS body \
FROM forum.messages WHERE conversation_id = ANY($1) ORDER BY conversation_id, id DESC",
)
.bind(&ids)
.fetch_all(&state.db)
.await?;
let unread: Vec<(i64, i64)> = sqlx::query_as(
"SELECT m.conversation_id, count(*) FROM forum.messages m \
WHERE m.conversation_id = ANY($1) AND m.sender_id IS DISTINCT FROM $2 \
AND m.id > COALESCE((SELECT r.last_message_id FROM forum.conversation_reads r \
WHERE r.conversation_id = m.conversation_id AND r.user_id = $2), 0) \
GROUP BY 1",
)
.bind(&ids)
.bind(me)
.fetch_all(&state.db)
.await?;
let people = authors(&state.db, rows.iter().map(|c| c.other(me))).await?;
let now = OffsetDateTime::now_utc();
let items: Vec<Value> = rows
.iter()
.filter_map(|c| {
let state = c.state_for(me, now);
if state == "closed" {
return None;
}
let last = last.iter().find(|l| l.conversation_id == c.id);
Some(json!({
"id": c.id,
"other": people.get(&c.other(me)),
"state": state,
"intro": c.intro,
"created_at": rfc3339(c.created_at),
"last_message_at": c.last_message_at.map(rfc3339),
"last_message": last.map(|l| json!({ "excerpt": l.body, "mine": l.sender_id == Some(me) })),
"unread": unread.iter().find(|(id, _)| *id == c.id).map(|(_, n)| *n).unwrap_or(0),
}))
})
.collect();
Ok(Json(json!({ "conversations": items })))
}
/// Unread messages and requests waiting for an answer (the menu's badge).
pub async fn unread_count(db: &PgPool, me: Uuid) -> Result<i64, sqlx::Error> {
sqlx::query_scalar(
"SELECT (SELECT count(*) FROM forum.messages m JOIN forum.conversations c ON c.id = m.conversation_id \
WHERE $1 IN (c.user_a, c.user_b) AND c.status = 'accepted' AND m.sender_id IS DISTINCT FROM $1 \
AND m.id > COALESCE((SELECT r.last_message_id FROM forum.conversation_reads r \
WHERE r.conversation_id = c.id AND r.user_id = $1), 0)) \
+ (SELECT count(*) FROM forum.conversations c \
WHERE $1 IN (c.user_a, c.user_b) AND c.status = 'pending' AND c.requested_by <> $1 \
AND c.created_at > now() - make_interval(days => $2))",
)
.bind(me)
.bind(REQUEST_DAYS as i32)
.fetch_one(db)
.await
}
/// One conversation: the request, and the messages once accepted.
pub async fn show(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<Json<Value>> {
let me = viewer.require_member()?.user_id;
let c = own(&state.db, me, id).await?;
let now = OffsetDateTime::now_utc();
let conversation_state = c.state_for(me, now);
if conversation_state == "closed" {
return Err(ApiError::NotFound("conversation"));
}
let messages: Vec<(i64, Option<Uuid>, String, OffsetDateTime)> =
if c.status == "accepted" || conversation_state == "blocked_by_me" {
sqlx::query_as(
"SELECT id, sender_id, body, created_at FROM \
(SELECT id, sender_id, body, created_at FROM forum.messages WHERE conversation_id = $1 \
ORDER BY id DESC LIMIT $2) recent ORDER BY id",
)
.bind(id)
.bind(MESSAGES_SHOWN)
.fetch_all(&state.db)
.await?
} else {
Vec::new()
};
let people = authors(&state.db, [c.other(me)]).await?;
Ok(Json(json!({
"viewer": super::home::viewer_json(&viewer),
"conversation": {
"id": c.id,
"other": people.get(&c.other(me)),
"state": conversation_state,
"intro": c.intro,
"requested_by_me": c.requested_by == me,
"created_at": rfc3339(c.created_at),
},
"messages": messages.into_iter().map(|(id, sender, body, at)| json!({
"id": id, "mine": sender == Some(me), "body": body, "created_at": rfc3339(at),
})).collect::<Vec<_>>(),
})))
}
/// The recipient answers a request: accept, decline (silently) or block.
pub async fn respond(state: St, viewer: Viewer, path: IdPath, answer: &'static str) -> ApiResult<StatusCode> {
let State(state) = state;
let WithRejection(Path(id), _) = path;
let me = viewer.require_member()?.user_id;
let c = own(&state.db, me, id).await?;
let now = OffsetDateTime::now_utc();
match answer {
"block" => {
sqlx::query(
"UPDATE forum.conversations SET status = 'blocked', blocked_by = $2, responded_at = now() WHERE id = $1",
)
.bind(id)
.bind(me)
.execute(&state.db)
.await?;
}
"unblock" => {
if c.blocked_by != Some(me) {
return Err(ApiError::bad("Ezt a tiltást nem te állítottad be."));
}
sqlx::query(
"UPDATE forum.conversations SET status = 'declined', blocked_by = NULL, responded_at = now() WHERE id = $1",
)
.bind(id)
.execute(&state.db)
.await?;
}
_ => {
if c.state_for(me, now) != "incoming" {
return Err(ApiError::bad("Erre a kérésre már nem lehet válaszolni."));
}
let status = if answer == "accept" { "accepted" } else { "declined" };
sqlx::query("UPDATE forum.conversations SET status = $2, responded_at = now() WHERE id = $1")
.bind(id)
.bind(status)
.execute(&state.db)
.await?;
}
}
2026-11-26 11:41:45 +00:00
let event = crate::live::Event { conversation: Some(id), ..Default::default() }.for_users(vec![c.other(me), me]);
crate::live::emit(&state.db, event).await;
Ok(StatusCode::NO_CONTENT)
}
pub async fn accept(state: St, viewer: Viewer, path: IdPath) -> ApiResult<StatusCode> {
respond(state, viewer, path, "accept").await
}
pub async fn decline(state: St, viewer: Viewer, path: IdPath) -> ApiResult<StatusCode> {
respond(state, viewer, path, "decline").await
}
pub async fn block(state: St, viewer: Viewer, path: IdPath) -> ApiResult<StatusCode> {
respond(state, viewer, path, "block").await
}
pub async fn unblock(state: St, viewer: Viewer, path: IdPath) -> ApiResult<StatusCode> {
respond(state, viewer, path, "unblock").await
}
#[derive(Deserialize)]
pub struct NewMessage {
body: String,
}
/// A message in an accepted conversation.
pub async fn send(
State(state): St,
viewer: Viewer,
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<NewMessage>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let me = viewer.require_writer()?.user_id;
let c = own(&state.db, me, id).await?;
if c.status != "accepted" {
return Err(ApiError::Forbidden("Ebben a beszélgetésben most nem lehet írni.".into()));
}
let body = text::body(&req.body)?;
if body.chars().count() > MESSAGE_MAX {
return Err(ApiError::bad(format!("Az üzenet legfeljebb {MESSAGE_MAX} karakter lehet.")));
}
let today: i64 = sqlx::query_scalar(
"SELECT count(*) FROM forum.messages WHERE sender_id = $1 AND created_at > now() - interval '24 hours'",
)
.bind(me)
.fetch_one(&state.db)
.await?;
if today >= MESSAGES_PER_DAY {
return Err(ApiError::Limited("Ma már nagyon sok üzenetet küldtél. Holnap folytathatod.".into()));
}
let mut tx = state.db.begin().await?;
let (message_id, created_at): (i64, OffsetDateTime) = sqlx::query_as(
"INSERT INTO forum.messages (conversation_id, sender_id, body) VALUES ($1, $2, $3) RETURNING id, created_at",
)
.bind(id)
.bind(me)
.bind(&body)
.fetch_one(&mut *tx)
.await?;
sqlx::query("UPDATE forum.conversations SET last_message_at = now() WHERE id = $1")
.bind(id)
.execute(&mut *tx)
.await?;
mark(&mut *tx, id, me, message_id).await?;
tx.commit().await?;
crate::mail::after_message(&state, id, me, false, None).await;
2026-11-26 11:41:45 +00:00
let event = crate::live::Event { conversation: Some(id), ..Default::default() }.for_users(vec![c.other(me)]);
crate::live::emit(&state.db, event).await;
Ok((
StatusCode::CREATED,
Json(json!({ "id": message_id, "mine": true, "body": body, "created_at": rfc3339(created_at) })),
))
}
async fn mark(db: impl sqlx::PgExecutor<'_>, conversation: i64, user: Uuid, message: i64) -> Result<(), sqlx::Error> {
sqlx::query(
"INSERT INTO forum.conversation_reads (conversation_id, user_id, last_message_id) VALUES ($1, $2, $3) \
ON CONFLICT (conversation_id, user_id) DO UPDATE \
SET last_message_id = GREATEST(forum.conversation_reads.last_message_id, EXCLUDED.last_message_id)",
)
.bind(conversation)
.bind(user)
.bind(message)
.execute(db)
.await?;
Ok(())
}
#[derive(Deserialize)]
pub struct ReadMark {
message_id: i64,
}
/// Read up to that message. No read receipts: the other never sees this.
pub async fn read(
State(state): St,
viewer: Viewer,
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<ReadMark>,
) -> ApiResult<StatusCode> {
let me = viewer.require_member()?.user_id;
own(&state.db, me, id).await?;
let last: Option<i64> = sqlx::query_scalar("SELECT max(id) FROM forum.messages WHERE conversation_id = $1")
.bind(id)
.fetch_one(&state.db)
.await?;
if let Some(last) = last {
mark(&state.db, id, me, req.message_id.min(last)).await?;
}
Ok(StatusCode::NO_CONTENT)
}