//! Members: one's own forum profile (nickname first), the nickname check //! while typing, the online heartbeat, and a member's public profile. use axum::Json; use axum::extract::{Path, Query, State}; use axum::http::StatusCode; use axum_extra::extract::WithRejection; use serde::Deserialize; use serde_json::{Value, json}; use time::OffsetDateTime; use uuid::Uuid; use super::home::viewer_json; use super::{Body, St, authors, online, rfc3339, shared_signs, visible_topics}; use crate::auth::{self, Viewer}; use crate::error::{ApiError, ApiResult}; use crate::text; /// The first this many members get the "Alapító tag" badge for good. pub const FOUNDERS: i64 = 15; /// A nickname may change once in this many days (spelling fixes that keep the /// same folded form any time). const NICKNAME_CHANGE_DAYS: i64 = 30; /// A nickname given up stays reserved this long. const NICKNAME_RESERVED_DAYS: i64 = 90; /// The viewer's own forum profile, and what each chart sharing level would show. pub async fn me(State(state): St, viewer: Viewer) -> ApiResult> { let user = viewer.require_user()?; let now = OffsetDateTime::now_utc(); let member = viewer.member.as_ref().map(|m| { let rank = m.rank(now); let change_after = m.nickname_changed_at + time::Duration::days(NICKNAME_CHANGE_DAYS); json!({ "nickname": m.nickname, "avatar": m.avatar, "bio": m.bio, "chart_share": m.chart_share, "invisible": m.invisible, "points": m.points, "post_count": m.post_count, "created_at": rfc3339(m.created_at), "rank": rank, "rank_name": rank.name(), "next_rank": rank.next().map(|(r, points, days)| json!({ "rank": r, "name": r.name(), "points": points, "days": days, })), "nickname_change_after": (change_after > now).then(|| rfc3339(change_after)), "banned_until": m.banned_until.filter(|u| *u > now).map(|u| { if u.year() >= 9999 { "infinity".to_string() } else { rfc3339(u) } }), "ban_reason": m.ban_reason.as_ref().filter(|_| m.banned(now)), "email": { "replies": m.email_replies, "followed": m.email_followed, "messages": m.email_messages, "mentions": m.email_mentions, "listener": m.email_listener, "weekly": m.email_weekly, }, "listener": m.listener, "supporter_badge": m.supporter_badge, // From the Kereső rank: volunteering as a companion. An own picture: anyone. "can_listen": viewer.is_moderator() || !rank.is_newcomer(), "can_upload_avatar": true, }) }); let buyer = super::has_purchase(&state.db, user.id).await?; let signs = shared_signs(&state.db, &[user.id]).await?.remove(&user.id); let chart = signs.map(|s| json!({ "sun": s.share("sun"), "big3": s.share("big3"), "planets": s.share("planets") })); Ok(Json(json!({ "viewer": viewer_json(&viewer), "member": member, "chart": chart, "can_supporter": buyer }))) } #[derive(Deserialize)] pub struct SaveMe { nickname: String, #[serde(default)] avatar: Option, #[serde(default)] bio: Option, #[serde(default)] chart_share: Option, #[serde(default)] invisible: Option, /// E-mail notifications: `{"replies": "off|daily|instant", "followed": "off|daily", "messages": "off|instant"}`. #[serde(default)] email: Option, /// Volunteering as a listener (from the Kereső rank). #[serde(default)] listener: Option, /// Showing the "Támogató" badge (buyers only). #[serde(default)] supporter_badge: Option, } #[derive(Deserialize)] pub struct EmailSettings { #[serde(default)] replies: Option, #[serde(default)] followed: Option, #[serde(default)] messages: Option, #[serde(default)] mentions: Option, #[serde(default)] listener: Option, #[serde(default)] weekly: Option, } fn one_of(value: Option<&str>, allowed: &[&str]) -> ApiResult> { match value { None => Ok(None), Some(v) if allowed.contains(&v) => Ok(Some(v.to_string())), Some(_) => Err(ApiError::bad("Ismeretlen értesítési beállítás.")), } } /// Whether someone else has (or recently had) this folded nickname. async fn nickname_taken(db: &sqlx::PgPool, key: &str, me: Uuid) -> Result { sqlx::query_scalar( "SELECT EXISTS (SELECT 1 FROM forum.members WHERE nickname_key = $1 AND user_id <> $2) \ OR EXISTS (SELECT 1 FROM forum.retired_nicknames \ WHERE nickname_key = $1 AND user_id <> $2 AND until > now())", ) .bind(key) .bind(me) .fetch_one(db) .await } fn taken() -> ApiError { ApiError::conflict("nickname_taken", "Ezt az álnevet már más használja. Válassz másikat.") } /// Creates the forum profile (choosing a nickname is the first step) or changes it. pub async fn save_me( State(state): St, viewer: Viewer, WithRejection(Json(req), _): Body, ) -> ApiResult> { let user = viewer.require_user()?; let nickname = text::nickname(&req.nickname)?; let key = text::nickname_key(&nickname); // The current avatar sent back unchanged (an own picture too) is no change. let current = viewer.member.as_ref().map(|m| m.avatar.as_str()); let avatar = match req.avatar.as_deref() { Some(a) if Some(a) == current => None, other => other.map(text::avatar).transpose()?, }; let avatar_changed = avatar.is_some(); let bio = req.bio.as_deref().map(text::bio).transpose()?; let chart_share = match req.chart_share.as_deref() { None => None, Some(level @ ("none" | "sun" | "big3" | "planets")) => Some(level.to_string()), Some(_) => return Err(ApiError::bad("Ismeretlen megosztási szint.")), }; let email = req.email.as_ref(); let email_replies = one_of(email.and_then(|e| e.replies.as_deref()), &["off", "daily", "instant"])?; let email_followed = one_of(email.and_then(|e| e.followed.as_deref()), &["off", "daily"])?; let email_messages = one_of(email.and_then(|e| e.messages.as_deref()), &["off", "instant"])?; let email_mentions = one_of(email.and_then(|e| e.mentions.as_deref()), &["off", "instant"])?; let email_listener = one_of(email.and_then(|e| e.listener.as_deref()), &["off", "instant"])?; let email_weekly = email.and_then(|e| e.weekly); if req.listener == Some(true) { let newcomer = viewer.member.as_ref().is_none_or(|m| m.rank(OffsetDateTime::now_utc()).is_newcomer()); if newcomer && !viewer.is_moderator() { return Err(ApiError::Forbidden("Kísérőnek a Kereső rangtól jelentkezhetsz.".into())); } } if req.supporter_badge == Some(true) && !super::has_purchase(&state.db, user.id).await? { return Err(ApiError::Forbidden("A Támogató jelvény a csomagot vásárlóké.".into())); } if nickname_taken(&state.db, &key, user.id).await? { return Err(taken()); } let now = OffsetDateTime::now_utc(); let mut tx = state.db.begin().await?; let result = match &viewer.member { None => { // One newcomer at a time, so the hundredth founder is the last. sqlx::query("SELECT pg_advisory_xact_lock(hashtext('forum_founders'))").execute(&mut *tx).await?; sqlx::query(&format!( "INSERT INTO forum.members (user_id, nickname, nickname_key, avatar, bio, chart_share, invisible, founder) \ VALUES ($1, $2, $3, $4, $5, $6, $7, (SELECT count(*) < {FOUNDERS} FROM forum.members WHERE founder))" )) .bind(user.id) .bind(&nickname) .bind(&key) .bind(avatar.unwrap_or_else(|| text::default_avatar(&key))) .bind(bio.unwrap_or_default()) .bind(chart_share.unwrap_or_else(|| "none".into())) .bind(req.invisible.unwrap_or(false)) .execute(&mut *tx) .await } Some(member) => { let old_key = text::nickname_key(&member.nickname); let renamed = old_key != key; if renamed { let allowed = member.nickname_changed_at + time::Duration::days(NICKNAME_CHANGE_DAYS); if allowed > now { return Err(ApiError::conflict( "nickname_too_soon", format!("Az álneved {NICKNAME_CHANGE_DAYS} naponta egyszer változtathatod meg."), )); } sqlx::query( "INSERT INTO forum.retired_nicknames (nickname_key, user_id, until) \ VALUES ($1, $2, now() + make_interval(days => $3)) \ ON CONFLICT (nickname_key) DO UPDATE SET user_id = EXCLUDED.user_id, until = EXCLUDED.until", ) .bind(&old_key) .bind(user.id) .bind(NICKNAME_RESERVED_DAYS as i32) .execute(&mut *tx) .await?; // Taking back one's own earlier name. sqlx::query("DELETE FROM forum.retired_nicknames WHERE nickname_key = $1 AND user_id = $2") .bind(&key) .bind(user.id) .execute(&mut *tx) .await?; } sqlx::query( "UPDATE forum.members SET nickname = $2, nickname_key = $3, \ avatar = COALESCE($4, avatar), bio = COALESCE($5, bio), \ chart_share = COALESCE($6, chart_share), invisible = COALESCE($7, invisible), \ nickname_changed_at = CASE WHEN $8 THEN now() ELSE nickname_changed_at END \ WHERE user_id = $1", ) .bind(user.id) .bind(&nickname) .bind(&key) .bind(avatar) .bind(bio) .bind(chart_share) .bind(req.invisible) .bind(renamed) .execute(&mut *tx) .await } }; match result { Ok(_) => {} // Someone took it in the same moment. Err(sqlx::Error::Database(e)) if e.is_unique_violation() => return Err(taken()), Err(e) => return Err(e.into()), } sqlx::query( "UPDATE forum.members SET email_replies = COALESCE($2, email_replies), \ email_followed = COALESCE($3, email_followed), email_messages = COALESCE($4, email_messages), \ email_mentions = COALESCE($5, email_mentions), email_listener = COALESCE($6, email_listener), \ email_weekly = COALESCE($7, email_weekly), listener = COALESCE($8, listener), \ supporter_badge = COALESCE($9, supporter_badge) \ WHERE user_id = $1", ) .bind(user.id) .bind(email_replies) .bind(email_followed) .bind(email_messages) .bind(email_mentions) .bind(email_listener) .bind(email_weekly) .bind(req.listener) .bind(req.supporter_badge) .execute(&mut *tx) .await?; tx.commit().await?; // A starter avatar chosen instead of an own picture: the picture goes. if let (Some(old), true) = (viewer.member.as_ref().map(|m| m.avatar.clone()), avatar_changed) { super::avatars::forget(&state, &old).await; } let viewer = Viewer { member: auth::load_member(&state.db, user.id).await?, ..viewer }; me(State(state), viewer).await } #[derive(Deserialize)] pub struct NameQuery { name: String, } /// While typing: is this nickname valid and free? pub async fn nickname_check( State(state): St, viewer: Viewer, WithRejection(Query(q), _): WithRejection, ApiError>, ) -> ApiResult> { let user = viewer.require_user()?; let nickname = match text::nickname(&q.name) { Ok(n) => n, Err(e) => return Ok(Json(json!({ "ok": false, "message": e.to_string() }))), }; if nickname_taken(&state.db, &text::nickname_key(&nickname), user.id).await? { return Ok(Json(json!({ "ok": false, "message": taken().to_string() }))); } Ok(Json(json!({ "ok": true, "nickname": nickname }))) } #[derive(Deserialize)] pub struct TokenQuery { token: String, } /// One click from a forum e-mail (its footer link, or the mail client's /// unsubscribe button, RFC 8058): every forum e-mail off, no login needed. pub async fn unsubscribe( State(state): St, WithRejection(Query(q), _): WithRejection, ApiError>, ) -> ApiResult> { let done = sqlx::query( "UPDATE forum.members SET email_replies = 'off', email_followed = 'off', email_messages = 'off', \ email_mentions = 'off', email_listener = 'off', email_weekly = false \ WHERE email_token = $1", ) .bind(q.token.trim()) .execute(&state.db) .await?; if done.rows_affected() == 0 { return Err(ApiError::NotFound("token")); } Ok(Json(json!({ "unsubscribed": true }))) } /// The page is open: keeps the online dot (the viewer extractor does the work). pub async fn presence(_viewer: Viewer) -> StatusCode { StatusCode::NO_CONTENT } #[derive(sqlx::FromRow)] struct ProfileRow { user_id: Uuid, bio: String, created_at: OffsetDateTime, post_count: i32, invisible: bool, last_seen_at: Option, banned_until: Option, ban_reason: Option, } #[derive(sqlx::FromRow)] struct RecentRow { id: i64, thread_id: i64, title: String, topic_slug: String, topic_name: String, created_at: OffsetDateTime, excerpt: String, is_opening: bool, } /// A member's public profile: nickname, avatar, rank, shared signs, bio, /// activity (coarsely), and recent posts from the topics the viewer may read. pub async fn profile( State(state): St, viewer: Viewer, WithRejection(Path(nickname), _): WithRejection, ApiError>, ) -> ApiResult> { let row: ProfileRow = sqlx::query_as( "SELECT user_id, bio, created_at, post_count, invisible, last_seen_at, banned_until, ban_reason \ FROM forum.members WHERE nickname_key = $1", ) .bind(text::nickname_key(&nickname)) .fetch_optional(&state.db) .await? .ok_or(ApiError::NotFound("member"))?; let brief = authors(&state.db, [row.user_id]).await?.remove(&row.user_id).ok_or(ApiError::NotFound("member"))?; let recent: Vec = sqlx::query_as(&format!( "SELECT p.id, p.thread_id, th.title, tp.slug AS topic_slug, tp.name AS topic_name, p.created_at, \ left(p.body, 200) AS excerpt, p.is_opening \ FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id JOIN forum.topics tp ON tp.id = th.topic_id \ WHERE p.author_id = $1 AND p.deleted_at IS NULL AND th.deleted_at IS NULL AND ({}) \ ORDER BY p.id DESC LIMIT 10", visible_topics(&viewer) )) .bind(row.user_id) .fetch_all(&state.db) .await?; let thread_count: i64 = sqlx::query_scalar("SELECT count(*) FROM forum.threads WHERE author_id = $1 AND deleted_at IS NULL") .bind(row.user_id) .fetch_one(&state.db) .await?; let now = OffsetDateTime::now_utc(); let own = viewer.user_id() == Some(row.user_id); let last_seen = if row.invisible && !own { None } else if online(false, row.last_seen_at, now) { Some("online") } else { row.last_seen_at.map(|t| match now - t { d if d < time::Duration::days(1) => "day", d if d < time::Duration::days(7) => "week", _ => "earlier", }) }; let banned = row.banned_until.filter(|u| *u > now); let show_ban = own || viewer.is_moderator(); Ok(Json(json!({ "viewer": viewer_json(&viewer), "member": { "author": brief, "bio": row.bio, "created_at": rfc3339(row.created_at), "post_count": row.post_count, "thread_count": thread_count, "last_seen": last_seen, "own": own, "muted": viewer.mutes.contains(&row.user_id), "banned_until": banned.filter(|_| show_ban).map(|u| { if u.year() >= 9999 { "infinity".to_string() } else { rfc3339(u) } }), "ban_reason": row.ban_reason.filter(|_| show_ban && banned.is_some()), }, "relation": super::messages::relation(&state.db, &viewer, row.user_id).await?, "recent": recent.into_iter().map(|r| json!({ "id": r.id, "thread_id": r.thread_id, "thread_slug": text::slug(&r.title), "thread_title": r.title, "topic": { "slug": r.topic_slug, "name": r.topic_name }, "created_at": rfc3339(r.created_at), "excerpt": r.excerpt, "is_opening": r.is_opening, })).collect::>(), }))) }