Merge the forum (community module) into main
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -11,6 +11,7 @@ db.workspace = true
|
||||
analysis-prompt.workspace = true
|
||||
email-templates.workspace = true
|
||||
gift-card.workspace = true
|
||||
object-storage.workspace = true
|
||||
hmac.workspace = true
|
||||
image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp"] }
|
||||
rand.workspace = true
|
||||
|
||||
@@ -179,6 +179,15 @@ pub async fn export(State(state): St, auth: AuthUser) -> ApiResult<impl IntoResp
|
||||
"questions": rows("SELECT json_build_object('id', q.id, 'analysis_id', q.analysis_id, 'question', q.question, 'status', q.status, 'answer', q.answer, 'created_at', q.created_at) FROM questions q WHERE q.asked_by = $1").await?,
|
||||
"credit_ledger": rows("SELECT json_build_object('unit', unit, 'delta', delta, 'reason', reason, 'note', note, 'created_at', created_at) FROM credit_ledger WHERE user_id = $1 ORDER BY created_at").await?,
|
||||
"shares": rows("SELECT json_build_object('slug', slug, 'kind', kind, 'title', title, 'show_birth_data', show_birth_data, 'view_count', view_count, 'created_at', created_at, 'revoked_at', revoked_at) FROM shares WHERE owner_id = $1").await?,
|
||||
// The forum (services/forum): what the user wrote and set there.
|
||||
"forum_profile": rows("SELECT json_build_object('nickname', nickname, 'avatar', avatar, 'bio', bio, 'chart_share', chart_share, 'invisible', invisible, 'points', points, 'post_count', post_count, 'created_at', created_at, 'email_replies', email_replies, 'email_followed', email_followed, 'email_messages', email_messages, 'email_mentions', email_mentions, 'email_listener', email_listener, 'email_weekly', email_weekly, 'listener', listener, 'supporter_badge', supporter_badge, 'banned_until', banned_until, 'ban_reason', ban_reason) FROM forum.members WHERE user_id = $1").await?,
|
||||
"forum_topic_memberships": rows("SELECT json_build_object('topic', tp.name, 'status', tm.status, 'note', tm.note, 'requested_at', tm.requested_at) FROM forum.topic_members tm JOIN forum.topics tp ON tp.id = tm.topic_id WHERE tm.user_id = $1").await?,
|
||||
"forum_posts": rows("SELECT json_build_object('id', p.id, 'thread_id', p.thread_id, 'thread_title', th.title, 'opening', p.is_opening, 'body', p.body, 'created_at', p.created_at, 'edited_at', p.edited_at, 'removed_at', p.deleted_at, 'removal_reason', p.delete_reason) FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id WHERE p.author_id = $1 ORDER BY p.id").await?,
|
||||
"forum_reactions": rows("SELECT json_build_object('post_id', post_id, 'kind', kind, 'created_at', created_at) FROM forum.reactions WHERE user_id = $1 ORDER BY created_at").await?,
|
||||
"forum_followed_threads": rows("SELECT json_build_object('thread_id', thread_id, 'since', created_at) FROM forum.follows WHERE user_id = $1").await?,
|
||||
"forum_conversations": rows("SELECT json_build_object('id', c.id, 'with', m.nickname, 'requested_by_me', c.requested_by = $1, 'intro', c.intro, 'status', c.status, 'created_at', c.created_at) FROM forum.conversations c LEFT JOIN forum.members m ON m.user_id = CASE WHEN c.user_a = $1 THEN c.user_b ELSE c.user_a END WHERE $1 IN (c.user_a, c.user_b)").await?,
|
||||
"forum_messages_sent": rows("SELECT json_build_object('conversation_id', conversation_id, 'body', body, 'created_at', created_at) FROM forum.messages WHERE sender_id = $1 ORDER BY id").await?,
|
||||
"forum_reports_sent": rows("SELECT json_build_object('post_id', post_id, 'message_id', message_id, 'kind', kind, 'note', note, 'status', status, 'created_at', created_at) FROM forum.reports WHERE reporter_id = $1").await?,
|
||||
});
|
||||
Ok(([("content-disposition", "attachment; filename=\"sorsfonalak-export.json\"")], Json(document)))
|
||||
}
|
||||
@@ -249,8 +258,18 @@ pub async fn delete_me(
|
||||
.bind(auth.id())
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
// The forum's own avatar picture (in the object storage) goes too.
|
||||
let avatar: Option<String> = sqlx::query_scalar("SELECT avatar FROM forum.members WHERE user_id = $1")
|
||||
.bind(auth.id())
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("DELETE FROM users WHERE id = $1").bind(auth.id()).execute(&mut *tx).await?;
|
||||
tx.commit().await?;
|
||||
if let (Some(file), Some(storage)) = (avatar.as_deref().and_then(|a| a.strip_prefix("upload:")), &state.storage)
|
||||
&& let Err(e) = storage.delete(&format!("forum-avatars/{file}")).await
|
||||
{
|
||||
tracing::warn!(error = %e, "removing a deleted account's forum avatar");
|
||||
}
|
||||
tracing::info!(user = %auth.id(), "account deleted");
|
||||
Ok((StatusCode::NO_CONTENT, jar.add(removal_cookie(&state.config))))
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ pub fn method(config: &crate::config::Config) -> Option<&'static str> {
|
||||
}
|
||||
|
||||
/// The terms (ÁSZF) version a purchase accepts; the frontend's `TERMS_UPDATED`.
|
||||
pub const TERMS_VERSION: &str = "2026-11-23";
|
||||
pub const TERMS_VERSION: &str = "2026-11-26";
|
||||
|
||||
/// Only admins can buy through Stripe: until purchases open, and always with a
|
||||
/// test key (nobody gets packages with Stripe's test cards, nobody types a
|
||||
|
||||
@@ -13,6 +13,12 @@
|
||||
//! per user: a click proves little. A natal analysis is earned by bringing a
|
||||
//! new user (`REFERRAL_REWARDS`): someone who signs up from a shared link and
|
||||
//! makes their own chart, at most [`REFERRAL_LIMIT`] times.
|
||||
//!
|
||||
//! A share made for the forum (`for_forum`, a question about one's chart,
|
||||
//! forecast or synastry) never shows birth data, and its public view leaves
|
||||
//! out the chart names: they may be real names next to a nickname. A yearly
|
||||
//! forecast can be shared too: its calculation and its detailed text, without
|
||||
//! the place of the birthday.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, State};
|
||||
@@ -27,6 +33,7 @@ use uuid::Uuid;
|
||||
|
||||
use super::analyses::{can_see, find_analysis};
|
||||
use super::charts::{ChartRow, find_chart, owned_chart};
|
||||
use super::forecasts::{ForecastRow, find_forecast, owned_forecast};
|
||||
use super::synastries::{VisibleSynastry, load_synastry, visible_synastry};
|
||||
use super::{Body, IdPath, St};
|
||||
use crate::auth::{AuthUser, user_agent};
|
||||
@@ -39,6 +46,7 @@ pub enum ShareKind {
|
||||
Chart,
|
||||
Synastry,
|
||||
Analysis,
|
||||
Forecast,
|
||||
}
|
||||
|
||||
#[derive(Debug, sqlx::FromRow)]
|
||||
@@ -50,16 +58,18 @@ struct ShareRow {
|
||||
chart_id: Option<Uuid>,
|
||||
synastry_id: Option<Uuid>,
|
||||
analysis_id: Option<Uuid>,
|
||||
forecast_id: Option<Uuid>,
|
||||
title: Option<String>,
|
||||
show_birth_data: bool,
|
||||
for_forum: bool,
|
||||
view_count: i64,
|
||||
created_at: OffsetDateTime,
|
||||
revoked_at: Option<OffsetDateTime>,
|
||||
owner_ip_hash: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
const SHARE_COLUMNS: &str = "id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, title, show_birth_data, \
|
||||
view_count, created_at, revoked_at, owner_ip_hash";
|
||||
const SHARE_COLUMNS: &str = "id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, forecast_id, title, \
|
||||
show_birth_data, for_forum, view_count, created_at, revoked_at, owner_ip_hash";
|
||||
|
||||
use super::client_ip;
|
||||
|
||||
@@ -113,8 +123,10 @@ impl ShareRow {
|
||||
"chart_id": self.chart_id,
|
||||
"synastry_id": self.synastry_id,
|
||||
"analysis_id": self.analysis_id,
|
||||
"forecast_id": self.forecast_id,
|
||||
"title": self.title,
|
||||
"show_birth_data": self.show_birth_data,
|
||||
"for_forum": self.for_forum,
|
||||
"view_count": self.view_count,
|
||||
"created_at": rfc3339(self.created_at),
|
||||
"revoked_at": rfc3339_opt(self.revoked_at),
|
||||
@@ -132,6 +144,9 @@ pub struct CreateShare {
|
||||
/// Show birth date, time and place (only ever of the sharer's own charts).
|
||||
#[serde(default)]
|
||||
show_birth_data: bool,
|
||||
/// For a forum post: no birth data, no names, no title.
|
||||
#[serde(default)]
|
||||
for_forum: bool,
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
@@ -140,14 +155,22 @@ pub async fn create(
|
||||
headers: HeaderMap,
|
||||
WithRejection(Json(req), _): Body<CreateShare>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let (chart_id, synastry_id, analysis_id, kind) = match req.kind {
|
||||
let (mut chart_id, mut synastry_id, mut analysis_id, mut forecast_id) = (None, None, None, None);
|
||||
let kind = match req.kind {
|
||||
ShareKind::Chart => {
|
||||
owned_chart(&state.db, req.target_id, auth.id()).await?;
|
||||
(Some(req.target_id), None, None, "chart")
|
||||
chart_id = Some(req.target_id);
|
||||
"chart"
|
||||
}
|
||||
ShareKind::Synastry => {
|
||||
visible_synastry(&state.db, req.target_id, auth.id()).await?;
|
||||
(None, Some(req.target_id), None, "synastry")
|
||||
synastry_id = Some(req.target_id);
|
||||
"synastry"
|
||||
}
|
||||
ShareKind::Forecast => {
|
||||
owned_forecast(&state.db, req.target_id, auth.id()).await?;
|
||||
forecast_id = Some(req.target_id);
|
||||
"forecast"
|
||||
}
|
||||
ShareKind::Analysis => {
|
||||
let analysis = find_analysis(&state.db, req.target_id).await?.ok_or(ApiError::NotFound("analysis"))?;
|
||||
@@ -157,14 +180,18 @@ pub async fn create(
|
||||
if analysis.status != "done" {
|
||||
return Err(ApiError::conflict("analysis_not_ready", "Csak elkészült elemzést lehet megosztani."));
|
||||
}
|
||||
(None, None, Some(req.target_id), "analysis")
|
||||
analysis_id = Some(req.target_id);
|
||||
"analysis"
|
||||
}
|
||||
};
|
||||
let title = req.title.map(|t| t.trim().chars().take(120).collect::<String>()).filter(|t| !t.is_empty());
|
||||
// A forum share: never birth data, and no title of the sharer's own.
|
||||
let (title, show_birth_data) = if req.for_forum { (None, false) } else { (title, req.show_birth_data) };
|
||||
let open: Option<ShareRow> = sqlx::query_as(&format!(
|
||||
"SELECT {SHARE_COLUMNS} FROM shares WHERE owner_id = $1 AND kind = $2 AND revoked_at IS NULL \
|
||||
AND chart_id IS NOT DISTINCT FROM $3 AND synastry_id IS NOT DISTINCT FROM $4 \
|
||||
AND analysis_id IS NOT DISTINCT FROM $5 AND title IS NOT DISTINCT FROM $6 AND show_birth_data = $7 \
|
||||
AND forecast_id IS NOT DISTINCT FROM $8 AND for_forum = $9 \
|
||||
ORDER BY created_at DESC LIMIT 1"
|
||||
))
|
||||
.bind(auth.id())
|
||||
@@ -173,7 +200,9 @@ pub async fn create(
|
||||
.bind(synastry_id)
|
||||
.bind(analysis_id)
|
||||
.bind(&title)
|
||||
.bind(req.show_birth_data)
|
||||
.bind(show_birth_data)
|
||||
.bind(forecast_id)
|
||||
.bind(req.for_forum)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
if let Some(row) = open {
|
||||
@@ -182,8 +211,8 @@ pub async fn create(
|
||||
let slug = new_slug();
|
||||
let row: ShareRow = sqlx::query_as(&format!(
|
||||
"INSERT INTO shares (id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, title, show_birth_data, \
|
||||
owner_ip_hash) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING {SHARE_COLUMNS}"
|
||||
owner_ip_hash, forecast_id, for_forum) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING {SHARE_COLUMNS}"
|
||||
))
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(auth.id())
|
||||
@@ -193,8 +222,10 @@ pub async fn create(
|
||||
.bind(synastry_id)
|
||||
.bind(analysis_id)
|
||||
.bind(title)
|
||||
.bind(req.show_birth_data)
|
||||
.bind(show_birth_data)
|
||||
.bind(client_ip(&headers).map(|ip| ip_hash(&slug, &ip)))
|
||||
.bind(forecast_id)
|
||||
.bind(req.for_forum)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
Ok((StatusCode::CREATED, Json(row.view(&state.config.public_base_url))))
|
||||
@@ -229,7 +260,27 @@ fn public_chart_block(chart: &ChartRow, share: &ShareRow) -> Value {
|
||||
// Birth data only of the sharer's own chart, never of a partner's or of a
|
||||
// person they added (that is someone else's data).
|
||||
let show = share.show_birth_data && chart.owner_id == share.owner_id && chart.kind == "own";
|
||||
json!({ "label": chart.label, "chart": public_chart(&chart.result, show) })
|
||||
// A forum share leaves out the names (they may be real names next to a nickname).
|
||||
let label = if share.for_forum { Value::Null } else { Value::from(chart.label.clone()) };
|
||||
json!({ "label": label, "chart": public_chart(&chart.result, show) })
|
||||
}
|
||||
|
||||
/// A yearly forecast without where it was reckoned: the solar return chart
|
||||
/// without its place and time zone, and the year's calculation.
|
||||
fn public_forecast_block(forecast: &ForecastRow) -> Value {
|
||||
let sr = &forecast.result["solar_return"];
|
||||
let solar_return = if sr.is_object() {
|
||||
let mut chart = public_chart(sr, false);
|
||||
if let Some(obj) = chart.as_object_mut() {
|
||||
for key in ["local_time", "timezone", "utc_offset", "moment_utc", "location"] {
|
||||
obj.remove(key);
|
||||
}
|
||||
}
|
||||
chart
|
||||
} else {
|
||||
Value::Null
|
||||
};
|
||||
json!({ "year": forecast.year, "forecast": forecast.result["forecast"], "solar_return": solar_return })
|
||||
}
|
||||
|
||||
fn public_synastry_block(s: &VisibleSynastry, share: &ShareRow) -> Value {
|
||||
@@ -269,6 +320,26 @@ async fn public_body(db: &PgPool, share: &ShareRow) -> Result<Value, ApiError> {
|
||||
let s = load_synastry(db, synastry_id).await?.ok_or(ApiError::NotFound("share"))?;
|
||||
body["synastry"] = public_synastry_block(&s, share);
|
||||
}
|
||||
} else if let Some(forecast_id) = share.forecast_id {
|
||||
let forecast = find_forecast(db, forecast_id).await?.ok_or(ApiError::NotFound("share"))?;
|
||||
body["forecast"] = public_forecast_block(&forecast);
|
||||
// The detailed text of the year, if it was written.
|
||||
let analysis: Option<(String, Option<Value>, Option<OffsetDateTime>)> = sqlx::query_as(
|
||||
"SELECT language, content, completed_at FROM analyses \
|
||||
WHERE forecast_id = $1 AND kind = 'forecast' AND status = 'done' ORDER BY completed_at DESC LIMIT 1",
|
||||
)
|
||||
.bind(forecast_id)
|
||||
.fetch_optional(db)
|
||||
.await?;
|
||||
body["analysis"] = match analysis {
|
||||
Some((language, content, completed_at)) => json!({
|
||||
"kind": "forecast",
|
||||
"language": language,
|
||||
"content": content,
|
||||
"completed_at": rfc3339_opt(completed_at),
|
||||
}),
|
||||
None => Value::Null,
|
||||
};
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
@@ -1,276 +1,3 @@
|
||||
//! Object storage for uploaded photos: any S3-compatible service, addressed
|
||||
//! path-style (`{endpoint}/{bucket}/{key}`). In production DigitalOcean
|
||||
//! Spaces, in development a RustFS container.
|
||||
//!
|
||||
//! The bucket stays private: the backend reads the objects itself and serves
|
||||
//! them under `/v1/public/photos/...`, from where the frontend's image
|
||||
//! optimizer makes the sized versions (and Cloudflare caches those).
|
||||
//!
|
||||
//! Requests are signed with AWS Signature Version 4.
|
||||
//! Object storage for uploaded photos: the shared `object-storage` crate.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use hmac::{Hmac, Mac};
|
||||
use sha2::{Digest, Sha256};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
/// `S3_ENDPOINT` (e.g. `https://fra1.digitaloceanspaces.com`), `S3_BUCKET`,
|
||||
/// `S3_REGION` (default `us-east-1`; Spaces accepts it too),
|
||||
/// `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY` (in `.env.secrets`).
|
||||
#[derive(Clone)]
|
||||
pub struct StorageConfig {
|
||||
pub endpoint: String,
|
||||
pub bucket: String,
|
||||
pub region: String,
|
||||
pub access_key: String,
|
||||
pub secret_key: String,
|
||||
}
|
||||
|
||||
// The secret stays out of logs.
|
||||
impl std::fmt::Debug for StorageConfig {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("StorageConfig")
|
||||
.field("endpoint", &self.endpoint)
|
||||
.field("bucket", &self.bucket)
|
||||
.field("region", &self.region)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum StorageError {
|
||||
#[error("object storage request failed: {0}")]
|
||||
Http(#[from] reqwest::Error),
|
||||
#[error("object storage answered {status}: {body}")]
|
||||
Status { status: u16, body: String },
|
||||
}
|
||||
|
||||
pub struct Storage {
|
||||
config: StorageConfig,
|
||||
http: reqwest::Client,
|
||||
}
|
||||
|
||||
/// An object read back: its bytes and content type.
|
||||
pub struct Object {
|
||||
pub bytes: axum::body::Bytes,
|
||||
pub content_type: Option<String>,
|
||||
}
|
||||
|
||||
impl Storage {
|
||||
pub fn new(config: StorageConfig) -> Self {
|
||||
let http = reqwest::Client::builder().timeout(Duration::from_secs(30)).build().expect("static configuration");
|
||||
Self { config, http }
|
||||
}
|
||||
|
||||
fn url(&self, key: &str) -> String {
|
||||
let path = if key.is_empty() { String::new() } else { format!("/{}", encode_path(key)) };
|
||||
format!("{}/{}{path}", self.config.endpoint, encode_segment(&self.config.bucket))
|
||||
}
|
||||
|
||||
async fn send(
|
||||
&self,
|
||||
method: reqwest::Method,
|
||||
key: &str,
|
||||
body: Vec<u8>,
|
||||
content_type: Option<&str>,
|
||||
) -> Result<reqwest::Response, StorageError> {
|
||||
let url = self.url(key);
|
||||
let parsed = reqwest::Url::parse(&url).map_err(|e| StorageError::Status { status: 0, body: e.to_string() })?;
|
||||
let host = match parsed.port() {
|
||||
Some(port) => format!("{}:{port}", parsed.host_str().unwrap_or_default()),
|
||||
None => parsed.host_str().unwrap_or_default().to_string(),
|
||||
};
|
||||
let payload_hash = hex(&Sha256::digest(&body));
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let auth = authorization(&self.config, method.as_str(), parsed.path(), &host, &payload_hash, now);
|
||||
let mut request = self
|
||||
.http
|
||||
.request(method, url)
|
||||
.header("x-amz-date", amz_date(now))
|
||||
.header("x-amz-content-sha256", &payload_hash)
|
||||
.header("authorization", auth);
|
||||
if let Some(ct) = content_type {
|
||||
request = request.header("content-type", ct);
|
||||
}
|
||||
let response = request.body(body).send().await?;
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn checked(response: reqwest::Response) -> Result<reqwest::Response, StorageError> {
|
||||
if response.status().is_success() {
|
||||
return Ok(response);
|
||||
}
|
||||
let status = response.status().as_u16();
|
||||
let body = response.text().await.unwrap_or_default().chars().take(500).collect();
|
||||
Err(StorageError::Status { status, body })
|
||||
}
|
||||
|
||||
pub async fn put(&self, key: &str, body: Vec<u8>, content_type: &str) -> Result<(), StorageError> {
|
||||
Self::checked(self.send(reqwest::Method::PUT, key, body, Some(content_type)).await?).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The object, or `None` if there is no such key.
|
||||
pub async fn get(&self, key: &str) -> Result<Option<Object>, StorageError> {
|
||||
let response = self.send(reqwest::Method::GET, key, Vec::new(), None).await?;
|
||||
if response.status() == reqwest::StatusCode::NOT_FOUND {
|
||||
return Ok(None);
|
||||
}
|
||||
let response = Self::checked(response).await?;
|
||||
let content_type = response.headers().get("content-type").and_then(|v| v.to_str().ok()).map(str::to_owned);
|
||||
Ok(Some(Object { bytes: response.bytes().await?, content_type }))
|
||||
}
|
||||
|
||||
/// Deletes the object; a missing one is not an error.
|
||||
pub async fn delete(&self, key: &str) -> Result<(), StorageError> {
|
||||
let response = self.send(reqwest::Method::DELETE, key, Vec::new(), None).await?;
|
||||
if response.status() == reqwest::StatusCode::NOT_FOUND {
|
||||
return Ok(());
|
||||
}
|
||||
Self::checked(response).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Creates the bucket if it does not exist yet (development: a fresh
|
||||
/// RustFS container has none; in production it is made in the console).
|
||||
pub async fn ensure_bucket(&self) -> Result<(), StorageError> {
|
||||
let head = self.send(reqwest::Method::HEAD, "", Vec::new(), None).await?;
|
||||
if head.status().is_success() {
|
||||
return Ok(());
|
||||
}
|
||||
Self::checked(self.send(reqwest::Method::PUT, "", Vec::new(), None).await?).await?;
|
||||
tracing::info!(bucket = %self.config.bucket, "object storage bucket created");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
type HmacSha256 = Hmac<Sha256>;
|
||||
|
||||
fn hmac(key: &[u8], data: &str) -> Vec<u8> {
|
||||
let mut mac = HmacSha256::new_from_slice(key).expect("HMAC takes any key length");
|
||||
mac.update(data.as_bytes());
|
||||
mac.finalize().into_bytes().to_vec()
|
||||
}
|
||||
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
fn amz_date(t: OffsetDateTime) -> String {
|
||||
format!(
|
||||
"{:04}{:02}{:02}T{:02}{:02}{:02}Z",
|
||||
t.year(),
|
||||
u8::from(t.month()),
|
||||
t.day(),
|
||||
t.hour(),
|
||||
t.minute(),
|
||||
t.second()
|
||||
)
|
||||
}
|
||||
|
||||
/// URI-encodes one path segment as SigV4 wants it (unreserved characters stay).
|
||||
fn encode_segment(s: &str) -> String {
|
||||
s.bytes()
|
||||
.map(|b| match b {
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),
|
||||
_ => format!("%{b:02X}"),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn encode_path(key: &str) -> String {
|
||||
key.split('/').map(encode_segment).collect::<Vec<_>>().join("/")
|
||||
}
|
||||
|
||||
fn signing_key(secret: &str, date: &str, region: &str, service: &str) -> Vec<u8> {
|
||||
[date, region, service, "aws4_request"]
|
||||
.iter()
|
||||
.fold(format!("AWS4{secret}").into_bytes(), |key, part| hmac(&key, part))
|
||||
}
|
||||
|
||||
/// The `Authorization` header of a request (no query string; the path is
|
||||
/// already encoded, as in the URL).
|
||||
fn authorization(
|
||||
config: &StorageConfig,
|
||||
method: &str,
|
||||
path: &str,
|
||||
host: &str,
|
||||
payload_hash: &str,
|
||||
now: OffsetDateTime,
|
||||
) -> String {
|
||||
let date_time = amz_date(now);
|
||||
let date = &date_time[..8];
|
||||
let signed_headers = "host;x-amz-content-sha256;x-amz-date";
|
||||
let canonical = format!(
|
||||
"{method}\n{path}\n\nhost:{host}\nx-amz-content-sha256:{payload_hash}\nx-amz-date:{date_time}\n\n\
|
||||
{signed_headers}\n{payload_hash}"
|
||||
);
|
||||
let scope = format!("{date}/{}/s3/aws4_request", config.region);
|
||||
let to_sign = format!("AWS4-HMAC-SHA256\n{date_time}\n{scope}\n{}", hex(&Sha256::digest(canonical.as_bytes())));
|
||||
let signature = hex(&hmac(&signing_key(&config.secret_key, date, &config.region, "s3"), &to_sign));
|
||||
format!(
|
||||
"AWS4-HMAC-SHA256 Credential={}/{scope}, SignedHeaders={signed_headers}, Signature={signature}",
|
||||
config.access_key
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The signing key example of the AWS documentation ("Examples of how to
|
||||
/// derive a signing key for Signature Version 4").
|
||||
#[test]
|
||||
fn derives_the_signing_key_like_aws() {
|
||||
let key = signing_key("wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY", "20150830", "us-east-1", "iam");
|
||||
assert_eq!(hex(&key), "c4afb1cc5771d871763a393e44b703571b55cc28424d1a5e86da6ed3c154a4b9");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_the_authorization_header() {
|
||||
let config = StorageConfig {
|
||||
endpoint: "http://rustfs:9000".into(),
|
||||
bucket: "photos".into(),
|
||||
region: "us-east-1".into(),
|
||||
access_key: "AKIAIOSFODNN7EXAMPLE".into(),
|
||||
secret_key: "secret".into(),
|
||||
};
|
||||
let now = OffsetDateTime::from_unix_timestamp(1_369_353_600).unwrap();
|
||||
assert_eq!(amz_date(now), "20130524T000000Z");
|
||||
let empty = hex(&Sha256::digest(b""));
|
||||
assert_eq!(empty, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
|
||||
let auth = authorization(&config, "GET", "/photos/a.jpg", "rustfs:9000", &empty, now);
|
||||
assert!(auth.starts_with(
|
||||
"AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request, \
|
||||
SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature="
|
||||
));
|
||||
let storage = Storage::new(config);
|
||||
assert_eq!(storage.url("celebrities/a b/ő.jpg"), "http://rustfs:9000/photos/celebrities/a%20b/%C5%91.jpg");
|
||||
assert_eq!(storage.url(""), "http://rustfs:9000/photos");
|
||||
}
|
||||
|
||||
/// Against a real S3 service (e.g. the RustFS container of development):
|
||||
/// `S3_TEST_ENDPOINT=http://127.0.0.1:9000 S3_TEST_KEY=… S3_TEST_SECRET=…
|
||||
/// cargo test -p backend live_round_trip -- --ignored`
|
||||
#[tokio::test]
|
||||
#[ignore]
|
||||
async fn live_round_trip() {
|
||||
let env = |name: &str| std::env::var(name).unwrap_or_else(|_| panic!("{name} is not set"));
|
||||
let storage = Storage::new(StorageConfig {
|
||||
endpoint: env("S3_TEST_ENDPOINT"),
|
||||
bucket: "storage-test".into(),
|
||||
region: "us-east-1".into(),
|
||||
access_key: env("S3_TEST_KEY"),
|
||||
secret_key: env("S3_TEST_SECRET"),
|
||||
});
|
||||
storage.ensure_bucket().await.unwrap();
|
||||
storage.ensure_bucket().await.unwrap();
|
||||
let key = "dir/próba kép.jpg";
|
||||
storage.put(key, b"hello".to_vec(), "image/jpeg").await.unwrap();
|
||||
let object = storage.get(key).await.unwrap().unwrap();
|
||||
assert_eq!((&object.bytes[..], object.content_type.as_deref()), (&b"hello"[..], Some("image/jpeg")));
|
||||
storage.delete(key).await.unwrap();
|
||||
assert!(storage.get(key).await.unwrap().is_none());
|
||||
storage.delete(key).await.unwrap();
|
||||
}
|
||||
}
|
||||
pub use object_storage::*;
|
||||
|
||||
@@ -1019,6 +1019,21 @@ async fn public_shares(pool: PgPool) {
|
||||
);
|
||||
assert_eq!(app.get(&format!("/v1/public/shares/{slug}"), None).await.status, StatusCode::NOT_FOUND);
|
||||
assert_eq!(app.get("/v1/public/shares/nincs-ilyen", None).await.status, StatusCode::NOT_FOUND);
|
||||
|
||||
// A share for the forum: its own link, never birth data, no names, no title.
|
||||
let r = app
|
||||
.post(
|
||||
"/v1/shares",
|
||||
Some(&anna),
|
||||
json!({"kind": "chart", "target_id": chart_id, "for_forum": true, "show_birth_data": true, "title": "Én"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
assert_eq!((r.body["for_forum"].as_bool(), r.body["show_birth_data"].as_bool()), (Some(true), Some(false)));
|
||||
let r = app.get(&format!("/v1/public/shares/{}", r.body["slug"].as_str().unwrap()), None).await;
|
||||
assert!(r.body["chart"]["label"].is_null(), "{}", r.body);
|
||||
assert!(r.body["chart"]["chart"].get("birth").is_none());
|
||||
assert!(r.body["title"].is_null());
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
@@ -1032,12 +1047,39 @@ async fn export_and_delete_account(pool: PgPool) {
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
let r = app.post("/v1/synastries", Some(&anna), json!({"chart1_id": b["id"], "chart2_id": a["id"]})).await;
|
||||
assert_eq!(r.status, StatusCode::OK); // already exists
|
||||
// Anna also wrote in the forum (services/forum keeps it in the same database).
|
||||
let (anna_id,): (uuid::Uuid,) =
|
||||
sqlx::query_as("SELECT id FROM users WHERE email = 'anna@example.com'").fetch_one(&app.pool).await.unwrap();
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.members (user_id, nickname, nickname_key, avatar) \
|
||||
VALUES ($1, 'Holdfény', 'holdfeny', 'hold-ejkek')",
|
||||
)
|
||||
.bind(anna_id)
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let thread: i64 = sqlx::query_scalar(
|
||||
"INSERT INTO forum.threads (topic_id, author_id, title) VALUES (4, $1, 'Téli levesek') RETURNING id",
|
||||
)
|
||||
.bind(anna_id)
|
||||
.fetch_one(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO forum.posts (thread_id, author_id, is_opening, body) VALUES ($1, $2, true, 'Sütőtök')")
|
||||
.bind(thread)
|
||||
.bind(anna_id)
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let r = app.get("/v1/me/export", Some(&anna)).await;
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
assert_eq!(r.body["charts"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(r.body["synastries"].as_array().unwrap().len(), 1);
|
||||
assert!(r.body["login_methods"][0].get("password_hash").is_none());
|
||||
assert_eq!(r.body["forum_profile"][0]["nickname"], "Holdfény");
|
||||
assert_eq!(r.body["forum_posts"][0]["body"], "Sütőtök");
|
||||
assert_eq!(r.body["forum_posts"][0]["thread_title"], "Téli levesek");
|
||||
|
||||
let r = app.call("DELETE", "/v1/me", Some(&anna), Some(json!({"confirm": "yes"}))).await;
|
||||
assert_eq!(r.status, StatusCode::BAD_REQUEST);
|
||||
@@ -1049,6 +1091,15 @@ async fn export_and_delete_account(pool: PgPool) {
|
||||
assert_eq!(r.status, StatusCode::UNAUTHORIZED);
|
||||
let (left,): (i64,) = sqlx::query_as("SELECT count(*) FROM charts").fetch_one(&app.pool).await.unwrap();
|
||||
assert_eq!(left, 0);
|
||||
// Her forum profile is gone; her thread stays, by "Törölt tag" (no author).
|
||||
let (members, author): (i64, Option<uuid::Uuid>) = sqlx::query_as(
|
||||
"SELECT (SELECT count(*) FROM forum.members), (SELECT author_id FROM forum.threads WHERE id = $1)",
|
||||
)
|
||||
.bind(thread)
|
||||
.fetch_one(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!((members, author), (0, None));
|
||||
assert_eq!(app.get("/v1/me", Some(&bela)).await.status, StatusCode::OK);
|
||||
}
|
||||
|
||||
@@ -1940,6 +1991,19 @@ async fn forecasts_are_free_their_analysis_uses_a_forecast_unit(pool: PgPool) {
|
||||
assert_eq!(app.get(&uri, Some(&bob)).await.status, StatusCode::NOT_FOUND);
|
||||
assert_eq!(app.get(&format!("/v1/forecasts/{id}"), Some(&anna)).await.body["year"], json!(year));
|
||||
|
||||
// A forecast can be shared (not by others), without where it was reckoned.
|
||||
let r = app.post("/v1/shares", Some(&bob), json!({"kind": "forecast", "target_id": away.body["id"]})).await;
|
||||
assert_eq!(r.status, StatusCode::NOT_FOUND);
|
||||
let r = app
|
||||
.post("/v1/shares", Some(&anna), json!({"kind": "forecast", "target_id": away.body["id"], "for_forum": true}))
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
let shared = app.get(&format!("/v1/public/shares/{}", r.body["slug"].as_str().unwrap()), None).await.body;
|
||||
assert_eq!(shared["kind"], "forecast");
|
||||
assert_eq!(shared["forecast"]["forecast"]["start"], format!("{year}-03-15"));
|
||||
assert!(!shared.to_string().contains("Tokió"), "the place stays private: {shared}");
|
||||
assert!(shared["analysis"].is_null(), "no detailed text yet");
|
||||
|
||||
// the detailed text uses a forecast unit, not a natal one
|
||||
let analyses = format!("/v1/forecasts/{id}/analyses");
|
||||
grant_units(&app, &anna, "natal", 1).await;
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
[package]
|
||||
name = "forum"
|
||||
description = "Sorsfonalak forum: pseudonymous members, topics, threads, posts, reactions, moderation"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
db.workspace = true
|
||||
object-storage.workspace = true
|
||||
image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp"] }
|
||||
sha2.workspace = true
|
||||
service-kit.workspace = true
|
||||
anyhow.workspace = true
|
||||
axum = { workspace = true, features = ["ws"] }
|
||||
axum-extra.workspace = true
|
||||
deunicode.workspace = true
|
||||
reqwest.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
sqlx.workspace = true
|
||||
thiserror.workspace = true
|
||||
time.workspace = true
|
||||
tokio = { workspace = true, features = ["time"] }
|
||||
tower-http.workspace = true
|
||||
tracing.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
tokio-tungstenite = "0.29"
|
||||
futures-util = { version = "0.3", default-features = false }
|
||||
http-body-util = "0.1"
|
||||
@@ -0,0 +1,33 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
#
|
||||
# Build from the repository root:
|
||||
# docker build -f services/forum/Dockerfile -t sorsfonalak/forum .
|
||||
|
||||
ARG RUST_VERSION=1.99
|
||||
|
||||
# --- 1. static (musl) build ----------------------------------------------------
|
||||
FROM rust:${RUST_VERSION}-alpine AS build
|
||||
RUN apk add --no-cache musl-dev
|
||||
WORKDIR /app
|
||||
COPY Cargo.toml Cargo.lock ./
|
||||
COPY crates crates
|
||||
COPY services services
|
||||
RUN --mount=type=cache,target=/usr/local/cargo/registry,sharing=locked \
|
||||
--mount=type=cache,target=/app/target,sharing=locked \
|
||||
cargo build --release --locked -p forum \
|
||||
&& cp target/release/forum /forum
|
||||
# The log directory (LOG_DIR); a volume mounted here takes over its owner.
|
||||
RUN mkdir /logs
|
||||
|
||||
# --- 2. runtime: the binary only (TLS roots are compiled in via webpki-roots) ---
|
||||
FROM scratch
|
||||
COPY --from=build /forum /forum
|
||||
COPY --from=build --chown=65532:65532 /logs /logs
|
||||
ENV BIND_ADDR=0.0.0.0:8083 \
|
||||
LOG_FORMAT=json \
|
||||
RUST_LOG=info
|
||||
USER 65532:65532
|
||||
EXPOSE 8083
|
||||
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
|
||||
CMD ["/forum", "healthcheck"]
|
||||
ENTRYPOINT ["/forum"]
|
||||
@@ -0,0 +1,166 @@
|
||||
//! Who is asking: the backend's session (cookie or Bearer token) and the
|
||||
//! member behind it. Reading needs no login; writing needs a nickname.
|
||||
//! Every request of a member also keeps the online dot fresh.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::FromRequestParts;
|
||||
use axum::http::header::AUTHORIZATION;
|
||||
use axum::http::request::Parts;
|
||||
use axum_extra::extract::cookie::CookieJar;
|
||||
use db::{Role, User};
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::AppState;
|
||||
use crate::error::ApiError;
|
||||
use crate::rank::Rank;
|
||||
|
||||
pub const SESSION_COOKIE: &str = "sf_session";
|
||||
|
||||
/// How long a member counts as online after the last request.
|
||||
pub const ONLINE_MINUTES: i64 = 5;
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct Member {
|
||||
pub user_id: Uuid,
|
||||
pub nickname: String,
|
||||
pub avatar: String,
|
||||
pub bio: String,
|
||||
pub chart_share: String,
|
||||
pub invisible: bool,
|
||||
pub points: i32,
|
||||
pub post_count: i32,
|
||||
pub created_at: OffsetDateTime,
|
||||
pub nickname_changed_at: OffsetDateTime,
|
||||
pub banned_until: Option<OffsetDateTime>,
|
||||
pub ban_reason: Option<String>,
|
||||
pub email_replies: String,
|
||||
pub email_followed: String,
|
||||
pub email_messages: String,
|
||||
pub email_mentions: String,
|
||||
pub email_listener: String,
|
||||
pub email_weekly: bool,
|
||||
pub listener: bool,
|
||||
pub supporter_badge: bool,
|
||||
}
|
||||
|
||||
pub const MEMBER_COLUMNS: &str = "user_id, nickname, avatar, bio, chart_share, invisible, points, post_count, \
|
||||
created_at, nickname_changed_at, banned_until, ban_reason, email_replies, email_followed, email_messages, \
|
||||
email_mentions, email_listener, email_weekly, listener, supporter_badge";
|
||||
|
||||
impl Member {
|
||||
pub fn rank(&self, now: OffsetDateTime) -> Rank {
|
||||
Rank::of(self.points, self.created_at, now)
|
||||
}
|
||||
|
||||
pub fn banned(&self, now: OffsetDateTime) -> bool {
|
||||
self.banned_until.is_some_and(|until| until > now)
|
||||
}
|
||||
}
|
||||
|
||||
/// The visitor: maybe logged in, maybe a member (has chosen a nickname).
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Viewer {
|
||||
pub user: Option<User>,
|
||||
pub member: Option<Member>,
|
||||
/// The restricted topics the member was approved into.
|
||||
pub topics: Vec<i16>,
|
||||
/// The members they muted.
|
||||
pub mutes: Vec<Uuid>,
|
||||
}
|
||||
|
||||
impl Viewer {
|
||||
pub fn user_id(&self) -> Option<Uuid> {
|
||||
self.user.as_ref().map(|u| u.id)
|
||||
}
|
||||
|
||||
pub fn logged_in(&self) -> bool {
|
||||
self.user.is_some()
|
||||
}
|
||||
|
||||
pub fn is_admin(&self) -> bool {
|
||||
self.user.as_ref().is_some_and(|u| u.has_role(Role::Admin))
|
||||
}
|
||||
|
||||
/// A moderator or an admin.
|
||||
pub fn is_moderator(&self) -> bool {
|
||||
self.user.as_ref().is_some_and(|u| u.has_role(Role::Moderator) || u.has_role(Role::Admin))
|
||||
}
|
||||
|
||||
pub fn require_user(&self) -> Result<&User, ApiError> {
|
||||
self.user.as_ref().ok_or(ApiError::Unauthorized)
|
||||
}
|
||||
|
||||
pub fn require_member(&self) -> Result<&Member, ApiError> {
|
||||
self.require_user()?;
|
||||
self.member.as_ref().ok_or(ApiError::NicknameRequired)
|
||||
}
|
||||
|
||||
/// A member who may write (not banned).
|
||||
pub fn require_writer(&self) -> Result<&Member, ApiError> {
|
||||
let member = self.require_member()?;
|
||||
if member.banned(OffsetDateTime::now_utc()) {
|
||||
let reason = member.ban_reason.as_deref().map(|r| format!(" Indok: {r}")).unwrap_or_default();
|
||||
return Err(ApiError::Banned(format!("Most nem írhatsz a fórumba.{reason}")));
|
||||
}
|
||||
Ok(member)
|
||||
}
|
||||
|
||||
pub fn require_moderator(&self) -> Result<&User, ApiError> {
|
||||
let user = self.require_user()?;
|
||||
if self.is_moderator() { Ok(user) } else { Err(ApiError::Forbidden("Ehhez moderátori jog kell.".into())) }
|
||||
}
|
||||
}
|
||||
|
||||
fn session_token(parts: &Parts) -> Option<String> {
|
||||
if let Some(value) = parts.headers.get(AUTHORIZATION).and_then(|v| v.to_str().ok())
|
||||
&& let Some(token) = value.strip_prefix("Bearer ")
|
||||
{
|
||||
return Some(token.trim().to_string());
|
||||
}
|
||||
CookieJar::from_headers(&parts.headers).get(SESSION_COOKIE).map(|c| c.value().to_string())
|
||||
}
|
||||
|
||||
impl FromRequestParts<Arc<AppState>> for Viewer {
|
||||
type Rejection = ApiError;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, state: &Arc<AppState>) -> Result<Self, Self::Rejection> {
|
||||
let Some(token) = session_token(parts) else { return Ok(Viewer::default()) };
|
||||
let Some((_, user)) = db::user_by_session(&state.db, &token).await? else { return Ok(Viewer::default()) };
|
||||
let member = load_member(&state.db, user.id).await?;
|
||||
if member.is_some() {
|
||||
// At most once a minute per member: the online dot.
|
||||
sqlx::query(
|
||||
"UPDATE forum.members SET last_seen_at = now() \
|
||||
WHERE user_id = $1 AND (last_seen_at IS NULL OR last_seen_at < now() - interval '60 seconds')",
|
||||
)
|
||||
.bind(user.id)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
}
|
||||
let (topics, mutes) = if member.is_some() {
|
||||
let topics = sqlx::query_scalar(
|
||||
"SELECT topic_id FROM forum.topic_members WHERE user_id = $1 AND status = 'approved'",
|
||||
)
|
||||
.bind(user.id)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let mutes = sqlx::query_scalar("SELECT muted_id FROM forum.mutes WHERE user_id = $1")
|
||||
.bind(user.id)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
(topics, mutes)
|
||||
} else {
|
||||
(Vec::new(), Vec::new())
|
||||
};
|
||||
Ok(Viewer { user: Some(user), member, topics, mutes })
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn load_member(db: &sqlx::PgPool, user_id: Uuid) -> Result<Option<Member>, sqlx::Error> {
|
||||
sqlx::query_as(&format!("SELECT {MEMBER_COLUMNS} FROM forum.members WHERE user_id = $1"))
|
||||
.bind(user_id)
|
||||
.fetch_optional(db)
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
use axum::Json;
|
||||
use axum::extract::rejection::{JsonRejection, PathRejection, QueryRejection};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use serde_json::json;
|
||||
|
||||
/// API error, rendered as `{"error": {"code", "message"}}` like the backend's.
|
||||
/// Messages meant for the user are Hungarian.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ApiError {
|
||||
#[error("{0}")]
|
||||
BadRequest(String),
|
||||
#[error("authentication required")]
|
||||
Unauthorized,
|
||||
/// Logged in, but no nickname yet: the frontend sends the user to choose one.
|
||||
#[error("Előbb válassz álnevet.")]
|
||||
NicknameRequired,
|
||||
#[error("{0}")]
|
||||
Forbidden(String),
|
||||
/// Banned from writing; the message tells until when.
|
||||
#[error("{0}")]
|
||||
Banned(String),
|
||||
#[error("{0} not found")]
|
||||
NotFound(&'static str),
|
||||
#[error("{message}")]
|
||||
Conflict { code: &'static str, message: String },
|
||||
/// A usage limit; the message is shown to the user as is.
|
||||
#[error("{0}")]
|
||||
Limited(String),
|
||||
#[error("internal error")]
|
||||
Internal(String),
|
||||
}
|
||||
|
||||
impl ApiError {
|
||||
pub fn conflict(code: &'static str, message: impl Into<String>) -> Self {
|
||||
ApiError::Conflict { code, message: message.into() }
|
||||
}
|
||||
|
||||
pub fn bad(message: impl Into<String>) -> Self {
|
||||
ApiError::BadRequest(message.into())
|
||||
}
|
||||
|
||||
fn status_and_code(&self) -> (StatusCode, &'static str) {
|
||||
match self {
|
||||
ApiError::BadRequest(_) => (StatusCode::BAD_REQUEST, "bad_request"),
|
||||
ApiError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized"),
|
||||
ApiError::NicknameRequired => (StatusCode::FORBIDDEN, "nickname_required"),
|
||||
ApiError::Forbidden(_) => (StatusCode::FORBIDDEN, "forbidden"),
|
||||
ApiError::Banned(_) => (StatusCode::FORBIDDEN, "banned"),
|
||||
ApiError::NotFound(_) => (StatusCode::NOT_FOUND, "not_found"),
|
||||
ApiError::Conflict { code, .. } => (StatusCode::CONFLICT, code),
|
||||
ApiError::Limited(_) => (StatusCode::TOO_MANY_REQUESTS, "limited"),
|
||||
ApiError::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "internal_error"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoResponse for ApiError {
|
||||
fn into_response(self) -> Response {
|
||||
let (status, code) = self.status_and_code();
|
||||
if let ApiError::Internal(detail) = &self {
|
||||
tracing::error!(error = %detail, code, "request failed");
|
||||
}
|
||||
(status, Json(json!({ "error": { "code": code, "message": self.to_string() } }))).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<sqlx::Error> for ApiError {
|
||||
fn from(e: sqlx::Error) -> Self {
|
||||
ApiError::Internal(format!("database: {e}"))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<JsonRejection> for ApiError {
|
||||
fn from(rejection: JsonRejection) -> Self {
|
||||
ApiError::BadRequest(rejection.body_text())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<QueryRejection> for ApiError {
|
||||
fn from(rejection: QueryRejection) -> Self {
|
||||
ApiError::BadRequest(rejection.body_text())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PathRejection> for ApiError {
|
||||
fn from(rejection: PathRejection) -> Self {
|
||||
ApiError::BadRequest(rejection.body_text())
|
||||
}
|
||||
}
|
||||
|
||||
pub type ApiResult<T> = Result<T, ApiError>;
|
||||
@@ -0,0 +1,195 @@
|
||||
//! The link module: recognises links in a post and shows a preview for the
|
||||
//! ones a provider knows. For now only YouTube ([`youtube`]). Previews are
|
||||
//! fetched when a post is written or edited (a few seconds at most), kept in
|
||||
//! `forum.link_previews`, and found again from the text when posts are shown.
|
||||
//! Thumbnails are stored in our own object storage and served by the forum,
|
||||
//! so reading a thread sends nothing to the provider.
|
||||
|
||||
pub mod youtube;
|
||||
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::header;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::AppState;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::routes::St;
|
||||
|
||||
/// At most this many previews under one post.
|
||||
pub const MAX_PER_POST: usize = 3;
|
||||
/// The thumbnails' folder in the bucket.
|
||||
pub const FOLDER: &str = "forum-links";
|
||||
|
||||
/// Where the providers are asked (the tests point them at a fake server).
|
||||
#[derive(Clone)]
|
||||
pub struct LinkConfig {
|
||||
pub http: reqwest::Client,
|
||||
pub youtube_oembed: String,
|
||||
pub youtube_thumbs: String,
|
||||
}
|
||||
|
||||
impl LinkConfig {
|
||||
pub fn new(youtube_oembed: &str, youtube_thumbs: &str) -> Self {
|
||||
let http = reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(5))
|
||||
.user_agent("Sorsfonalak-Forum/1.0 (link preview)")
|
||||
.build()
|
||||
.expect("an HTTP client");
|
||||
Self {
|
||||
http,
|
||||
youtube_oembed: youtube_oembed.trim_end_matches('/').to_string(),
|
||||
youtube_thumbs: youtube_thumbs.trim_end_matches('/').to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_env() -> Self {
|
||||
let var = |name: &str, default: &str| std::env::var(name).unwrap_or_else(|_| default.to_string());
|
||||
Self::new(
|
||||
&var("YOUTUBE_OEMBED_URL", "https://www.youtube.com/oembed"),
|
||||
&var("YOUTUBE_THUMBS_URL", "https://i.ytimg.com"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// A recognised link in a post's text.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Found {
|
||||
pub provider: &'static str,
|
||||
pub key: String,
|
||||
/// As written in the post.
|
||||
pub url: String,
|
||||
/// Where to start playing, in seconds.
|
||||
pub start: Option<u32>,
|
||||
}
|
||||
|
||||
/// The links of a text the providers know (each video once, at most [`MAX_PER_POST`]).
|
||||
pub fn find(text: &str) -> Vec<Found> {
|
||||
let mut out: Vec<Found> = Vec::new();
|
||||
for word in text.split_whitespace() {
|
||||
let word = word.trim_matches(|c: char| matches!(c, '(' | ')' | '<' | '>' | '"' | '\'' | '„' | '”' | '«' | '»'));
|
||||
let word = word.trim_end_matches(['.', ',', ';', ':', '!', '?']);
|
||||
if !word.starts_with("http://") && !word.starts_with("https://") {
|
||||
continue;
|
||||
}
|
||||
let Ok(url) = reqwest::Url::parse(word) else { continue };
|
||||
if let Some((key, start)) = youtube::video(&url)
|
||||
&& !out.iter().any(|f| f.provider == youtube::PROVIDER && f.key == key)
|
||||
{
|
||||
out.push(Found { provider: youtube::PROVIDER, key, url: word.to_string(), start });
|
||||
}
|
||||
if out.len() == MAX_PER_POST {
|
||||
break;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Fetches the previews a text needs and does not have yet. Failures only
|
||||
/// leave a link without a preview (the next edit tries again).
|
||||
pub async fn process(state: &AppState, text: &str) {
|
||||
for found in find(text) {
|
||||
let known: bool =
|
||||
sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM forum.link_previews WHERE provider = $1 AND key = $2)")
|
||||
.bind(found.provider)
|
||||
.bind(&found.key)
|
||||
.fetch_one(&state.db)
|
||||
.await
|
||||
.unwrap_or(true);
|
||||
if known {
|
||||
continue;
|
||||
}
|
||||
let result = match found.provider {
|
||||
youtube::PROVIDER => youtube::fetch(state, &found.key).await,
|
||||
_ => continue,
|
||||
};
|
||||
if let Err(e) = result {
|
||||
tracing::warn!(provider = found.provider, key = %found.key, error = %e, "link preview not made");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The previews of these posts' texts, by post id, as the page shows them.
|
||||
pub async fn previews(
|
||||
db: &PgPool,
|
||||
texts: &[(i64, &str)],
|
||||
) -> Result<std::collections::HashMap<i64, Value>, sqlx::Error> {
|
||||
let found: Vec<(i64, Vec<Found>)> =
|
||||
texts.iter().map(|(id, text)| (*id, find(text))).filter(|(_, f)| !f.is_empty()).collect();
|
||||
if found.is_empty() {
|
||||
return Ok(Default::default());
|
||||
}
|
||||
let keys: Vec<String> = found.iter().flat_map(|(_, f)| f.iter().map(|x| x.key.clone())).collect();
|
||||
type Row = (String, String, String, Option<String>, Option<String>);
|
||||
let rows: Vec<Row> =
|
||||
sqlx::query_as("SELECT provider, key, title, author, thumbnail FROM forum.link_previews WHERE key = ANY($1)")
|
||||
.bind(&keys)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
Ok(found
|
||||
.into_iter()
|
||||
.filter_map(|(id, links)| {
|
||||
let shown: Vec<Value> = links
|
||||
.iter()
|
||||
.filter_map(|f| {
|
||||
let (_, _, title, author, thumb) =
|
||||
rows.iter().find(|(provider, key, ..)| provider == f.provider && *key == f.key)?;
|
||||
Some(json!({
|
||||
"provider": f.provider,
|
||||
"id": f.key,
|
||||
"url": f.url,
|
||||
"start": f.start,
|
||||
"title": title,
|
||||
"author": author,
|
||||
"thumbnail": thumb.as_ref().map(|t| format!("/api/v1/forum/link-thumbs/{t}")),
|
||||
}))
|
||||
})
|
||||
.collect();
|
||||
(!shown.is_empty()).then_some((id, Value::Array(shown)))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// `GET /v1/forum/link-thumbs/{file}`: a stored thumbnail (cached for good).
|
||||
pub async fn thumbnail(
|
||||
State(state): St,
|
||||
WithRejection(Path(file), _): WithRejection<Path<String>, ApiError>,
|
||||
) -> ApiResult<Response> {
|
||||
let valid = file.len() <= 64
|
||||
&& file.ends_with(".jpg")
|
||||
&& file.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
|
||||
if !valid {
|
||||
return Err(ApiError::NotFound("thumbnail"));
|
||||
}
|
||||
let storage = state.storage.as_ref().ok_or(ApiError::NotFound("thumbnail"))?;
|
||||
let object = storage
|
||||
.get(&format!("{FOLDER}/{file}"))
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("reading a thumbnail: {e}")))?
|
||||
.ok_or(ApiError::NotFound("thumbnail"))?;
|
||||
Ok((
|
||||
[(header::CONTENT_TYPE, "image/jpeg"), (header::CACHE_CONTROL, "public, max-age=31536000, immutable")],
|
||||
object.bytes,
|
||||
)
|
||||
.into_response())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn finds_the_links_providers_know() {
|
||||
let text = "Nézzétek: https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=1m30s, és (https://youtu.be/dQw4w9WgXcQ) \
|
||||
meg https://youtube.com/shorts/abcdefghijk! Ez nem: https://example.com/watch?v=dQw4w9WgXcQ";
|
||||
let found = find(text);
|
||||
assert_eq!(found.len(), 2, "{found:?}");
|
||||
assert_eq!(found[0].key, "dQw4w9WgXcQ");
|
||||
assert_eq!(found[0].start, Some(90));
|
||||
assert_eq!(found[0].url, "https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=1m30s");
|
||||
assert_eq!(found[1].key, "abcdefghijk");
|
||||
assert!(find("Nincs itt link, csak youtube.com/watch?v=dQw4w9WgXcQ").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
//! YouTube links: the video's id (and where to start) from the usual forms
|
||||
//! of address, its title and channel from YouTube's oEmbed answer, and its
|
||||
//! thumbnail cut to 16:9 and kept in our storage.
|
||||
|
||||
use std::io::Cursor;
|
||||
|
||||
use image::codecs::jpeg::JpegEncoder;
|
||||
use image::imageops::FilterType;
|
||||
use image::{ImageFormat, ImageReader};
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::FOLDER;
|
||||
use crate::AppState;
|
||||
|
||||
pub const PROVIDER: &str = "youtube";
|
||||
/// The stored thumbnail: 480×270.
|
||||
const WIDTH: u32 = 480;
|
||||
const HEIGHT: u32 = 270;
|
||||
|
||||
fn valid_id(id: &str) -> bool {
|
||||
id.len() == 11 && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
|
||||
}
|
||||
|
||||
/// "90", "90s", "1m30s", "1h2m3s" as seconds.
|
||||
fn seconds(raw: &str) -> Option<u32> {
|
||||
if let Ok(n) = raw.parse::<u32>() {
|
||||
return Some(n);
|
||||
}
|
||||
let (mut total, mut number) = (0u32, String::new());
|
||||
for c in raw.chars() {
|
||||
match c {
|
||||
'0'..='9' => number.push(c),
|
||||
'h' | 'm' | 's' => {
|
||||
let n: u32 = number.parse().ok()?;
|
||||
total += n * match c {
|
||||
'h' => 3600,
|
||||
'm' => 60,
|
||||
_ => 1,
|
||||
};
|
||||
number.clear();
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
number.is_empty().then_some(total).filter(|t| *t > 0)
|
||||
}
|
||||
|
||||
/// The video id and start (seconds) of a YouTube address: watch, shorts,
|
||||
/// live, embed and youtu.be links, on www., m. and music. too.
|
||||
pub fn video(url: &reqwest::Url) -> Option<(String, Option<u32>)> {
|
||||
let host = url.host_str()?.to_ascii_lowercase();
|
||||
let host = host.strip_prefix("www.").unwrap_or(&host);
|
||||
let param = |name: &str| url.query_pairs().find(|(k, _)| k == name).map(|(_, v)| v.into_owned());
|
||||
let mut segments = url.path_segments()?;
|
||||
let id = match host {
|
||||
"youtu.be" => segments.next().map(str::to_string),
|
||||
"youtube.com" | "m.youtube.com" | "music.youtube.com" => match segments.next() {
|
||||
Some("watch") => param("v"),
|
||||
Some("shorts" | "live" | "embed") => segments.next().map(str::to_string),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}?;
|
||||
if !valid_id(&id) {
|
||||
return None;
|
||||
}
|
||||
let start = param("t").or_else(|| param("start")).as_deref().and_then(seconds);
|
||||
Some((id, start))
|
||||
}
|
||||
|
||||
/// YouTube's oEmbed answer (live streams come without title and channel).
|
||||
#[derive(Deserialize)]
|
||||
struct OEmbed {
|
||||
#[serde(default)]
|
||||
title: Option<String>,
|
||||
#[serde(default)]
|
||||
author_name: Option<String>,
|
||||
}
|
||||
|
||||
/// The card's title when YouTube gives none.
|
||||
const NO_TITLE: &str = "YouTube-videó";
|
||||
|
||||
/// The video's title and channel, and its thumbnail into the storage.
|
||||
pub async fn fetch(state: &AppState, id: &str) -> anyhow::Result<()> {
|
||||
let links = &state.links;
|
||||
let watch = format!("https://www.youtube.com/watch?v={id}");
|
||||
let answer = links
|
||||
.http
|
||||
.get(&links.youtube_oembed)
|
||||
.query(&[("url", watch.as_str()), ("format", "json")])
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?
|
||||
.text()
|
||||
.await?;
|
||||
let meta: OEmbed = serde_json::from_str(&answer).map_err(|e| {
|
||||
anyhow::anyhow!("oEmbed answer not understood ({e}): {}", answer.chars().take(160).collect::<String>())
|
||||
})?;
|
||||
// Without a thumbnail the card still shows (title and play button).
|
||||
let thumbnail = match &state.storage {
|
||||
Some(storage) => match store_thumbnail(state, storage, id).await {
|
||||
Ok(file) => Some(file),
|
||||
Err(e) => {
|
||||
tracing::warn!(key = id, error = %e, "no thumbnail for a YouTube link");
|
||||
None
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let title: String = meta.title.filter(|t| !t.trim().is_empty()).unwrap_or_else(|| NO_TITLE.into());
|
||||
let title: String = title.chars().take(200).collect();
|
||||
let author = meta.author_name.map(|a| a.chars().take(100).collect::<String>());
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.link_previews (provider, key, title, author, thumbnail) VALUES ($1, $2, $3, $4, $5) \
|
||||
ON CONFLICT (provider, key) DO UPDATE SET title = EXCLUDED.title, author = EXCLUDED.author, \
|
||||
thumbnail = COALESCE(EXCLUDED.thumbnail, forum.link_previews.thumbnail), fetched_at = now()",
|
||||
)
|
||||
.bind(PROVIDER)
|
||||
.bind(id)
|
||||
.bind(&title)
|
||||
.bind(&author)
|
||||
.bind(&thumbnail)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn store_thumbnail(state: &AppState, storage: &object_storage::Storage, id: &str) -> anyhow::Result<String> {
|
||||
let bytes = state
|
||||
.links
|
||||
.http
|
||||
.get(format!("{}/vi/{id}/hqdefault.jpg", state.links.youtube_thumbs))
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?
|
||||
.bytes()
|
||||
.await?;
|
||||
let jpeg = widescreen(&bytes)?;
|
||||
let file = format!("{PROVIDER}-{id}.jpg");
|
||||
storage.put(&format!("{FOLDER}/{file}"), jpeg, "image/jpeg").await?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// YouTube's 4:3 thumbnail (with black bands) as a 16:9 JPEG.
|
||||
fn widescreen(bytes: &[u8]) -> anyhow::Result<Vec<u8>> {
|
||||
let img = ImageReader::with_format(Cursor::new(bytes), ImageFormat::Jpeg).decode()?;
|
||||
let (w, h) = (img.width(), img.height());
|
||||
let band_h = (w * 9 / 16).min(h);
|
||||
let cropped = img.crop_imm(0, (h - band_h) / 2, w, band_h);
|
||||
let small = cropped.resize_exact(WIDTH, HEIGHT, FilterType::Triangle).to_rgb8();
|
||||
let mut out = Vec::new();
|
||||
JpegEncoder::new_with_quality(&mut out, 82).encode_image(&small)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_youtube_addresses() {
|
||||
let id = |s: &str| video(&reqwest::Url::parse(s).unwrap());
|
||||
assert_eq!(id("https://www.youtube.com/watch?v=dQw4w9WgXcQ"), Some(("dQw4w9WgXcQ".into(), None)));
|
||||
assert_eq!(
|
||||
id("https://m.youtube.com/watch?feature=share&v=dQw4w9WgXcQ&t=42"),
|
||||
Some(("dQw4w9WgXcQ".into(), Some(42)))
|
||||
);
|
||||
assert_eq!(id("https://youtu.be/dQw4w9WgXcQ?t=1h2m3s"), Some(("dQw4w9WgXcQ".into(), Some(3723))));
|
||||
assert_eq!(id("https://youtube.com/shorts/dQw4w9WgXcQ"), Some(("dQw4w9WgXcQ".into(), None)));
|
||||
assert_eq!(id("https://music.youtube.com/watch?v=dQw4w9WgXcQ&list=x"), Some(("dQw4w9WgXcQ".into(), None)));
|
||||
assert_eq!(id("https://www.youtube.com/@csatorna"), None);
|
||||
assert_eq!(id("https://www.youtube.com/watch?v=rovid"), None);
|
||||
assert_eq!(id("https://notyoutube.com/watch?v=dQw4w9WgXcQ"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
//! Live notices over WebSocket: a doorbell, never the data. The server only
|
||||
//! says "something changed" (`{"t":"nav"}`: the menu's counts; `{"t":"thread",
|
||||
//! "id":…}`: a thread; `{"t":"conversation","id":…}`), and the page fetches the
|
||||
//! news over HTTP as before. The one thing a page says is that its member is
|
||||
//! typing (`{"typing":"thread"|"conversation","id":…}`, every few seconds while
|
||||
//! they type); the others there get `{"t":"typing","kind":…,"id":…,"who":…}`. A dropped connection loses nothing: the page asks
|
||||
//! again when it reconnects, and polls while it cannot.
|
||||
//!
|
||||
//! Events go through Postgres (`NOTIFY forum_events`), so every instance of the
|
||||
//! service hears every change, whichever instance it happened on; each one
|
||||
//! passes them to its own connections.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::extract::State;
|
||||
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
|
||||
use axum::http::{HeaderMap, StatusCode, header};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
use sqlx::PgPool;
|
||||
use sqlx::postgres::PgListener;
|
||||
use tokio::sync::broadcast;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::AppState;
|
||||
use crate::auth::Viewer;
|
||||
|
||||
pub const CHANNEL: &str = "forum_events";
|
||||
/// A ping this often keeps the connection open through proxies (Cloudflare
|
||||
/// closes one idle for 100 seconds), and refreshes the online dot.
|
||||
const PING: Duration = Duration::from_secs(30);
|
||||
/// Above this many recipients an event goes to everyone (NOTIFY payloads are small).
|
||||
const MAX_USERS: usize = 300;
|
||||
|
||||
/// What changed, and for whom.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
|
||||
pub struct Event {
|
||||
/// A thread got a post, an edit, a reaction or a removal (anyone viewing it refetches).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub thread: Option<i64>,
|
||||
/// A conversation changed (only its two members hear it, through `users`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub conversation: Option<i64>,
|
||||
/// Whose menu counts changed.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub users: Vec<Uuid>,
|
||||
/// Everyone's menu (too many recipients to list).
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub everyone: bool,
|
||||
/// The moderators' menu (the open reports).
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub moderators: bool,
|
||||
/// Someone is typing in a thread (everyone there sees it) or a
|
||||
/// conversation (the other member, in `users`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub typing: Option<Typing>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct Typing {
|
||||
/// `thread` or `conversation`.
|
||||
pub kind: String,
|
||||
pub id: i64,
|
||||
/// The nickname shown ("Holdfény gépel…").
|
||||
pub who: String,
|
||||
/// Who types (they do not hear of themselves).
|
||||
pub from: Uuid,
|
||||
}
|
||||
|
||||
impl Event {
|
||||
pub fn for_users(mut self, users: Vec<Uuid>) -> Self {
|
||||
if users.len() > MAX_USERS {
|
||||
self.everyone = true;
|
||||
} else {
|
||||
self.users = users;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// The messages one connection gets from this event.
|
||||
pub fn messages_for(&self, user: Uuid, moderator: bool) -> Vec<String> {
|
||||
if let Some(t) = &self.typing {
|
||||
let hears = t.from != user && (t.kind == "thread" || self.users.contains(&user));
|
||||
return if hears {
|
||||
vec![json!({ "t": "typing", "kind": t.kind, "id": t.id, "who": t.who }).to_string()]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
}
|
||||
let mine = self.everyone || self.users.contains(&user);
|
||||
let mut out = Vec::new();
|
||||
if let Some(id) = self.thread {
|
||||
out.push(json!({ "t": "thread", "id": id }).to_string());
|
||||
}
|
||||
if let (Some(id), true) = (self.conversation, self.users.contains(&user)) {
|
||||
out.push(json!({ "t": "conversation", "id": id }).to_string());
|
||||
}
|
||||
if mine || (self.moderators && moderator) {
|
||||
out.push(json!({ "t": "nav" }).to_string());
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The events of this instance, for its connections.
|
||||
#[derive(Clone)]
|
||||
pub struct Hub {
|
||||
tx: broadcast::Sender<Arc<Event>>,
|
||||
}
|
||||
|
||||
impl Default for Hub {
|
||||
fn default() -> Self {
|
||||
Self { tx: broadcast::channel(1024).0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Hub {
|
||||
pub fn subscribe(&self) -> broadcast::Receiver<Arc<Event>> {
|
||||
self.tx.subscribe()
|
||||
}
|
||||
}
|
||||
|
||||
/// Announces a change to every instance. A failure is logged: the pages poll anyway.
|
||||
pub async fn emit(db: &PgPool, event: Event) {
|
||||
let payload = serde_json::to_string(&event).unwrap_or_default();
|
||||
if let Err(e) = sqlx::query("SELECT pg_notify($1, $2)").bind(CHANNEL).bind(&payload).execute(db).await {
|
||||
tracing::warn!(error = %e, "announcing a forum event");
|
||||
}
|
||||
}
|
||||
|
||||
/// Passes the database's events to this instance's connections, for good
|
||||
/// (it reconnects after a lost database connection).
|
||||
pub async fn listen(db: PgPool, hub: Hub) {
|
||||
loop {
|
||||
match PgListener::connect_with(&db).await {
|
||||
Ok(mut listener) => {
|
||||
if let Err(e) = listener.listen(CHANNEL).await {
|
||||
tracing::warn!(error = %e, "LISTEN forum_events failed");
|
||||
} else {
|
||||
loop {
|
||||
match listener.recv().await {
|
||||
Ok(note) => match serde_json::from_str::<Event>(note.payload()) {
|
||||
Ok(event) => {
|
||||
// No connection listening is fine.
|
||||
let _ = hub.tx.send(Arc::new(event));
|
||||
}
|
||||
Err(e) => tracing::warn!(error = %e, "unreadable forum event"),
|
||||
},
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "forum events: listener lost");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::warn!(error = %e, "forum events: cannot listen"),
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs(3)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Only the site itself may open a connection with the visitor's cookie
|
||||
/// (no cross-site WebSocket hijacking).
|
||||
fn origin_allowed(headers: &HeaderMap, base_url: &str) -> bool {
|
||||
match headers.get(header::ORIGIN).and_then(|o| o.to_str().ok()) {
|
||||
Some(origin) => origin.trim_end_matches('/') == base_url,
|
||||
// Not a browser (no Origin header): it brings its own token.
|
||||
None => headers.contains_key(header::AUTHORIZATION),
|
||||
}
|
||||
}
|
||||
|
||||
/// `GET /v1/forum/ws`: a member's live connection.
|
||||
pub async fn connect(
|
||||
State(state): State<Arc<AppState>>,
|
||||
viewer: Viewer,
|
||||
headers: HeaderMap,
|
||||
ws: WebSocketUpgrade,
|
||||
) -> Response {
|
||||
if !origin_allowed(&headers, &state.base_url) {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
let Some(member) = viewer.member.clone() else { return StatusCode::UNAUTHORIZED.into_response() };
|
||||
let me = Me { user: member.user_id, nickname: member.nickname, moderator: viewer.is_moderator() };
|
||||
let rx = state.hub.subscribe();
|
||||
let db = state.db.clone();
|
||||
ws.on_upgrade(move |socket| serve(socket, rx, db, me))
|
||||
}
|
||||
|
||||
/// Who is on the other end of a connection.
|
||||
struct Me {
|
||||
user: Uuid,
|
||||
nickname: String,
|
||||
moderator: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Incoming {
|
||||
typing: String,
|
||||
id: i64,
|
||||
}
|
||||
|
||||
/// At most one typing notice per target in this time.
|
||||
const TYPING_EVERY: Duration = Duration::from_secs(2);
|
||||
|
||||
/// "I am typing", from the page: passed on to those who may see that place.
|
||||
async fn typing(db: &PgPool, me: &Me, text: &str) -> Option<Event> {
|
||||
let incoming: Incoming = serde_json::from_str(text).ok()?;
|
||||
let users = match incoming.typing.as_str() {
|
||||
"conversation" => {
|
||||
let other: Option<Uuid> = sqlx::query_scalar(
|
||||
"SELECT CASE WHEN user_a = $2 THEN user_b ELSE user_a END FROM forum.conversations \
|
||||
WHERE id = $1 AND status = 'accepted' AND $2 IN (user_a, user_b)",
|
||||
)
|
||||
.bind(incoming.id)
|
||||
.bind(me.user)
|
||||
.fetch_optional(db)
|
||||
.await
|
||||
.ok()?;
|
||||
vec![other?]
|
||||
}
|
||||
"thread" => {
|
||||
let visibility: Option<String> = sqlx::query_scalar(
|
||||
"SELECT tp.visibility FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
|
||||
WHERE th.id = $1 AND th.deleted_at IS NULL AND (NOT th.locked OR $2)",
|
||||
)
|
||||
.bind(incoming.id)
|
||||
.bind(me.moderator)
|
||||
.fetch_optional(db)
|
||||
.await
|
||||
.ok()?;
|
||||
if visibility? == "restricted" && !me.moderator {
|
||||
return None;
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Some(Event {
|
||||
users,
|
||||
typing: Some(Typing { kind: incoming.typing, id: incoming.id, who: me.nickname.clone(), from: me.user }),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
async fn serve(mut socket: WebSocket, mut rx: broadcast::Receiver<Arc<Event>>, db: PgPool, me: Me) {
|
||||
let (user, moderator) = (me.user, me.moderator);
|
||||
let mut last_typing: Option<(String, std::time::Instant)> = None;
|
||||
let mut ping = tokio::time::interval(PING);
|
||||
ping.tick().await;
|
||||
loop {
|
||||
tokio::select! {
|
||||
event = rx.recv() => {
|
||||
let messages = match event {
|
||||
Ok(event) => event.messages_for(user, moderator),
|
||||
// Too slow to follow: just refresh everything.
|
||||
Err(broadcast::error::RecvError::Lagged(_)) => vec![json!({ "t": "nav" }).to_string()],
|
||||
Err(broadcast::error::RecvError::Closed) => break,
|
||||
};
|
||||
for message in messages {
|
||||
if socket.send(Message::Text(message.into())).await.is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = ping.tick() => {
|
||||
if socket.send(Message::Ping(Vec::new().into())).await.is_err() {
|
||||
return;
|
||||
}
|
||||
// Connected means present: the online dot.
|
||||
let _ = sqlx::query(
|
||||
"UPDATE forum.members SET last_seen_at = now() \
|
||||
WHERE user_id = $1 AND (last_seen_at IS NULL OR last_seen_at < now() - interval '60 seconds')",
|
||||
)
|
||||
.bind(user)
|
||||
.execute(&db)
|
||||
.await;
|
||||
}
|
||||
incoming = socket.recv() => match incoming {
|
||||
Some(Ok(Message::Text(text))) => {
|
||||
// Typing notices, a few seconds apart per place.
|
||||
let fresh = last_typing
|
||||
.as_ref()
|
||||
.is_none_or(|(place, at)| *place != text.as_str() || at.elapsed() >= TYPING_EVERY);
|
||||
if fresh {
|
||||
last_typing = Some((text.to_string(), std::time::Instant::now()));
|
||||
if let Some(event) = typing(&db, &me, &text).await {
|
||||
emit(&db, event).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Pongs and the like are fine.
|
||||
Some(Ok(Message::Close(_))) | None | Some(Err(_)) => break,
|
||||
Some(Ok(_)) => {}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The followers of a thread other than `except` (whose menu counts change).
|
||||
pub async fn followers(db: &PgPool, thread: i64, except: Uuid) -> Vec<Uuid> {
|
||||
sqlx::query_scalar("SELECT user_id FROM forum.follows WHERE thread_id = $1 AND user_id <> $2")
|
||||
.bind(thread)
|
||||
.bind(except)
|
||||
.fetch_all(db)
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn who_hears_what() {
|
||||
let (anna, bea) = (Uuid::now_v7(), Uuid::now_v7());
|
||||
let post = Event { thread: Some(7), ..Default::default() }.for_users(vec![anna]);
|
||||
assert_eq!(post.messages_for(anna, false), vec![r#"{"id":7,"t":"thread"}"#, r#"{"t":"nav"}"#]);
|
||||
assert_eq!(post.messages_for(bea, false), vec![r#"{"id":7,"t":"thread"}"#]);
|
||||
let message = Event { conversation: Some(3), ..Default::default() }.for_users(vec![bea]);
|
||||
assert!(message.messages_for(anna, true).is_empty(), "nobody else hears of a conversation");
|
||||
assert_eq!(message.messages_for(bea, false).len(), 2);
|
||||
let report = Event { moderators: true, ..Default::default() };
|
||||
assert!(report.messages_for(anna, false).is_empty());
|
||||
assert_eq!(report.messages_for(anna, true), vec![r#"{"t":"nav"}"#]);
|
||||
let many = Event::default().for_users((0..400).map(|_| Uuid::now_v7()).collect());
|
||||
assert!(many.everyone && many.users.is_empty());
|
||||
let round: Event = serde_json::from_str(&serde_json::to_string(&post).unwrap()).unwrap();
|
||||
assert_eq!(round, post);
|
||||
|
||||
// Typing: never to oneself; a conversation only to the other member.
|
||||
let typing = |kind: &str, users: Vec<Uuid>| Event {
|
||||
users,
|
||||
typing: Some(Typing { kind: kind.into(), id: 9, who: "Holdfény".into(), from: bea }),
|
||||
..Default::default()
|
||||
};
|
||||
let in_thread = typing("thread", vec![]);
|
||||
assert_eq!(
|
||||
in_thread.messages_for(anna, false),
|
||||
vec![r#"{"id":9,"kind":"thread","t":"typing","who":"Holdfény"}"#]
|
||||
);
|
||||
assert!(in_thread.messages_for(bea, false).is_empty());
|
||||
let in_chat = typing("conversation", vec![anna]);
|
||||
assert_eq!(in_chat.messages_for(anna, false).len(), 1);
|
||||
assert!(in_chat.messages_for(Uuid::now_v7(), true).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
//! Instant forum e-mails (a reply to the member, a private message or a
|
||||
//! request), queued in `email_outbox` for the worker to send. The daily
|
||||
//! digest is the worker's own job (its `forum` task).
|
||||
//!
|
||||
//! Nobody gets an instant e-mail while online (they see the badge), and at
|
||||
//! most one per thread an hour, one per conversation in half an hour. A
|
||||
//! failure here is logged and never fails the post itself.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::AppState;
|
||||
use crate::text;
|
||||
|
||||
/// The one-click unsubscribe links of a member's forum e-mails.
|
||||
fn unsubscribe_links(base: &str, token: &str) -> (String, String) {
|
||||
(format!("{base}/forum/leiratkozas?token={token}"), format!("{base}/api/v1/forum/unsubscribe?token={token}"))
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct Recipient {
|
||||
user_id: Uuid,
|
||||
email: String,
|
||||
locale: String,
|
||||
nickname: String,
|
||||
email_token: String,
|
||||
}
|
||||
|
||||
async fn queue(db: &PgPool, base: &str, to: &Recipient, template: &str, mut payload: Value) -> Result<(), sqlx::Error> {
|
||||
let (unsubscribe_url, unsubscribe_post_url) = unsubscribe_links(base, &to.email_token);
|
||||
payload["nickname"] = json!(to.nickname);
|
||||
payload["unsubscribe_url"] = json!(unsubscribe_url);
|
||||
payload["unsubscribe_post_url"] = json!(unsubscribe_post_url);
|
||||
sqlx::query(
|
||||
"INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload) VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(to.user_id)
|
||||
.bind(&to.email)
|
||||
.bind(template)
|
||||
.bind(&to.locale)
|
||||
.bind(payload)
|
||||
.execute(db)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Not online now (the last request more than five minutes ago).
|
||||
const OFFLINE: &str = "(m.last_seen_at IS NULL OR m.last_seen_at < now() - interval '5 minutes')";
|
||||
|
||||
/// A reply: to the thread's author and to the author of the post answered,
|
||||
/// if they asked for instant e-mails.
|
||||
pub async fn after_reply(
|
||||
state: &AppState,
|
||||
thread_id: i64,
|
||||
post_id: i64,
|
||||
replier: Uuid,
|
||||
parent: Option<i64>,
|
||||
body: &str,
|
||||
) {
|
||||
if let Err(e) = reply_mails(state, thread_id, post_id, replier, parent, body).await {
|
||||
tracing::error!(error = %e, thread = thread_id, "queueing the reply e-mails");
|
||||
}
|
||||
}
|
||||
|
||||
async fn reply_mails(
|
||||
state: &AppState,
|
||||
thread_id: i64,
|
||||
post_id: i64,
|
||||
replier: Uuid,
|
||||
parent: Option<i64>,
|
||||
body: &str,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
let recipients: Vec<Recipient> = sqlx::query_as(&format!(
|
||||
"SELECT m.user_id, u.email, u.locale, m.nickname, m.email_token \
|
||||
FROM forum.members m JOIN users u ON u.id = m.user_id \
|
||||
WHERE m.email_replies = 'instant' AND m.user_id <> $1 AND {OFFLINE} \
|
||||
AND m.user_id IN (SELECT author_id FROM forum.threads WHERE id = $2 \
|
||||
UNION SELECT author_id FROM forum.posts WHERE id = $3) \
|
||||
AND NOT EXISTS (SELECT 1 FROM forum.mutes mu WHERE mu.user_id = m.user_id AND mu.muted_id = $1) \
|
||||
AND NOT EXISTS (SELECT 1 FROM email_outbox e \
|
||||
WHERE e.user_id = m.user_id AND e.template = 'forum_reply' \
|
||||
AND e.payload->>'thread_id' = $2::text AND e.created_at > now() - interval '1 hour')"
|
||||
))
|
||||
.bind(replier)
|
||||
.bind(thread_id)
|
||||
.bind(parent)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
if recipients.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let (title, author): (String, Option<String>) = sqlx::query_as(
|
||||
"SELECT th.title, (SELECT nickname FROM forum.members WHERE user_id = $2) \
|
||||
FROM forum.threads th WHERE th.id = $1",
|
||||
)
|
||||
.bind(thread_id)
|
||||
.bind(replier)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
let url = format!("{}/forum/szal/{thread_id}-{}#h{post_id}", state.base_url, text::slug(&title));
|
||||
for to in &recipients {
|
||||
let payload = json!({
|
||||
"url": url,
|
||||
"author": author,
|
||||
"thread_title": title,
|
||||
"thread_id": thread_id.to_string(),
|
||||
"excerpt": body.chars().take(300).collect::<String>(),
|
||||
});
|
||||
queue(&state.db, &state.base_url, to, "forum_reply", payload).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A private message or a request: to the other member, if they asked for it.
|
||||
pub async fn after_message(state: &AppState, conversation: i64, sender: Uuid, request: bool, intro: Option<&str>) {
|
||||
if let Err(e) = message_mail(state, conversation, sender, request, intro).await {
|
||||
tracing::error!(error = %e, conversation, "queueing the message e-mail");
|
||||
}
|
||||
}
|
||||
|
||||
async fn message_mail(
|
||||
state: &AppState,
|
||||
conversation: i64,
|
||||
sender: Uuid,
|
||||
request: bool,
|
||||
intro: Option<&str>,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
let to: Option<Recipient> = sqlx::query_as(&format!(
|
||||
"SELECT m.user_id, u.email, u.locale, m.nickname, m.email_token \
|
||||
FROM forum.conversations c \
|
||||
JOIN forum.members m ON m.user_id = CASE WHEN c.user_a = $2 THEN c.user_b ELSE c.user_a END \
|
||||
JOIN users u ON u.id = m.user_id \
|
||||
WHERE c.id = $1 AND m.email_messages = 'instant' AND {OFFLINE} \
|
||||
AND NOT EXISTS (SELECT 1 FROM email_outbox e \
|
||||
WHERE e.user_id = m.user_id AND e.template = 'forum_message' \
|
||||
AND e.payload->>'conversation_id' = $1::text \
|
||||
AND e.created_at > now() - interval '30 minutes')"
|
||||
))
|
||||
.bind(conversation)
|
||||
.bind(sender)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let Some(to) = to else { return Ok(()) };
|
||||
let from: Option<String> = sqlx::query_scalar("SELECT nickname FROM forum.members WHERE user_id = $1")
|
||||
.bind(sender)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let payload = json!({
|
||||
"url": format!("{}/forum/uzenetek/{conversation}", state.base_url),
|
||||
"from": from,
|
||||
"kind": if request { "request" } else { "message" },
|
||||
"excerpt": intro,
|
||||
"conversation_id": conversation.to_string(),
|
||||
});
|
||||
queue(&state.db, &state.base_url, &to, "forum_message", payload).await
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct Person {
|
||||
email: String,
|
||||
locale: String,
|
||||
nickname: Option<String>,
|
||||
}
|
||||
|
||||
/// A notice that has to reach the user whatever their notification settings
|
||||
/// (a moderation step concerning them, the decision on their report).
|
||||
pub async fn notify_user(state: &AppState, user: Uuid, template: &str, mut payload: Value) {
|
||||
let person: Result<Option<Person>, sqlx::Error> = sqlx::query_as(
|
||||
"SELECT u.email, u.locale, m.nickname FROM users u LEFT JOIN forum.members m ON m.user_id = u.id WHERE u.id = $1",
|
||||
)
|
||||
.bind(user)
|
||||
.fetch_optional(&state.db)
|
||||
.await;
|
||||
let result = match person {
|
||||
Ok(Some(p)) => {
|
||||
payload["nickname"] = json!(p.nickname);
|
||||
sqlx::query(
|
||||
"INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(user)
|
||||
.bind(&p.email)
|
||||
.bind(template)
|
||||
.bind(&p.locale)
|
||||
.bind(payload)
|
||||
.execute(&state.db)
|
||||
.await
|
||||
.map(|_| ())
|
||||
}
|
||||
Ok(None) => Ok(()),
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
if let Err(e) = result {
|
||||
tracing::error!(error = %e, template, "queueing a moderation e-mail");
|
||||
}
|
||||
}
|
||||
|
||||
/// The forum rules, where the moderation e-mails point.
|
||||
pub fn rules_url(state: &AppState) -> String {
|
||||
format!("{}/aszf#forum", state.base_url)
|
||||
}
|
||||
|
||||
/// "3 napos" or "12 órás": a ban's length for the e-mail.
|
||||
pub fn ban_duration(hours: i64) -> String {
|
||||
if hours % 24 == 0 { format!("{} napos", hours / 24) } else { format!("{hours} órás") }
|
||||
}
|
||||
|
||||
/// Tells each reporter (once) how their report was decided.
|
||||
pub async fn notify_reporters(state: &AppState, reporters: &[Option<Uuid>], outcome: &str) {
|
||||
let mut seen: Vec<Uuid> = reporters.iter().flatten().copied().collect();
|
||||
seen.sort_unstable();
|
||||
seen.dedup();
|
||||
for reporter in seen {
|
||||
let payload = json!({ "url": format!("{}/forum", state.base_url), "outcome": outcome });
|
||||
notify_user(state, reporter, "forum_report_result", payload).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Members named in a post ("@Holdfény") who asked for an e-mail about it
|
||||
/// (not while online, one per thread an hour).
|
||||
pub async fn after_mention(state: &AppState, thread_id: i64, post_id: i64, author: Uuid, users: &[Uuid], body: &str) {
|
||||
let result: Result<(), sqlx::Error> = async {
|
||||
let recipients: Vec<Recipient> = sqlx::query_as(&format!(
|
||||
"SELECT m.user_id, u.email, u.locale, m.nickname, m.email_token \
|
||||
FROM forum.members m JOIN users u ON u.id = m.user_id \
|
||||
WHERE m.user_id = ANY($1) AND m.email_mentions = 'instant' AND {OFFLINE} \
|
||||
AND NOT EXISTS (SELECT 1 FROM forum.mutes mu WHERE mu.user_id = m.user_id AND mu.muted_id = $3) \
|
||||
AND NOT EXISTS (SELECT 1 FROM email_outbox e WHERE e.user_id = m.user_id \
|
||||
AND e.template IN ('forum_mention', 'forum_reply') \
|
||||
AND e.payload->>'thread_id' = $2::text AND e.created_at > now() - interval '1 hour')"
|
||||
))
|
||||
.bind(users)
|
||||
.bind(thread_id)
|
||||
.bind(author)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
if recipients.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let (title, who): (String, Option<String>) = sqlx::query_as(
|
||||
"SELECT th.title, (SELECT nickname FROM forum.members WHERE user_id = $2) FROM forum.threads th WHERE th.id = $1",
|
||||
)
|
||||
.bind(thread_id)
|
||||
.bind(author)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
let url = format!("{}/forum/szal/{thread_id}-{}#h{post_id}", state.base_url, text::slug(&title));
|
||||
for to in &recipients {
|
||||
let payload = json!({
|
||||
"url": url,
|
||||
"author": who,
|
||||
"thread_title": title,
|
||||
"thread_id": thread_id.to_string(),
|
||||
"excerpt": body.chars().take(300).collect::<String>(),
|
||||
});
|
||||
queue(&state.db, &state.base_url, to, "forum_mention", payload).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
if let Err(e) = result {
|
||||
tracing::error!(error = %e, thread = thread_id, "queueing the mention e-mails");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
//! Sorsfonalak forum: pseudonymous members, topics, threads, posts,
|
||||
//! reactions, read marks, followed threads and moderation (docs/kozosseg.md).
|
||||
//!
|
||||
//! A service of its own, so it can be scaled apart from the backend. It shares
|
||||
//! the database and the login: a session of the backend (`sf_session` cookie
|
||||
//! or `Authorization: Bearer`) is valid here too.
|
||||
//!
|
||||
//! Configuration: `DATABASE_URL`, `PUBLIC_BASE_URL` (the site, for e-mail
|
||||
//! links; default `http://localhost:3001`), `S3_*` (avatar uploads, as the
|
||||
//! backend's); `BIND_ADDR` (default `0.0.0.0:8083`),
|
||||
//! `LOG_FORMAT`, `RUST_LOG`, `LOG_DIR`. Database migrations run at startup.
|
||||
//!
|
||||
//! `forum healthcheck` performs a local health check (for Docker).
|
||||
|
||||
mod auth;
|
||||
mod error;
|
||||
mod links;
|
||||
mod live;
|
||||
mod mail;
|
||||
mod rank;
|
||||
mod routes;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod text;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Context;
|
||||
use sqlx::PgPool;
|
||||
|
||||
const DEFAULT_BIND_ADDR: &str = "0.0.0.0:8083";
|
||||
|
||||
pub struct AppState {
|
||||
pub db: PgPool,
|
||||
/// Seconds a member waits between two posts (0 in the tests).
|
||||
pub flood_secs: i32,
|
||||
/// The site's address, for the links in e-mails (`PUBLIC_BASE_URL`); also
|
||||
/// the only origin allowed to open a live connection.
|
||||
pub base_url: String,
|
||||
/// The live events of this instance (`live::listen` fills it).
|
||||
pub hub: live::Hub,
|
||||
/// Where uploaded avatars are kept (`S3_*`); `None`: no uploads.
|
||||
pub storage: Option<object_storage::Storage>,
|
||||
/// The link module's providers (YouTube previews).
|
||||
pub links: links::LinkConfig,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new(db: PgPool, base_url: String, storage: Option<object_storage::Storage>) -> Self {
|
||||
Self {
|
||||
db,
|
||||
flood_secs: 5,
|
||||
base_url: base_url.trim_end_matches('/').to_string(),
|
||||
hub: live::Hub::default(),
|
||||
storage,
|
||||
links: links::LinkConfig::from_env(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let addr = service_kit::bind_addr(DEFAULT_BIND_ADDR)?;
|
||||
if std::env::args().nth(1).as_deref() == Some("healthcheck") {
|
||||
return service_kit::healthcheck(addr);
|
||||
}
|
||||
let _log = service_kit::init_logging("forum");
|
||||
let url = std::env::var("DATABASE_URL").context("DATABASE_URL is not set")?;
|
||||
let pool = db::connect(&url).await.context("connecting to the database")?;
|
||||
db::migrate(&pool).await.context("running database migrations")?;
|
||||
let base_url = std::env::var("PUBLIC_BASE_URL").unwrap_or_else(|_| "http://localhost:3001".into());
|
||||
let storage =
|
||||
object_storage::StorageConfig::from_env().map_err(anyhow::Error::msg)?.map(object_storage::Storage::new);
|
||||
if storage.is_none() {
|
||||
tracing::info!("S3_ENDPOINT is not set: no avatar uploads");
|
||||
}
|
||||
let state = Arc::new(AppState::new(pool, base_url, storage));
|
||||
tokio::spawn(live::listen(state.db.clone(), state.hub.clone()));
|
||||
let app = routes::router(state);
|
||||
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
|
||||
tracing::info!(%addr, "listening");
|
||||
axum::serve(listener, app).with_graceful_shutdown(service_kit::shutdown_signal()).await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
//! Ranks: earned from points (reactions and "Ez segített" marks received)
|
||||
//! and time spent as a member, so nobody climbs in a few days. A rank is
|
||||
//! also a permission level. Buying a package gives no rank: it only lifts the
|
||||
//! newcomer's daily limits (docs/kozosseg.md).
|
||||
|
||||
use serde::Serialize;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Rank {
|
||||
Vandor,
|
||||
Kereso,
|
||||
Fono,
|
||||
Csillagfono,
|
||||
Sorsfono,
|
||||
}
|
||||
|
||||
/// (rank, points needed, days of membership needed), lowest first.
|
||||
const LADDER: [(Rank, i32, i64); 5] = [
|
||||
(Rank::Vandor, i32::MIN, 0),
|
||||
(Rank::Kereso, 5, 3),
|
||||
(Rank::Fono, 30, 14),
|
||||
(Rank::Csillagfono, 100, 45),
|
||||
(Rank::Sorsfono, 300, 120),
|
||||
];
|
||||
|
||||
/// What an "Ez segített" mark is worth.
|
||||
pub const HELPED_POINTS: i32 = 5;
|
||||
/// Newcomer limits (lifted by a purchase): new threads and posts in 24 hours.
|
||||
pub const NEWCOMER_THREADS_PER_DAY: i64 = 3;
|
||||
pub const NEWCOMER_POSTS_PER_DAY: i64 = 20;
|
||||
/// A post whose reactions add up to this or less is shown collapsed.
|
||||
pub const COLLAPSE_SCORE: i64 = -3;
|
||||
|
||||
impl Rank {
|
||||
pub fn of(points: i32, member_since: OffsetDateTime, now: OffsetDateTime) -> Rank {
|
||||
let days = (now - member_since).whole_days();
|
||||
LADDER.iter().rev().find(|(_, p, d)| points >= *p && days >= *d).map(|(r, _, _)| *r).unwrap_or(Rank::Vandor)
|
||||
}
|
||||
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Rank::Vandor => "Vándor",
|
||||
Rank::Kereso => "Kereső",
|
||||
Rank::Fono => "Fonó",
|
||||
Rank::Csillagfono => "Csillagfonó",
|
||||
Rank::Sorsfono => "Sorsfonó",
|
||||
}
|
||||
}
|
||||
|
||||
/// A newcomer: daily limits, reactions that do not count yet, no ⌄.
|
||||
pub fn is_newcomer(self) -> bool {
|
||||
self == Rank::Vandor
|
||||
}
|
||||
|
||||
/// May use the ⌄ (never in a listening topic).
|
||||
pub fn may_downvote(self) -> bool {
|
||||
self >= Rank::Kereso
|
||||
}
|
||||
|
||||
/// The next rank and what it needs, for the member's own profile.
|
||||
pub fn next(self) -> Option<(Rank, i32, i64)> {
|
||||
LADDER.iter().find(|(r, _, _)| *r > self).copied()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ranks_need_points_and_time() {
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let days = |d: i64| now - time::Duration::days(d);
|
||||
assert_eq!(Rank::of(0, days(400), now), Rank::Vandor);
|
||||
assert_eq!(Rank::of(500, days(1), now), Rank::Vandor, "points alone are not enough");
|
||||
assert_eq!(Rank::of(5, days(3), now), Rank::Kereso);
|
||||
assert_eq!(Rank::of(40, days(20), now), Rank::Fono);
|
||||
assert_eq!(Rank::of(40, days(400), now), Rank::Fono);
|
||||
assert_eq!(Rank::of(300, days(120), now), Rank::Sorsfono);
|
||||
assert_eq!(Rank::Vandor.next().map(|n| n.0), Some(Rank::Kereso));
|
||||
assert_eq!(Rank::Sorsfono.next(), None);
|
||||
assert!(!Rank::Vandor.may_downvote() && Rank::Kereso.may_downvote());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
//! A question about one's own chart, yearly forecast or synastry: the opening
|
||||
//! post carries a share made for the forum on the main site (no birth data,
|
||||
//! no names). The post shows it as a card to logged-in members only; a
|
||||
//! visitor (and a search engine) sees that there is one. The sharer can
|
||||
//! revoke it on the main site; the card then says so.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, State};
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::St;
|
||||
use crate::auth::{Member, Viewer};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct CardRow {
|
||||
id: Uuid,
|
||||
slug: String,
|
||||
kind: String,
|
||||
revoked: bool,
|
||||
natal: Option<Value>,
|
||||
year: Option<i32>,
|
||||
summary_title: Option<String>,
|
||||
}
|
||||
|
||||
const CARD_SELECT: &str = "SELECT s.id, s.slug, s.kind, s.revoked_at IS NOT NULL AS revoked, \
|
||||
COALESCE(c.result, fc.result) AS natal, f.year, \
|
||||
CASE s.kind \
|
||||
WHEN 'chart' THEN (SELECT a.content->>'title' FROM analyses a WHERE a.chart_id = s.chart_id \
|
||||
AND a.kind = 'summary' AND a.status = 'done' ORDER BY a.completed_at DESC LIMIT 1) \
|
||||
WHEN 'forecast' THEN (SELECT a.content->>'title' FROM analyses a WHERE a.forecast_id = s.forecast_id \
|
||||
AND a.kind = 'forecast' AND a.status = 'done' ORDER BY a.completed_at DESC LIMIT 1) \
|
||||
END AS summary_title \
|
||||
FROM shares s \
|
||||
LEFT JOIN charts c ON c.id = s.chart_id \
|
||||
LEFT JOIN forecasts f ON f.id = s.forecast_id \
|
||||
LEFT JOIN charts fc ON fc.id = f.chart_id";
|
||||
|
||||
/// Sun, Moon and (with a known birth time) the Ascendant: sign, degree, house.
|
||||
fn big_three(natal: &Value) -> (Vec<Value>, bool) {
|
||||
let time_known = natal.pointer("/time/time_known").and_then(Value::as_bool).unwrap_or(false);
|
||||
let mut points: Vec<Value> = ["sun", "moon"]
|
||||
.iter()
|
||||
.filter_map(|id| natal["points"].as_array()?.iter().find(|p| p["id"] == *id))
|
||||
.map(|p| {
|
||||
json!({
|
||||
"id": p["id"],
|
||||
"sign": p["sign"],
|
||||
"degree": p["degree_in_sign"].as_f64().map(|d| d.floor() as i64),
|
||||
"house": if time_known { p["house"].clone() } else { Value::Null },
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let asc = &natal["angles"]["ascendant"];
|
||||
if time_known && asc.is_object() {
|
||||
points.push(json!({
|
||||
"id": "ascendant",
|
||||
"sign": asc["sign"],
|
||||
"degree": asc["degree_in_sign"].as_f64().map(|d| d.floor() as i64),
|
||||
"house": null,
|
||||
}));
|
||||
}
|
||||
(points, time_known)
|
||||
}
|
||||
|
||||
fn card(row: &CardRow) -> Value {
|
||||
if row.revoked {
|
||||
return json!({ "slug": row.slug, "kind": row.kind, "revoked": true });
|
||||
}
|
||||
let title = match (row.kind.as_str(), row.year) {
|
||||
("synastry", _) => "Két képlet összevetése".to_string(),
|
||||
("forecast", Some(year)) => format!("Éves előrejelzés · {year}–{}", year + 1),
|
||||
_ => "Születési képlet".to_string(),
|
||||
};
|
||||
let (points, time_known) = row.natal.as_ref().map(big_three).unwrap_or_default();
|
||||
json!({
|
||||
"slug": row.slug,
|
||||
"kind": row.kind,
|
||||
"revoked": false,
|
||||
"title": title,
|
||||
"summary": row.summary_title,
|
||||
"points": points,
|
||||
"time_known": time_known,
|
||||
})
|
||||
}
|
||||
|
||||
/// The cards of these shares, as the viewer may see them: in full for
|
||||
/// logged-in members, only that there is one for visitors.
|
||||
pub async fn cards(db: &PgPool, viewer: &Viewer, ids: &[Uuid]) -> Result<HashMap<Uuid, Value>, sqlx::Error> {
|
||||
if ids.is_empty() {
|
||||
return Ok(HashMap::new());
|
||||
}
|
||||
let rows: Vec<CardRow> =
|
||||
sqlx::query_as(&format!("{CARD_SELECT} WHERE s.id = ANY($1)")).bind(ids).fetch_all(db).await?;
|
||||
Ok(rows
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let shown = if viewer.logged_in() { card(r) } else { json!({ "kind": r.kind, "locked": true }) };
|
||||
(r.id, shown)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// A share the member made for the forum and has not revoked: its id.
|
||||
pub async fn attachable(db: &PgPool, member: &Member, slug: &str) -> ApiResult<Uuid> {
|
||||
let row: Option<(Uuid, Uuid, bool, bool)> =
|
||||
sqlx::query_as("SELECT id, owner_id, for_forum, revoked_at IS NOT NULL FROM shares WHERE slug = $1")
|
||||
.bind(slug.trim())
|
||||
.fetch_optional(db)
|
||||
.await?;
|
||||
match row {
|
||||
Some((id, owner, true, false)) if owner == member.user_id => Ok(id),
|
||||
_ => Err(ApiError::bad("Ez a képlet nem csatolható. Indítsd újra a kérdést a képlet oldaláról.")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The card of a share about to be attached (the new thread page shows it).
|
||||
pub async fn preview(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(slug), _): WithRejection<Path<String>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let member = viewer.require_member()?;
|
||||
let id = attachable(&state.db, member, &slug).await?;
|
||||
let row: CardRow = sqlx::query_as(&format!("{CARD_SELECT} WHERE s.id = $1")).bind(id).fetch_one(&state.db).await?;
|
||||
Ok(Json(card(&row)))
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
//! Own avatars: a member from the Kereső rank may upload a picture instead of
|
||||
//! a starter avatar. It is cut to a square, made small (256 pixels), stripped
|
||||
//! of its metadata (EXIF: camera, place) and kept in the object storage; the
|
||||
//! forum serves it. A moderator can put the starter avatar back.
|
||||
|
||||
use std::io::Cursor;
|
||||
|
||||
use axum::Json;
|
||||
use axum::body::Bytes;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::{StatusCode, header};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum_extra::extract::WithRejection;
|
||||
use image::codecs::jpeg::JpegEncoder;
|
||||
use image::imageops::FilterType;
|
||||
use image::metadata::Orientation;
|
||||
use image::{DynamicImage, ImageDecoder, ImageFormat, ImageReader, Limits};
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::St;
|
||||
use super::moderation::{self, Action};
|
||||
use crate::auth::Viewer;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::text;
|
||||
|
||||
/// The largest upload accepted, in bytes.
|
||||
pub const MAX_UPLOAD: usize = 8 * 1024 * 1024;
|
||||
/// The stored picture's side, in pixels.
|
||||
const SIDE: u32 = 256;
|
||||
const MIN_SIDE: u32 = 64;
|
||||
/// The objects' folder in the bucket.
|
||||
const FOLDER: &str = "forum-avatars";
|
||||
pub const PREFIX: &str = "upload:";
|
||||
|
||||
/// A JPEG, PNG or WebP picture as an upright square JPEG of [`SIDE`] pixels.
|
||||
/// The error is a message for the member.
|
||||
pub fn normalize(bytes: &[u8]) -> Result<Vec<u8>, String> {
|
||||
let unreadable = || "A képet nem sikerült beolvasni. JPEG, PNG vagy WebP képet tölts fel.".to_string();
|
||||
let mut reader = ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|_| unreadable())?;
|
||||
if !matches!(reader.format(), Some(ImageFormat::Jpeg | ImageFormat::Png | ImageFormat::WebP)) {
|
||||
return Err(unreadable());
|
||||
}
|
||||
let mut limits = Limits::default();
|
||||
limits.max_image_width = Some(12_000);
|
||||
limits.max_image_height = Some(12_000);
|
||||
reader.limits(limits);
|
||||
let mut decoder = reader.into_decoder().map_err(|_| unreadable())?;
|
||||
let orientation = decoder.orientation().unwrap_or(Orientation::NoTransforms);
|
||||
let mut img = DynamicImage::from_decoder(decoder).map_err(|_| unreadable())?;
|
||||
img.apply_orientation(orientation);
|
||||
let side = img.width().min(img.height());
|
||||
if side < MIN_SIDE {
|
||||
return Err(format!("A kép túl kicsi: legalább {MIN_SIDE}×{MIN_SIDE} pixeles legyen."));
|
||||
}
|
||||
// The middle square, then small.
|
||||
let square = img.crop_imm((img.width() - side) / 2, (img.height() - side) / 2, side, side);
|
||||
let small = square.resize_exact(SIDE, SIDE, FilterType::Lanczos3);
|
||||
let rgb = if small.color().has_alpha() {
|
||||
// JPEG has no transparency: a transparent part turns white.
|
||||
let rgba = small.to_rgba8();
|
||||
image::RgbImage::from_fn(SIDE, SIDE, |x, y| {
|
||||
let [r, g, b, a] = rgba.get_pixel(x, y).0;
|
||||
let mix = |c: u8| ((u16::from(c) * u16::from(a) + 255 * (255 - u16::from(a))) / 255) as u8;
|
||||
image::Rgb([mix(r), mix(g), mix(b)])
|
||||
})
|
||||
} else {
|
||||
small.to_rgb8()
|
||||
};
|
||||
let mut jpeg = Vec::new();
|
||||
JpegEncoder::new_with_quality(&mut jpeg, 85).encode_image(&rgb).map_err(|e| e.to_string())?;
|
||||
Ok(jpeg)
|
||||
}
|
||||
|
||||
/// The stored file of an `upload:` avatar, if it is one.
|
||||
pub fn uploaded_file(avatar: &str) -> Option<&str> {
|
||||
avatar.strip_prefix(PREFIX)
|
||||
}
|
||||
|
||||
fn valid_file(file: &str) -> bool {
|
||||
file.len() <= 80
|
||||
&& file.ends_with(".jpg")
|
||||
&& file.trim_end_matches(".jpg").chars().all(|c| c.is_ascii_hexdigit() || c == '-')
|
||||
}
|
||||
|
||||
/// Removes a stored avatar (best effort: a leftover file is only storage).
|
||||
pub async fn forget(state: &crate::AppState, avatar: &str) {
|
||||
if let (Some(file), Some(storage)) = (uploaded_file(avatar), &state.storage)
|
||||
&& let Err(e) = storage.delete(&format!("{FOLDER}/{file}")).await
|
||||
{
|
||||
tracing::warn!(error = %e, "removing an old avatar");
|
||||
}
|
||||
}
|
||||
|
||||
/// `PUT /v1/forum/me/avatar`: the picture's bytes as the body.
|
||||
pub async fn upload(State(state): St, viewer: Viewer, body: Bytes) -> ApiResult<Json<Value>> {
|
||||
let member = viewer.require_writer()?.clone();
|
||||
if member.rank(OffsetDateTime::now_utc()).is_newcomer() && !viewer.is_moderator() {
|
||||
return Err(ApiError::Forbidden("Saját képet a Kereső rangtól tölthetsz fel.".into()));
|
||||
}
|
||||
let Some(storage) = &state.storage else {
|
||||
return Err(ApiError::Forbidden("A képfeltöltés most nem érhető el.".into()));
|
||||
};
|
||||
if body.len() > MAX_UPLOAD {
|
||||
return Err(ApiError::bad("A kép legfeljebb 8 MB lehet."));
|
||||
}
|
||||
let bytes = body.to_vec();
|
||||
let jpeg = tokio::task::spawn_blocking(move || normalize(&bytes))
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(e.to_string()))?
|
||||
.map_err(ApiError::BadRequest)?;
|
||||
let hash: String = Sha256::digest(&jpeg).iter().take(6).map(|b| format!("{b:02x}")).collect();
|
||||
let file = format!("{}-{hash}.jpg", member.user_id.simple());
|
||||
storage
|
||||
.put(&format!("{FOLDER}/{file}"), jpeg, "image/jpeg")
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("storing an avatar: {e}")))?;
|
||||
let avatar = format!("{PREFIX}{file}");
|
||||
sqlx::query("UPDATE forum.members SET avatar = $2 WHERE user_id = $1")
|
||||
.bind(member.user_id)
|
||||
.bind(&avatar)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
if member.avatar != avatar {
|
||||
forget(&state, &member.avatar).await;
|
||||
}
|
||||
Ok(Json(json!({ "avatar": avatar })))
|
||||
}
|
||||
|
||||
/// `GET /v1/forum/avatars/{file}`: a stored avatar (its name changes with
|
||||
/// its content, so it is cached for good).
|
||||
pub async fn serve(
|
||||
State(state): St,
|
||||
WithRejection(Path(file), _): WithRejection<Path<String>, ApiError>,
|
||||
) -> ApiResult<Response> {
|
||||
if !valid_file(&file) {
|
||||
return Err(ApiError::NotFound("avatar"));
|
||||
}
|
||||
let storage = state.storage.as_ref().ok_or(ApiError::NotFound("avatar"))?;
|
||||
let object = storage
|
||||
.get(&format!("{FOLDER}/{file}"))
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("reading an avatar: {e}")))?
|
||||
.ok_or(ApiError::NotFound("avatar"))?;
|
||||
Ok((
|
||||
[(header::CONTENT_TYPE, "image/jpeg"), (header::CACHE_CONTROL, "public, max-age=31536000, immutable")],
|
||||
object.bytes,
|
||||
)
|
||||
.into_response())
|
||||
}
|
||||
|
||||
/// A moderator puts back the starter avatar (an unfit picture).
|
||||
pub async fn reset(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let moderator = viewer.require_moderator()?;
|
||||
let key = text::nickname_key(&nickname);
|
||||
let found: Option<(Uuid, String)> =
|
||||
sqlx::query_as("SELECT user_id, avatar FROM forum.members WHERE nickname_key = $1")
|
||||
.bind(&key)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let (user, avatar) = found.ok_or(ApiError::NotFound("member"))?;
|
||||
if uploaded_file(&avatar).is_none() {
|
||||
return Ok(StatusCode::NO_CONTENT);
|
||||
}
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE forum.members SET avatar = $2 WHERE user_id = $1")
|
||||
.bind(user)
|
||||
.bind(text::default_avatar(&key))
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
moderation::record(&mut *tx, moderator.id, Action::ResetAvatar, Some(user), None, None, None, None).await?;
|
||||
tx.commit().await?;
|
||||
forget(&state, &avatar).await;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn png(width: u32, height: u32) -> Vec<u8> {
|
||||
let img =
|
||||
DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(width, height, image::Rgba([200, 100, 50, 255])));
|
||||
let mut out = Vec::new();
|
||||
img.write_to(&mut Cursor::new(&mut out), ImageFormat::Png).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn makes_a_small_square_jpeg() {
|
||||
let jpeg = normalize(&png(900, 400)).unwrap();
|
||||
let back = image::load_from_memory(&jpeg).unwrap();
|
||||
assert_eq!((back.width(), back.height()), (SIDE, SIDE));
|
||||
assert!(normalize(&png(40, 40)).unwrap_err().contains("túl kicsi"));
|
||||
assert!(normalize(b"GIF89a\x01\x00\x01\x00\x00\x00\x00;").is_err());
|
||||
assert!(valid_file("0190aa-3f2a1b.jpg") && !valid_file("../x.jpg") && !valid_file("a.png"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
//! The forum's front page, the topics, a topic's threads, followed threads.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, Query, State};
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{CardRow, St, card_params, card_sql, cards_json, may_read, rfc3339};
|
||||
use crate::auth::Viewer;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
|
||||
/// Threads on one page of a topic.
|
||||
const PAGE_SIZE: i64 = 30;
|
||||
/// "Élénk beszélgetések": at least this many replies in the last 24 hours.
|
||||
const HOT_MIN_REPLIES: i64 = 3;
|
||||
/// "Várják a válaszod": threads without a reply from the last two weeks.
|
||||
const UNANSWERED_DAYS: i32 = 14;
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct TopicRow {
|
||||
id: i16,
|
||||
slug: String,
|
||||
name: String,
|
||||
description: String,
|
||||
visibility: String,
|
||||
listening: bool,
|
||||
archived: bool,
|
||||
thread_count: i64,
|
||||
new_count: Option<i64>,
|
||||
last_author: Option<Uuid>,
|
||||
last_at: Option<OffsetDateTime>,
|
||||
}
|
||||
|
||||
/// The topics in order: counts and the latest post for those the viewer may
|
||||
/// read, the others (a members-only topic for a visitor) only by name.
|
||||
async fn topic_list(state: &St, viewer: &Viewer) -> ApiResult<Vec<Value>> {
|
||||
let (me, since) = card_params(viewer);
|
||||
let rows: Vec<TopicRow> = sqlx::query_as(
|
||||
"SELECT tp.id, tp.slug, tp.name, tp.description, tp.visibility, tp.listening, \
|
||||
tp.archived_at IS NOT NULL AS archived, \
|
||||
(SELECT count(*) FROM forum.threads th WHERE th.topic_id = tp.id AND th.deleted_at IS NULL) AS thread_count, \
|
||||
CASE WHEN $1::uuid IS NULL THEN NULL ELSE \
|
||||
(SELECT count(*) FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id \
|
||||
WHERE th.topic_id = tp.id AND th.deleted_at IS NULL AND p.deleted_at IS NULL \
|
||||
AND p.author_id IS DISTINCT FROM $1 AND p.created_at > $2::timestamptz \
|
||||
AND p.id > COALESCE((SELECT r.last_post_id FROM forum.reads r \
|
||||
WHERE r.user_id = $1 AND r.thread_id = th.id), 0)) END AS new_count, \
|
||||
last.author_id AS last_author, last.created_at AS last_at \
|
||||
FROM forum.topics tp \
|
||||
LEFT JOIN LATERAL (SELECT p.author_id, p.created_at FROM forum.posts p \
|
||||
JOIN forum.threads th ON th.id = p.thread_id \
|
||||
WHERE th.topic_id = tp.id AND th.deleted_at IS NULL AND p.deleted_at IS NULL \
|
||||
ORDER BY p.id DESC LIMIT 1) last ON true \
|
||||
ORDER BY tp.position",
|
||||
)
|
||||
.bind(me)
|
||||
.bind(since)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let readable: Vec<bool> = rows.iter().map(|r| may_read(viewer, &r.visibility, r.id)).collect();
|
||||
let people =
|
||||
super::authors(&state.db, rows.iter().zip(&readable).filter(|(_, ok)| **ok).filter_map(|(r, _)| r.last_author))
|
||||
.await?;
|
||||
// A restricted topic shows by name to members, who may ask to join.
|
||||
let pending: Vec<i16> = match viewer.user_id() {
|
||||
Some(me) => {
|
||||
sqlx::query_scalar("SELECT topic_id FROM forum.topic_members WHERE user_id = $1 AND status = 'pending'")
|
||||
.bind(me)
|
||||
.fetch_all(&state.db)
|
||||
.await?
|
||||
}
|
||||
None => Vec::new(),
|
||||
};
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.zip(readable)
|
||||
.filter(|(r, _)| r.visibility != "restricted" || viewer.member.is_some() || viewer.is_moderator())
|
||||
.map(|(r, readable)| {
|
||||
let membership = (r.visibility == "restricted").then(|| {
|
||||
if viewer.topics.contains(&r.id) {
|
||||
"approved"
|
||||
} else if pending.contains(&r.id) {
|
||||
"pending"
|
||||
} else {
|
||||
"none"
|
||||
}
|
||||
});
|
||||
let mut topic = json!({
|
||||
"id": r.id,
|
||||
"slug": r.slug,
|
||||
"name": r.name,
|
||||
"description": r.description,
|
||||
"visibility": r.visibility,
|
||||
"listening": r.listening,
|
||||
"archived": r.archived,
|
||||
"readable": readable,
|
||||
"membership": membership,
|
||||
});
|
||||
if readable {
|
||||
topic["thread_count"] = json!(r.thread_count);
|
||||
topic["new_count"] = json!(r.new_count);
|
||||
topic["last"] = json!(r.last_at.map(|at| json!({
|
||||
"author": r.last_author.and_then(|id| people.get(&id).cloned()),
|
||||
"at": rfc3339(at),
|
||||
})));
|
||||
}
|
||||
topic
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// What the header and the front page show about the viewer.
|
||||
pub fn viewer_json(viewer: &Viewer) -> Value {
|
||||
let now = OffsetDateTime::now_utc();
|
||||
json!({
|
||||
"logged_in": viewer.logged_in(),
|
||||
"needs_nickname": viewer.logged_in() && viewer.member.is_none(),
|
||||
"moderator": viewer.is_moderator(),
|
||||
"member": viewer.member.as_ref().map(|m| {
|
||||
let rank = m.rank(now);
|
||||
json!({
|
||||
"nickname": m.nickname,
|
||||
"avatar": m.avatar,
|
||||
"rank": rank,
|
||||
"rank_name": rank.name(),
|
||||
"banned": m.banned(now),
|
||||
})
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
/// The front page: the viewer, new replies in followed threads, the topics,
|
||||
/// threads waiting for a first reply, and the busiest threads of the day.
|
||||
pub async fn home(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||
let (me, since) = card_params(&viewer);
|
||||
let topics = topic_list(&state, &viewer).await?;
|
||||
|
||||
let followed = followed_counts(&state, &viewer).await?;
|
||||
|
||||
let unanswered: Vec<CardRow> = sqlx::query_as(&format!(
|
||||
"{} AND th.reply_count = 0 AND NOT th.locked AND th.author_id IS DISTINCT FROM $1 AND tp.archived_at IS NULL \
|
||||
AND th.created_at > now() - make_interval(days => $3) \
|
||||
ORDER BY th.created_at LIMIT 3",
|
||||
card_sql(&viewer)
|
||||
))
|
||||
.bind(me)
|
||||
.bind(since)
|
||||
.bind(UNANSWERED_DAYS)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
|
||||
let hot: Vec<CardRow> = sqlx::query_as(&format!(
|
||||
"WITH recent AS (SELECT thread_id, count(*) AS n FROM forum.posts \
|
||||
WHERE created_at > now() - interval '24 hours' AND deleted_at IS NULL AND NOT is_opening \
|
||||
GROUP BY thread_id HAVING count(*) >= $3) \
|
||||
{} AND th.id IN (SELECT thread_id FROM recent) AND tp.archived_at IS NULL \
|
||||
ORDER BY (SELECT n FROM recent WHERE recent.thread_id = th.id) DESC, th.last_post_at DESC LIMIT 5",
|
||||
card_sql(&viewer)
|
||||
))
|
||||
.bind(me)
|
||||
.bind(since)
|
||||
.bind(HOT_MIN_REPLIES)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
|
||||
// "Most itt vannak": members seen in the last few minutes (not the invisible ones).
|
||||
let present: Vec<Uuid> = sqlx::query_scalar(
|
||||
"SELECT user_id FROM forum.members WHERE NOT invisible \
|
||||
AND last_seen_at > now() - make_interval(mins => $1) ORDER BY last_seen_at DESC LIMIT 24",
|
||||
)
|
||||
.bind(crate::auth::ONLINE_MINUTES as i32)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let people = super::authors(&state.db, present.iter().copied()).await?;
|
||||
let online: Vec<Value> =
|
||||
present.iter().filter(|id| !viewer.mutes.contains(id)).filter_map(|id| people.get(id).cloned()).collect();
|
||||
|
||||
// Volunteer listeners: threads asking to be heard, still without a reply.
|
||||
let waiting = match &viewer.member {
|
||||
Some(m) if m.listener => Some(waiting_count(&state, &viewer).await?),
|
||||
_ => None,
|
||||
};
|
||||
let replies = match &viewer.member {
|
||||
Some(m) => Some(super::replies::unread_count(&state.db, &viewer, m.user_id).await?),
|
||||
None => None,
|
||||
};
|
||||
Ok(Json(json!({
|
||||
"viewer": viewer_json(&viewer),
|
||||
"followed": followed,
|
||||
"replies": replies,
|
||||
"waiting": waiting,
|
||||
"online": online,
|
||||
"topics": topics,
|
||||
"unanswered": cards_json(&state.db, unanswered).await?,
|
||||
"hot": cards_json(&state.db, hot).await?,
|
||||
})))
|
||||
}
|
||||
|
||||
/// New replies (by others, unread) in the member's followed threads.
|
||||
async fn followed_counts(state: &St, viewer: &Viewer) -> ApiResult<Option<Value>> {
|
||||
let (Some(me), Some(since)) = card_params(viewer) else { return Ok(None) };
|
||||
let (replies, threads): (i64, i64) = sqlx::query_as(
|
||||
"SELECT count(*), count(DISTINCT p.thread_id) FROM forum.follows f \
|
||||
JOIN forum.threads th ON th.id = f.thread_id AND th.deleted_at IS NULL \
|
||||
JOIN forum.posts p ON p.thread_id = f.thread_id AND p.deleted_at IS NULL \
|
||||
WHERE f.user_id = $1 AND p.author_id IS DISTINCT FROM $1 AND p.created_at > $2 \
|
||||
AND NOT EXISTS (SELECT 1 FROM forum.mutes mu WHERE mu.user_id = $1 AND mu.muted_id = p.author_id) \
|
||||
AND p.id > COALESCE((SELECT r.last_post_id FROM forum.reads r \
|
||||
WHERE r.user_id = $1 AND r.thread_id = f.thread_id), 0)",
|
||||
)
|
||||
.bind(me)
|
||||
.bind(since)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
Ok(Some(json!({ "new_replies": replies, "threads": threads })))
|
||||
}
|
||||
|
||||
/// Threads asking to be heard (or in a listening topic) that have waited an
|
||||
/// hour without a reply (two weeks at most), not the listener's own.
|
||||
pub const WAITING_SQL: &str = "th.reply_count = 0 AND NOT th.locked AND th.deleted_at IS NULL AND NOT th.system \
|
||||
AND th.created_at < now() - interval '1 hour' AND th.created_at > now() - interval '14 days' \
|
||||
AND (th.intent = 'listen' OR tp.listening) AND tp.archived_at IS NULL";
|
||||
|
||||
async fn waiting_count(state: &St, viewer: &Viewer) -> ApiResult<i64> {
|
||||
let me = viewer.user_id();
|
||||
Ok(sqlx::query_scalar(&format!(
|
||||
"SELECT count(*) FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
|
||||
WHERE {WAITING_SQL} AND th.author_id IS DISTINCT FROM $1 AND ({})",
|
||||
super::visible_topics(viewer)
|
||||
))
|
||||
.bind(me)
|
||||
.fetch_one(&state.db)
|
||||
.await?)
|
||||
}
|
||||
|
||||
/// For the forum's menu on every page: who the viewer is, and the badge.
|
||||
pub async fn nav(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||
let messages = match &viewer.member {
|
||||
Some(m) => Some(super::messages::unread_count(&state.db, m.user_id).await?),
|
||||
None => None,
|
||||
};
|
||||
let reports = if viewer.is_moderator() {
|
||||
let requests: i64 = sqlx::query_scalar("SELECT count(*) FROM forum.topic_members WHERE status = 'pending'")
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
Some(super::reports::open_count(&state.db).await? + requests)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// The only count on the forum tab: unread answers to the member.
|
||||
let replies = match &viewer.member {
|
||||
Some(m) => Some(super::replies::unread_count(&state.db, &viewer, m.user_id).await?),
|
||||
None => None,
|
||||
};
|
||||
Ok(Json(json!({
|
||||
"viewer": viewer_json(&viewer),
|
||||
"replies": replies,
|
||||
"messages": messages,
|
||||
"reports": reports,
|
||||
})))
|
||||
}
|
||||
|
||||
pub async fn topics(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||
Ok(Json(json!({ "topics": topic_list(&state, &viewer).await? })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct PageQuery {
|
||||
#[serde(default)]
|
||||
page: Option<i64>,
|
||||
}
|
||||
|
||||
/// A topic's threads: pinned ones first, then by the latest post.
|
||||
pub async fn topic(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(slug), _): WithRejection<Path<String>, ApiError>,
|
||||
WithRejection(Query(q), _): WithRejection<Query<PageQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let topic: Option<(i16, String, String, String, bool, bool)> = sqlx::query_as(
|
||||
"SELECT id, name, description, visibility, listening, archived_at IS NOT NULL FROM forum.topics WHERE slug = $1",
|
||||
)
|
||||
.bind(&slug)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let (id, name, description, visibility, listening, archived) = topic.ok_or(ApiError::NotFound("topic"))?;
|
||||
if !may_read(&viewer, &visibility, id) {
|
||||
// A members-only topic asks for a login; a restricted one stays hidden.
|
||||
return Err(if visibility == "members" { ApiError::Unauthorized } else { ApiError::NotFound("topic") });
|
||||
}
|
||||
let page = q.page.unwrap_or(1).clamp(1, 10_000);
|
||||
let (me, since) = card_params(&viewer);
|
||||
let rows: Vec<CardRow> = sqlx::query_as(&format!(
|
||||
"{} AND th.topic_id = $3 ORDER BY th.pinned DESC, th.last_post_at DESC LIMIT $4 OFFSET $5",
|
||||
card_sql(&viewer)
|
||||
))
|
||||
.bind(me)
|
||||
.bind(since)
|
||||
.bind(id)
|
||||
.bind(PAGE_SIZE + 1)
|
||||
.bind((page - 1) * PAGE_SIZE)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let has_more = rows.len() as i64 > PAGE_SIZE;
|
||||
let rows = rows.into_iter().take(PAGE_SIZE as usize).collect();
|
||||
Ok(Json(json!({
|
||||
"viewer": viewer_json(&viewer),
|
||||
"topic": {
|
||||
"slug": slug, "name": name, "description": description,
|
||||
"visibility": visibility, "listening": listening, "archived": archived,
|
||||
},
|
||||
"threads": cards_json(&state.db, rows).await?,
|
||||
"page": page,
|
||||
"has_more": has_more,
|
||||
})))
|
||||
}
|
||||
|
||||
/// The threads the member follows, the latest activity first, with what is unread.
|
||||
pub async fn followed(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||
viewer.require_member()?;
|
||||
let (me, since) = card_params(&viewer);
|
||||
let rows: Vec<CardRow> = sqlx::query_as(&format!(
|
||||
"{} AND th.id IN (SELECT thread_id FROM forum.follows WHERE user_id = $1) \
|
||||
ORDER BY th.last_post_at DESC LIMIT 50",
|
||||
card_sql(&viewer)
|
||||
))
|
||||
.bind(me)
|
||||
.bind(since)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
Ok(Json(json!({ "viewer": viewer_json(&viewer), "threads": cards_json(&state.db, rows).await? })))
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
//! 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<Json<Value>> {
|
||||
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 listener, an own picture.
|
||||
"can_listen": viewer.is_moderator() || !rank.is_newcomer(),
|
||||
"can_upload_avatar": viewer.is_moderator() || !rank.is_newcomer(),
|
||||
})
|
||||
});
|
||||
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<String>,
|
||||
#[serde(default)]
|
||||
bio: Option<String>,
|
||||
#[serde(default)]
|
||||
chart_share: Option<String>,
|
||||
#[serde(default)]
|
||||
invisible: Option<bool>,
|
||||
/// E-mail notifications: `{"replies": "off|daily|instant", "followed": "off|daily", "messages": "off|instant"}`.
|
||||
#[serde(default)]
|
||||
email: Option<EmailSettings>,
|
||||
/// Volunteering as a listener (from the Kereső rank).
|
||||
#[serde(default)]
|
||||
listener: Option<bool>,
|
||||
/// Showing the "Támogató" badge (buyers only).
|
||||
#[serde(default)]
|
||||
supporter_badge: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct EmailSettings {
|
||||
#[serde(default)]
|
||||
replies: Option<String>,
|
||||
#[serde(default)]
|
||||
followed: Option<String>,
|
||||
#[serde(default)]
|
||||
messages: Option<String>,
|
||||
#[serde(default)]
|
||||
mentions: Option<String>,
|
||||
#[serde(default)]
|
||||
listener: Option<String>,
|
||||
#[serde(default)]
|
||||
weekly: Option<bool>,
|
||||
}
|
||||
|
||||
fn one_of(value: Option<&str>, allowed: &[&str]) -> ApiResult<Option<String>> {
|
||||
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<bool, sqlx::Error> {
|
||||
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<SaveMe>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
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<Query<NameQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
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<Query<TokenQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
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<OffsetDateTime>,
|
||||
banned_until: Option<OffsetDateTime>,
|
||||
ban_reason: Option<String>,
|
||||
}
|
||||
|
||||
#[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<Path<String>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
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<RecentRow> = 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::<Vec<_>>(),
|
||||
})))
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
//! "@Holdfény" in a post: the members it names follow the thread (so it shows
|
||||
//! as new for them), hear of it live, and by e-mail if they asked. Nicknames
|
||||
//! may hold spaces, so after an "@" the longest text that folds into a
|
||||
//! member's nickname wins ("@Hold fény" too).
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Query, State};
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{St, authors};
|
||||
use crate::AppState;
|
||||
use crate::auth::Viewer;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::text;
|
||||
|
||||
/// Members named in one post, at most.
|
||||
const MAX_MENTIONS: usize = 10;
|
||||
/// Characters looked at after an "@".
|
||||
const LOOK_AHEAD: usize = 30;
|
||||
|
||||
/// For each "@" (at the start of a word), the folded forms of the text after
|
||||
/// it, longest last.
|
||||
fn candidates(body: &str) -> Vec<Vec<String>> {
|
||||
let chars: Vec<char> = body.chars().collect();
|
||||
let mut out = Vec::new();
|
||||
for (i, c) in chars.iter().enumerate() {
|
||||
if *c != '@' || (i > 0 && chars[i - 1].is_alphanumeric()) {
|
||||
continue;
|
||||
}
|
||||
let mut keys = Vec::new();
|
||||
let mut taken = String::new();
|
||||
for &next in chars.iter().skip(i + 1).take(LOOK_AHEAD) {
|
||||
if next == '\n' || next == '@' {
|
||||
break;
|
||||
}
|
||||
taken.push(next);
|
||||
let key = text::nickname_key(&taken);
|
||||
if key.len() >= text::NICKNAME_MIN && keys.last() != Some(&key) {
|
||||
keys.push(key);
|
||||
}
|
||||
}
|
||||
if !keys.is_empty() {
|
||||
out.push(keys);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The members a text names (not its author), longest match per "@".
|
||||
pub async fn named(db: &PgPool, body: &str, author: Uuid) -> Result<Vec<Uuid>, sqlx::Error> {
|
||||
let per_at = candidates(body);
|
||||
let all: Vec<String> = per_at.iter().flatten().cloned().collect::<HashSet<_>>().into_iter().collect();
|
||||
if all.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let found: Vec<(Uuid, String)> =
|
||||
sqlx::query_as("SELECT user_id, nickname_key FROM forum.members WHERE nickname_key = ANY($1)")
|
||||
.bind(&all)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
let mut users = Vec::new();
|
||||
for keys in per_at {
|
||||
if let Some((user, _)) = keys.iter().rev().find_map(|k| found.iter().find(|(_, key)| key == k))
|
||||
&& *user != author
|
||||
&& !users.contains(user)
|
||||
{
|
||||
users.push(*user);
|
||||
}
|
||||
if users.len() >= MAX_MENTIONS {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(users)
|
||||
}
|
||||
|
||||
/// Records the mentions of a post; returns the members named for the first
|
||||
/// time, who may read the thread (a restricted topic: its members only).
|
||||
pub async fn record(state: &AppState, thread: i64, post: i64, author: Uuid, body: &str) -> Vec<Uuid> {
|
||||
let result: Result<Vec<Uuid>, sqlx::Error> = async {
|
||||
let users = named(&state.db, body, author).await?;
|
||||
if users.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let readers: Vec<Uuid> = sqlx::query_scalar(
|
||||
"SELECT u.id FROM users u JOIN forum.threads th ON th.id = $2 JOIN forum.topics tp ON tp.id = th.topic_id \
|
||||
WHERE u.id = ANY($1) AND (tp.visibility <> 'restricted' \
|
||||
OR 'moderator' = ANY(u.roles) OR 'admin' = ANY(u.roles) \
|
||||
OR EXISTS (SELECT 1 FROM forum.topic_members tm \
|
||||
WHERE tm.topic_id = tp.id AND tm.user_id = u.id AND tm.status = 'approved'))",
|
||||
)
|
||||
.bind(&users)
|
||||
.bind(thread)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let mut fresh = Vec::new();
|
||||
for user in readers {
|
||||
let inserted =
|
||||
sqlx::query("INSERT INTO forum.mentions (post_id, user_id) VALUES ($1, $2) ON CONFLICT DO NOTHING")
|
||||
.bind(post)
|
||||
.bind(user)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
if inserted.rows_affected() == 1 {
|
||||
sqlx::query("INSERT INTO forum.follows (user_id, thread_id) VALUES ($1, $2) ON CONFLICT DO NOTHING")
|
||||
.bind(user)
|
||||
.bind(thread)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
fresh.push(user);
|
||||
}
|
||||
}
|
||||
Ok(fresh)
|
||||
}
|
||||
.await;
|
||||
match result {
|
||||
Ok(fresh) => fresh,
|
||||
Err(e) => {
|
||||
tracing::error!(error = %e, post, "recording mentions");
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// After a post is saved: mentions recorded, the named told live and by e-mail.
|
||||
pub async fn after_post(state: &AppState, thread: i64, post: i64, author: Uuid, body: &str) {
|
||||
let fresh = record(state, thread, post, author, body).await;
|
||||
if fresh.is_empty() {
|
||||
return;
|
||||
}
|
||||
crate::mail::after_mention(state, thread, post, author, &fresh, body).await;
|
||||
crate::live::emit(&state.db, crate::live::Event::default().for_users(fresh)).await;
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct SearchQuery {
|
||||
q: String,
|
||||
}
|
||||
|
||||
/// While typing "@Ho…": members whose nickname starts so (the recently seen first).
|
||||
pub async fn search(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Query(q), _): WithRejection<Query<SearchQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
viewer.require_member()?;
|
||||
let key = text::nickname_key(&q.q);
|
||||
if key.is_empty() {
|
||||
return Ok(Json(json!({ "members": [] })));
|
||||
}
|
||||
let ids: Vec<Uuid> = sqlx::query_scalar(
|
||||
"SELECT user_id FROM forum.members WHERE nickname_key LIKE $1 || '%' \
|
||||
ORDER BY last_seen_at DESC NULLS LAST LIMIT 6",
|
||||
)
|
||||
.bind(&key)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let people = authors(&state.db, ids.iter().copied()).await?;
|
||||
Ok(Json(json!({ "members": ids.iter().filter_map(|id| people.get(id)).collect::<Vec<_>>() })))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn finds_the_text_after_each_at() {
|
||||
let found = candidates("Szia @Hold fény, és @zöldág! e-mail: a@b.hu");
|
||||
assert_eq!(found.len(), 2, "not inside an e-mail address");
|
||||
assert!(found[0].contains(&"holdfeny".to_string()));
|
||||
assert!(found[1].contains(&"zoldag".to_string()));
|
||||
assert!(candidates("@ab").is_empty(), "too short to be a nickname");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,517 @@
|
||||
//! 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: from the Kereső rank and after
|
||||
/// writing in public (moderators always).
|
||||
fn may_request(viewer: &Viewer, member: &Member) -> bool {
|
||||
viewer.is_moderator() || (!member.rank(OffsetDateTime::now_utc()).is_newcomer() && member.post_count > 0)
|
||||
}
|
||||
|
||||
/// 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(
|
||||
"Beszélgetést a Kereső rangtól kezdeményezhetsz, ha már írtál a fórumba. A neked küldött kéréseket addig is 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;
|
||||
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?;
|
||||
}
|
||||
}
|
||||
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;
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
//! HTTP routes, all under `/v1/forum`.
|
||||
//!
|
||||
//! Reading is open (members-only topics need a login); writing needs a
|
||||
//! nickname ([`Viewer::require_writer`]); moderation the moderator or admin
|
||||
//! role. A thread in a topic the viewer may not read answers 404, so its
|
||||
//! existence is not revealed.
|
||||
|
||||
mod attachments;
|
||||
mod avatars;
|
||||
mod home;
|
||||
mod members;
|
||||
mod mentions;
|
||||
mod messages;
|
||||
mod moderation;
|
||||
mod mutes;
|
||||
mod posts;
|
||||
mod replies;
|
||||
mod reports;
|
||||
mod search;
|
||||
mod threads;
|
||||
mod topics;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::{Path, State};
|
||||
use axum::routing::{get, post, put};
|
||||
use axum::{Json, Router};
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgPool;
|
||||
use time::OffsetDateTime;
|
||||
use tower_http::trace::TraceLayer;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::AppState;
|
||||
use crate::auth::{ONLINE_MINUTES, Viewer};
|
||||
use crate::error::ApiError;
|
||||
use crate::rank::Rank;
|
||||
|
||||
pub type Body<T> = WithRejection<Json<T>, ApiError>;
|
||||
pub type IdPath = WithRejection<Path<i64>, ApiError>;
|
||||
pub type St = State<Arc<AppState>>;
|
||||
|
||||
pub fn router(state: Arc<AppState>) -> Router {
|
||||
Router::new()
|
||||
.route("/healthz", get(health))
|
||||
.route("/v1/forum/home", get(home::home))
|
||||
.route("/v1/forum/nav", get(home::nav))
|
||||
.route("/v1/forum/topics", get(home::topics).post(topics::create))
|
||||
.route("/v1/forum/topics/{slug}", get(home::topic).patch(topics::update))
|
||||
.route("/v1/forum/topics/{slug}/join", post(topics::join).delete(topics::leave))
|
||||
.route("/v1/forum/mod/topic-requests", get(topics::requests).post(topics::decide))
|
||||
.route("/v1/forum/followed", get(home::followed))
|
||||
.route("/v1/forum/replies", get(replies::list))
|
||||
.route("/v1/forum/search", get(search::search))
|
||||
.route("/v1/forum/share-card/{slug}", get(attachments::preview))
|
||||
.route("/v1/forum/link-thumbs/{file}", get(crate::links::thumbnail))
|
||||
.route("/v1/forum/posts/{id}/share", axum::routing::delete(posts::detach_share))
|
||||
.route("/v1/forum/sitemap", get(search::sitemap))
|
||||
.route("/v1/forum/replies/read", post(replies::read_all))
|
||||
.route("/v1/forum/threads", post(threads::create))
|
||||
.route("/v1/forum/threads/{id}", get(threads::show).patch(threads::update).delete(threads::remove))
|
||||
.route("/v1/forum/threads/{id}/restore", post(threads::restore))
|
||||
.route("/v1/forum/threads/{id}/posts", post(threads::reply))
|
||||
.route("/v1/forum/threads/{id}/read", post(threads::mark_read))
|
||||
.route("/v1/forum/threads/{id}/follow", put(threads::follow).delete(threads::unfollow))
|
||||
.route("/v1/forum/posts/{id}", axum::routing::patch(posts::edit).delete(posts::remove))
|
||||
.route("/v1/forum/posts/{id}/restore", post(posts::restore))
|
||||
.route("/v1/forum/posts/{id}/reaction", put(posts::react).delete(posts::unreact))
|
||||
.route("/v1/forum/posts/{id}/helped", put(posts::mark_helped).delete(posts::unmark_helped))
|
||||
.route("/v1/forum/posts/{id}/report", post(reports::report_post))
|
||||
.route("/v1/forum/messages/{id}/report", post(reports::report_message))
|
||||
.route("/v1/forum/conversations", get(messages::list).post(messages::request))
|
||||
.route("/v1/forum/conversations/{id}", get(messages::show))
|
||||
.route("/v1/forum/conversations/{id}/accept", post(messages::accept))
|
||||
.route("/v1/forum/conversations/{id}/decline", post(messages::decline))
|
||||
.route("/v1/forum/conversations/{id}/block", post(messages::block).delete(messages::unblock))
|
||||
.route("/v1/forum/conversations/{id}/messages", post(messages::send))
|
||||
.route("/v1/forum/conversations/{id}/read", post(messages::read))
|
||||
.route("/v1/forum/me", get(members::me).put(members::save_me))
|
||||
.route(
|
||||
"/v1/forum/me/avatar",
|
||||
put(avatars::upload).layer(axum::extract::DefaultBodyLimit::max(avatars::MAX_UPLOAD + 1024)),
|
||||
)
|
||||
.route("/v1/forum/avatars/{file}", get(avatars::serve))
|
||||
.route("/v1/forum/members/{nickname}/avatar-reset", post(avatars::reset))
|
||||
.route("/v1/forum/nickname-check", get(members::nickname_check))
|
||||
.route("/v1/forum/presence", post(members::presence))
|
||||
.route("/v1/forum/unsubscribe", post(members::unsubscribe))
|
||||
.route("/v1/forum/ws", get(crate::live::connect))
|
||||
.route("/v1/forum/members/search", get(mentions::search))
|
||||
.route("/v1/forum/members/{nickname}", get(members::profile))
|
||||
.route("/v1/forum/members/{nickname}/mute", put(mutes::mute).delete(mutes::unmute))
|
||||
.route("/v1/forum/members/{nickname}/founder", put(mutes::set_founder))
|
||||
.route("/v1/forum/me/mutes", get(mutes::list))
|
||||
.route("/v1/forum/members/{nickname}/ban", post(moderation::ban).delete(moderation::unban))
|
||||
.route("/v1/forum/mod/log", get(moderation::log))
|
||||
.route("/v1/forum/mod/reports", get(reports::list))
|
||||
.route("/v1/forum/mod/reports/{id}", post(reports::handle))
|
||||
// The request log: masked paths, health checks only when they fail.
|
||||
.layer(TraceLayer::new_for_http().make_span_with(service_kit::RequestLog).on_response(service_kit::RequestLog))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
async fn health(State(state): St) -> Result<Json<Value>, ApiError> {
|
||||
sqlx::query("SELECT 1").execute(&state.db).await?;
|
||||
Ok(Json(json!({ "status": "ok" })))
|
||||
}
|
||||
|
||||
/// The topics the viewer may read, as an SQL condition on `tp` (forum.topics).
|
||||
/// Built from the viewer's flags and their approved topic ids only, never
|
||||
/// from input.
|
||||
pub fn visible_topics(viewer: &Viewer) -> String {
|
||||
if viewer.is_moderator() {
|
||||
"TRUE".into()
|
||||
} else if viewer.logged_in() {
|
||||
let mut sql = "tp.visibility IN ('public', 'members')".to_string();
|
||||
if !viewer.topics.is_empty() {
|
||||
let ids: Vec<String> = viewer.topics.iter().map(|id| id.to_string()).collect();
|
||||
sql.push_str(&format!(" OR tp.id IN ({})", ids.join(", ")));
|
||||
}
|
||||
sql
|
||||
} else {
|
||||
"tp.visibility = 'public'".into()
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the viewer may read a topic of this visibility (restricted: only
|
||||
/// moderators and the approved members).
|
||||
pub fn may_read(viewer: &Viewer, visibility: &str, topic: i16) -> bool {
|
||||
match visibility {
|
||||
"public" => true,
|
||||
"members" => viewer.logged_in(),
|
||||
_ => viewer.is_moderator() || viewer.topics.contains(&topic),
|
||||
}
|
||||
}
|
||||
|
||||
/// A thread in a list: what the cards on the forum pages show.
|
||||
#[derive(sqlx::FromRow)]
|
||||
pub struct CardRow {
|
||||
pub id: i64,
|
||||
pub title: String,
|
||||
pub intent: Option<String>,
|
||||
pub author_id: Option<Uuid>,
|
||||
pub created_at: OffsetDateTime,
|
||||
pub last_post_at: OffsetDateTime,
|
||||
pub reply_count: i32,
|
||||
pub pinned: bool,
|
||||
pub locked: bool,
|
||||
pub topic_slug: String,
|
||||
pub topic_name: String,
|
||||
pub participants: i64,
|
||||
/// Posts by others the member has not read; `None` for visitors.
|
||||
pub unread: Option<i64>,
|
||||
/// The site's own thread (the daily sky).
|
||||
pub system: bool,
|
||||
}
|
||||
|
||||
/// `SELECT` of [`CardRow`]s over the threads the viewer may read; `$1` is
|
||||
/// the member's user id and `$2` when they joined (both NULL for a visitor),
|
||||
/// so the caller's own parameters start at `$3`. Append `AND …`, `ORDER BY`, `LIMIT`.
|
||||
/// `col` (an author) is not muted by the viewer, `$1` (true for visitors).
|
||||
pub fn not_muted(col: &str) -> String {
|
||||
format!("NOT EXISTS (SELECT 1 FROM forum.mutes mu WHERE mu.user_id = $1 AND mu.muted_id = {col})")
|
||||
}
|
||||
|
||||
pub fn card_sql(viewer: &Viewer) -> String {
|
||||
format!(
|
||||
"SELECT th.id, th.title, th.intent, th.author_id, th.created_at, th.last_post_at, th.reply_count, \
|
||||
th.pinned, th.locked, tp.slug AS topic_slug, tp.name AS topic_name, \
|
||||
(SELECT count(DISTINCT p.author_id) FROM forum.posts p \
|
||||
WHERE p.thread_id = th.id AND p.deleted_at IS NULL) AS participants, \
|
||||
CASE WHEN $1::uuid IS NULL THEN NULL ELSE \
|
||||
(SELECT count(*) FROM forum.posts p \
|
||||
WHERE p.thread_id = th.id AND p.deleted_at IS NULL AND p.author_id IS DISTINCT FROM $1 \
|
||||
AND p.created_at > $2::timestamptz AND {} \
|
||||
AND p.id > COALESCE((SELECT r.last_post_id FROM forum.reads r \
|
||||
WHERE r.user_id = $1 AND r.thread_id = th.id), 0)) END AS unread, \
|
||||
th.system \
|
||||
FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
|
||||
WHERE th.deleted_at IS NULL AND ({}) AND {}",
|
||||
not_muted("p.author_id"),
|
||||
visible_topics(viewer),
|
||||
not_muted("th.author_id"),
|
||||
)
|
||||
}
|
||||
|
||||
/// `$1` and `$2` of [`card_sql`].
|
||||
pub fn card_params(viewer: &Viewer) -> (Option<Uuid>, Option<OffsetDateTime>) {
|
||||
match &viewer.member {
|
||||
Some(m) => (Some(m.user_id), Some(m.created_at)),
|
||||
None => (None, None),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn cards_json(db: &PgPool, rows: Vec<CardRow>) -> Result<Vec<Value>, sqlx::Error> {
|
||||
let people = authors(db, rows.iter().filter_map(|r| r.author_id)).await?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
json!({
|
||||
"id": r.id,
|
||||
"slug": crate::text::slug(&r.title),
|
||||
"title": r.title,
|
||||
"intent": r.intent,
|
||||
"topic": { "slug": r.topic_slug, "name": r.topic_name },
|
||||
"author": r.author_id.and_then(|id| people.get(&id).cloned()),
|
||||
"created_at": rfc3339(r.created_at),
|
||||
"last_post_at": rfc3339(r.last_post_at),
|
||||
"reply_count": r.reply_count,
|
||||
"participants": r.participants,
|
||||
"pinned": r.pinned,
|
||||
"locked": r.locked,
|
||||
"unread": r.unread,
|
||||
"system": r.system,
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct AuthorRow {
|
||||
user_id: Uuid,
|
||||
nickname: String,
|
||||
avatar: String,
|
||||
points: i32,
|
||||
created_at: OffsetDateTime,
|
||||
invisible: bool,
|
||||
last_seen_at: Option<OffsetDateTime>,
|
||||
chart_share: String,
|
||||
roles: Vec<String>,
|
||||
listener: bool,
|
||||
supporter: bool,
|
||||
founder: bool,
|
||||
}
|
||||
|
||||
/// How members appear next to what they wrote: nickname, avatar, rank,
|
||||
/// moderator badge, online dot, and the signs they chose to share.
|
||||
pub async fn authors(db: &PgPool, ids: impl IntoIterator<Item = Uuid>) -> Result<HashMap<Uuid, Value>, sqlx::Error> {
|
||||
let mut ids: Vec<Uuid> = ids.into_iter().collect();
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
if ids.is_empty() {
|
||||
return Ok(HashMap::new());
|
||||
}
|
||||
let rows: Vec<AuthorRow> = sqlx::query_as(
|
||||
"SELECT m.user_id, m.nickname, m.avatar, m.points, m.created_at, m.invisible, m.last_seen_at, \
|
||||
m.chart_share, u.roles, m.listener, m.founder, \
|
||||
m.supporter_badge AND EXISTS (SELECT 1 FROM package_orders o \
|
||||
WHERE o.user_id = m.user_id AND o.source = 'stripe') AS supporter \
|
||||
FROM forum.members m JOIN users u ON u.id = m.user_id WHERE m.user_id = ANY($1)",
|
||||
)
|
||||
.bind(&ids)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
let sharing: Vec<Uuid> = rows.iter().filter(|r| r.chart_share != "none").map(|r| r.user_id).collect();
|
||||
let signs = shared_signs(db, &sharing).await?;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let rank = Rank::of(r.points, r.created_at, now);
|
||||
let moderator = r.roles.iter().any(|role| role == "moderator" || role == "admin");
|
||||
let shown = signs.get(&r.user_id).map(|chart| chart.share(&r.chart_share));
|
||||
let value = json!({
|
||||
"nickname": r.nickname,
|
||||
"avatar": r.avatar,
|
||||
"rank": rank,
|
||||
"rank_name": rank.name(),
|
||||
"moderator": moderator,
|
||||
"online": online(r.invisible, r.last_seen_at, now),
|
||||
"signs": shown,
|
||||
"listener": r.listener,
|
||||
"supporter": r.supporter,
|
||||
"founder": r.founder,
|
||||
});
|
||||
(r.user_id, value)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn online(invisible: bool, last_seen_at: Option<OffsetDateTime>, now: OffsetDateTime) -> bool {
|
||||
!invisible && last_seen_at.is_some_and(|t| now - t < time::Duration::minutes(ONLINE_MINUTES))
|
||||
}
|
||||
|
||||
/// The signs of a member's own chart (never degrees: they would give away the
|
||||
/// birth date and time).
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ChartSigns {
|
||||
/// Planet id → sign id, in the chart's order.
|
||||
pub planets: Vec<(String, String)>,
|
||||
/// Only when the birth time is known.
|
||||
pub ascendant: Option<String>,
|
||||
}
|
||||
|
||||
const PLANETS: [&str; 10] =
|
||||
["sun", "moon", "mercury", "venus", "mars", "jupiter", "saturn", "uranus", "neptune", "pluto"];
|
||||
|
||||
impl ChartSigns {
|
||||
fn sign(&self, id: &str) -> Option<&str> {
|
||||
self.planets.iter().find(|(p, _)| p == id).map(|(_, s)| s.as_str())
|
||||
}
|
||||
|
||||
/// What a sharing level shows; `None` for "none".
|
||||
pub fn share(&self, level: &str) -> Option<Value> {
|
||||
let mut out = serde_json::Map::new();
|
||||
let mut put = |key: &str, sign: Option<&str>| {
|
||||
if let Some(sign) = sign {
|
||||
out.insert(key.to_string(), json!(sign));
|
||||
}
|
||||
};
|
||||
match level {
|
||||
"sun" => put("sun", self.sign("sun")),
|
||||
"big3" => {
|
||||
put("sun", self.sign("sun"));
|
||||
put("moon", self.sign("moon"));
|
||||
put("ascendant", self.ascendant.as_deref());
|
||||
}
|
||||
"planets" => {
|
||||
for planet in PLANETS {
|
||||
put(planet, self.sign(planet));
|
||||
}
|
||||
put("ascendant", self.ascendant.as_deref());
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
if out.is_empty() { None } else { Some(Value::Object(out)) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The signs of each user's own chart (the current one first).
|
||||
pub async fn shared_signs(db: &PgPool, users: &[Uuid]) -> Result<HashMap<Uuid, ChartSigns>, sqlx::Error> {
|
||||
if users.is_empty() {
|
||||
return Ok(HashMap::new());
|
||||
}
|
||||
type Row = (Uuid, Option<Value>, Option<String>, Option<bool>);
|
||||
let rows: Vec<Row> = sqlx::query_as(
|
||||
"SELECT DISTINCT ON (owner_id) owner_id, result->'points', result->'angles'->'ascendant'->>'sign', \
|
||||
(result->'time'->>'time_known')::boolean \
|
||||
FROM charts WHERE owner_id = ANY($1) AND kind = 'own' ORDER BY owner_id, is_primary DESC, created_at",
|
||||
)
|
||||
.bind(users)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|(owner, points, ascendant, time_known)| {
|
||||
let planets = points
|
||||
.as_ref()
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|p| Some((p["id"].as_str()?.to_string(), p["sign"].as_str()?.to_string())))
|
||||
.filter(|(id, _)| PLANETS.contains(&id.as_str()))
|
||||
.collect();
|
||||
let ascendant = ascendant.filter(|_| time_known.unwrap_or(false));
|
||||
(owner, ChartSigns { planets, ascendant })
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn rfc3339(t: OffsetDateTime) -> String {
|
||||
t.format(&time::format_description::well_known::Rfc3339).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether the user bought a package (lifts the newcomer limits).
|
||||
pub async fn has_purchase(db: &PgPool, user: Uuid) -> Result<bool, sqlx::Error> {
|
||||
sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM package_orders WHERE user_id = $1 AND source = 'stripe')")
|
||||
.bind(user)
|
||||
.fetch_one(db)
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
//! Moderation: bans and the log of every moderation step (who, what, why;
|
||||
//! a person or, later, the AI). Removing posts and threads is in their modules.
|
||||
|
||||
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 time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{Body, St, rfc3339};
|
||||
use crate::auth::Viewer;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::text;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum Action {
|
||||
DeletePost,
|
||||
RestorePost,
|
||||
DeleteThread,
|
||||
RestoreThread,
|
||||
Ban,
|
||||
Unban,
|
||||
Lock,
|
||||
Unlock,
|
||||
Pin,
|
||||
Unpin,
|
||||
ResolveReport,
|
||||
DismissReport,
|
||||
ApproveMember,
|
||||
RejectMember,
|
||||
RemoveMember,
|
||||
ResetAvatar,
|
||||
Topic,
|
||||
}
|
||||
|
||||
impl Action {
|
||||
fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Action::DeletePost => "delete_post",
|
||||
Action::RestorePost => "restore_post",
|
||||
Action::DeleteThread => "delete_thread",
|
||||
Action::RestoreThread => "restore_thread",
|
||||
Action::Ban => "ban",
|
||||
Action::Unban => "unban",
|
||||
Action::Lock => "lock",
|
||||
Action::Unlock => "unlock",
|
||||
Action::Pin => "pin",
|
||||
Action::Unpin => "unpin",
|
||||
Action::ResolveReport => "resolve_report",
|
||||
Action::DismissReport => "dismiss_report",
|
||||
Action::ApproveMember => "approve_member",
|
||||
Action::RejectMember => "reject_member",
|
||||
Action::RemoveMember => "remove_member",
|
||||
Action::ResetAvatar => "reset_avatar",
|
||||
Action::Topic => "topic",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes one line of the moderation log (a person's step).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn record(
|
||||
db: impl sqlx::PgExecutor<'_>,
|
||||
actor: Uuid,
|
||||
action: Action,
|
||||
target_user: Option<Uuid>,
|
||||
thread_id: Option<i64>,
|
||||
post_id: Option<i64>,
|
||||
reason: Option<&str>,
|
||||
until: Option<OffsetDateTime>,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.mod_log (actor_id, actor_kind, action, target_user, thread_id, post_id, reason, until) \
|
||||
VALUES ($1, 'human', $2, $3, $4, $5, $6, $7)",
|
||||
)
|
||||
.bind(actor)
|
||||
.bind(action.as_str())
|
||||
.bind(target_user)
|
||||
.bind(thread_id)
|
||||
.bind(post_id)
|
||||
.bind(reason)
|
||||
.bind(until)
|
||||
.execute(db)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Logs the closing of a report.
|
||||
pub async fn record_report(
|
||||
db: impl sqlx::PgExecutor<'_>,
|
||||
actor: Uuid,
|
||||
action: Action,
|
||||
report_id: i64,
|
||||
post_id: Option<i64>,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.mod_log (actor_id, actor_kind, action, report_id, post_id, \
|
||||
thread_id, target_user) \
|
||||
SELECT $1, 'human', $2, $3, $4, p.thread_id, p.author_id \
|
||||
FROM (SELECT 1) one LEFT JOIN forum.posts p ON p.id = $4",
|
||||
)
|
||||
.bind(actor)
|
||||
.bind(action.as_str())
|
||||
.bind(report_id)
|
||||
.bind(post_id)
|
||||
.execute(db)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A ban for good: the last day of year 9999.
|
||||
fn forever() -> OffsetDateTime {
|
||||
let day = time::Date::from_calendar_date(9999, time::Month::December, 31).expect("valid date");
|
||||
time::PrimitiveDateTime::new(day, time::Time::MIDNIGHT).assume_utc()
|
||||
}
|
||||
|
||||
/// The longest temporary ban, in hours (a year); longer is a ban for good.
|
||||
const MAX_BAN_HOURS: i64 = 24 * 365;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct BanRequest {
|
||||
/// Hours; missing or `null`: for good.
|
||||
#[serde(default)]
|
||||
hours: Option<i64>,
|
||||
#[serde(default)]
|
||||
reason: Option<String>,
|
||||
}
|
||||
|
||||
/// The member behind a nickname, and whether they are a moderator or admin.
|
||||
async fn target(db: &sqlx::PgPool, nickname: &str) -> ApiResult<(Uuid, bool)> {
|
||||
let row: Option<(Uuid, Vec<String>)> = sqlx::query_as(
|
||||
"SELECT m.user_id, u.roles FROM forum.members m JOIN users u ON u.id = m.user_id WHERE m.nickname_key = $1",
|
||||
)
|
||||
.bind(text::nickname_key(nickname))
|
||||
.fetch_optional(db)
|
||||
.await?;
|
||||
let (id, roles) = row.ok_or(ApiError::NotFound("member"))?;
|
||||
Ok((id, roles.iter().any(|r| r == "moderator" || r == "admin")))
|
||||
}
|
||||
|
||||
/// A moderator bans a member for some hours or for good: they may still
|
||||
/// read, not write. Moderators and admins cannot be banned this way.
|
||||
pub async fn ban(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
|
||||
WithRejection(Json(req), _): Body<BanRequest>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let moderator = viewer.require_moderator()?;
|
||||
let (user, protected) = target(&state.db, &nickname).await?;
|
||||
if protected {
|
||||
return Err(ApiError::Forbidden("Moderátort vagy admint nem tilthatsz ki.".into()));
|
||||
}
|
||||
let reason = text::reason(req.reason.as_deref().unwrap_or(""))?;
|
||||
let until = match req.hours {
|
||||
Some(h) if (1..=MAX_BAN_HOURS).contains(&h) => OffsetDateTime::now_utc() + time::Duration::hours(h),
|
||||
Some(_) => return Err(ApiError::bad(format!("Az eltiltás 1 és {MAX_BAN_HOURS} óra között lehet."))),
|
||||
None => forever(),
|
||||
};
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE forum.members SET banned_until = $2, ban_reason = $3 WHERE user_id = $1")
|
||||
.bind(user)
|
||||
.bind(until)
|
||||
.bind(&reason)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
record(&mut *tx, moderator.id, Action::Ban, Some(user), None, None, Some(&reason), Some(until)).await?;
|
||||
tx.commit().await?;
|
||||
tracing::info!(moderator = %moderator.id, member = %user, hours = ?req.hours, "member banned");
|
||||
let payload = json!({
|
||||
"url": crate::mail::rules_url(&state),
|
||||
"action": "banned",
|
||||
"reason": reason,
|
||||
"duration": req.hours.map(crate::mail::ban_duration),
|
||||
});
|
||||
crate::mail::notify_user(&state, user, "forum_moderation", payload).await;
|
||||
Ok(Json(json!({ "banned_until": if req.hours.is_none() { "infinity".to_string() } else { rfc3339(until) } })))
|
||||
}
|
||||
|
||||
pub async fn unban(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let moderator = viewer.require_moderator()?;
|
||||
let (user, _) = target(&state.db, &nickname).await?;
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE forum.members SET banned_until = NULL, ban_reason = NULL WHERE user_id = $1")
|
||||
.bind(user)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
record(&mut *tx, moderator.id, Action::Unban, Some(user), None, None, None, None).await?;
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct LogRow {
|
||||
id: i64,
|
||||
actor: Option<String>,
|
||||
actor_kind: String,
|
||||
action: String,
|
||||
target: Option<String>,
|
||||
thread_id: Option<i64>,
|
||||
thread_title: Option<String>,
|
||||
post_id: Option<i64>,
|
||||
report_id: Option<i64>,
|
||||
reason: Option<String>,
|
||||
until: Option<OffsetDateTime>,
|
||||
created_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
/// The latest moderation steps, for moderators.
|
||||
pub async fn log(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||
viewer.require_moderator()?;
|
||||
let rows: Vec<LogRow> = sqlx::query_as(
|
||||
"SELECT l.id, COALESCE(am.nickname, au.display_name, 'admin') AS actor, l.actor_kind, l.action, \
|
||||
tm.nickname AS target, l.thread_id, th.title AS thread_title, l.post_id, l.report_id, l.reason, l.until, \
|
||||
l.created_at \
|
||||
FROM forum.mod_log l \
|
||||
LEFT JOIN forum.members am ON am.user_id = l.actor_id \
|
||||
LEFT JOIN users au ON au.id = l.actor_id \
|
||||
LEFT JOIN forum.members tm ON tm.user_id = l.target_user \
|
||||
LEFT JOIN forum.threads th ON th.id = l.thread_id \
|
||||
ORDER BY l.id DESC LIMIT 200",
|
||||
)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
Ok(Json(json!({
|
||||
"entries": rows.into_iter().map(|r| json!({
|
||||
"id": r.id,
|
||||
"actor": r.actor,
|
||||
"actor_kind": r.actor_kind,
|
||||
"action": r.action,
|
||||
"target": r.target,
|
||||
"thread": r.thread_id.map(|id| json!({ "id": id, "title": r.thread_title })),
|
||||
"post_id": r.post_id,
|
||||
"report_id": r.report_id,
|
||||
"reason": r.reason,
|
||||
"until": r.until.map(|u| if u.year() >= 9999 { "infinity".to_string() } else { rfc3339(u) }),
|
||||
"created_at": rfc3339(r.created_at),
|
||||
})).collect::<Vec<_>>(),
|
||||
})))
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
//! "Némítás": a member mutes another. The muted member's threads leave the
|
||||
//! muter's lists, their posts fold up (one click shows them), their replies
|
||||
//! and mentions no longer notify, and they drop out of "Most itt vannak".
|
||||
//! The muted member is not told, and can still be reported.
|
||||
//! (Also here: the admin's switch for the "Alapító tag" badge.)
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde_json::{Value, json};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{St, authors};
|
||||
use crate::AppState;
|
||||
use crate::auth::Viewer;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::text;
|
||||
|
||||
async fn member_id(state: &AppState, nickname: &str) -> ApiResult<Uuid> {
|
||||
sqlx::query_scalar("SELECT user_id FROM forum.members WHERE nickname_key = $1")
|
||||
.bind(text::nickname_key(nickname))
|
||||
.fetch_optional(&state.db)
|
||||
.await?
|
||||
.ok_or(ApiError::NotFound("member"))
|
||||
}
|
||||
|
||||
pub async fn mute(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let member = viewer.require_member()?;
|
||||
let target = member_id(&state, &nickname).await?;
|
||||
if target == member.user_id {
|
||||
return Err(ApiError::bad("Saját magadat nem némíthatod el."));
|
||||
}
|
||||
sqlx::query("INSERT INTO forum.mutes (user_id, muted_id) VALUES ($1, $2) ON CONFLICT DO NOTHING")
|
||||
.bind(member.user_id)
|
||||
.bind(target)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
pub async fn unmute(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let member = viewer.require_member()?;
|
||||
let target = member_id(&state, &nickname).await?;
|
||||
sqlx::query("DELETE FROM forum.mutes WHERE user_id = $1 AND muted_id = $2")
|
||||
.bind(member.user_id)
|
||||
.bind(target)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
/// The members the viewer muted (for the settings page).
|
||||
pub async fn list(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||
viewer.require_member()?;
|
||||
let people = authors(&state.db, viewer.mutes.iter().copied()).await?;
|
||||
let mut muted: Vec<Value> = viewer.mutes.iter().filter_map(|id| people.get(id).cloned()).collect();
|
||||
muted.sort_by(|a, b| a["nickname"].as_str().cmp(&b["nickname"].as_str()));
|
||||
Ok(Json(json!({ "muted": muted })))
|
||||
}
|
||||
|
||||
/// The admin takes the "Alapító tag" badge from a member (a test account) or
|
||||
/// gives it; a place taken away goes to the next newcomer.
|
||||
pub async fn set_founder(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
|
||||
WithRejection(axum::Json(req), _): WithRejection<axum::Json<FounderChange>, ApiError>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
viewer.require_user()?;
|
||||
if !viewer.is_admin() {
|
||||
return Err(ApiError::Forbidden("Ezt csak az admin teheti meg.".into()));
|
||||
}
|
||||
let target = member_id(&state, &nickname).await?;
|
||||
sqlx::query("UPDATE forum.members SET founder = $2 WHERE user_id = $1")
|
||||
.bind(target)
|
||||
.bind(req.founder)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
pub struct FounderChange {
|
||||
founder: bool,
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
//! A post: editing one's own, removal (one's own, or a moderator's with a
|
||||
//! reason), the admin's restore, reactions and the "Ez segített" mark.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
use sqlx::PgPool;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::moderation::{self, Action};
|
||||
use super::threads::{POST_COLUMNS, PostRow, REACTIONS, Reason, ThreadRow, open_thread, posts_json, readable_thread};
|
||||
use super::{Body, IdPath, St};
|
||||
use crate::auth::Viewer;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::rank::HELPED_POINTS;
|
||||
use crate::text;
|
||||
|
||||
/// Anyone viewing the thread refetches it (reactions, edits, removals).
|
||||
async fn announce(state: &crate::AppState, thread: i64) {
|
||||
crate::live::emit(&state.db, crate::live::Event { thread: Some(thread), ..Default::default() }).await;
|
||||
}
|
||||
|
||||
/// A post and its thread, both readable by the viewer.
|
||||
async fn load(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult<(PostRow, ThreadRow)> {
|
||||
let post: PostRow = sqlx::query_as(&format!("SELECT {POST_COLUMNS} FROM forum.posts WHERE id = $1"))
|
||||
.bind(id)
|
||||
.fetch_optional(db)
|
||||
.await?
|
||||
.ok_or(ApiError::NotFound("post"))?;
|
||||
let thread = readable_thread(db, viewer, post.thread_id).await?;
|
||||
Ok((post, thread))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Edit {
|
||||
body: String,
|
||||
}
|
||||
|
||||
/// The author changes their post (while the thread is open).
|
||||
pub async fn edit(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<Edit>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let member = viewer.require_writer()?;
|
||||
let (post, _) = load(&state.db, &viewer, id).await?;
|
||||
if post.author_id != Some(member.user_id) || post.deleted_at.is_some() {
|
||||
return Err(ApiError::Forbidden("Csak a saját hozzászólásodat szerkesztheted.".into()));
|
||||
}
|
||||
open_thread(&state.db, &viewer, post.thread_id).await?;
|
||||
let body = text::body(&req.body)?;
|
||||
let post: PostRow = sqlx::query_as(&format!(
|
||||
"UPDATE forum.posts SET body = $2, edited_at = now() WHERE id = $1 RETURNING {POST_COLUMNS}"
|
||||
))
|
||||
.bind(id)
|
||||
.bind(&body)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
crate::links::process(&state, &body).await;
|
||||
announce(&state, post.thread_id).await;
|
||||
super::mentions::after_post(&state, post.thread_id, post.id, member.user_id, &body).await;
|
||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||
}
|
||||
|
||||
/// The author takes back their post, or a moderator removes it with a reason.
|
||||
/// Hidden, not erased: the admin can restore it.
|
||||
pub async fn remove(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<Reason>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let user = viewer.require_user()?;
|
||||
let (post, thread) = load(&state.db, &viewer, id).await?;
|
||||
if post.deleted_at.is_some() {
|
||||
return Ok(StatusCode::NO_CONTENT);
|
||||
}
|
||||
let own = post.author_id == Some(user.id);
|
||||
let reason = if own {
|
||||
None
|
||||
} else if viewer.is_moderator() {
|
||||
Some(text::reason(req.reason.as_deref().unwrap_or(""))?)
|
||||
} else {
|
||||
return Err(ApiError::Forbidden("Csak a saját hozzászólásodat törölheted.".into()));
|
||||
};
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE forum.posts SET deleted_at = now(), deleted_by = $2, delete_reason = $3 WHERE id = $1")
|
||||
.bind(id)
|
||||
.bind(user.id)
|
||||
.bind(&reason)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
if !post.is_opening {
|
||||
sqlx::query("UPDATE forum.threads SET reply_count = greatest(reply_count - 1, 0) WHERE id = $1")
|
||||
.bind(post.thread_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
// Deleting one's own question takes the shared chart's link down too.
|
||||
if own && let Some(share) = post.share_id {
|
||||
revoke_share(&mut *tx, share, user.id).await?;
|
||||
}
|
||||
let mut reporters = Vec::new();
|
||||
if !own {
|
||||
reporters = super::reports::resolve_for_post(&mut tx, id, user.id).await?;
|
||||
moderation::record(
|
||||
&mut *tx,
|
||||
user.id,
|
||||
Action::DeletePost,
|
||||
post.author_id,
|
||||
Some(post.thread_id),
|
||||
Some(id),
|
||||
reason.as_deref(),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
if !own {
|
||||
if let Some(author) = post.author_id {
|
||||
let payload = serde_json::json!({
|
||||
"url": crate::mail::rules_url(&state),
|
||||
"action": "post_removed",
|
||||
"reason": reason,
|
||||
"thread_title": thread.title,
|
||||
});
|
||||
crate::mail::notify_user(&state, author, "forum_moderation", payload).await;
|
||||
}
|
||||
crate::mail::notify_reporters(&state, &reporters, "removed").await;
|
||||
}
|
||||
announce(&state, post.thread_id).await;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
/// The admin undoes a removal.
|
||||
pub async fn restore(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
|
||||
let admin = viewer.require_user()?;
|
||||
if !viewer.is_admin() {
|
||||
return Err(ApiError::Forbidden("Visszaállítani csak az admin tud.".into()));
|
||||
}
|
||||
let (post, _) = load(&state.db, &viewer, id).await?;
|
||||
if post.deleted_at.is_none() {
|
||||
return Ok(StatusCode::NO_CONTENT);
|
||||
}
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE forum.posts SET deleted_at = NULL, deleted_by = NULL, delete_reason = NULL WHERE id = $1")
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
if !post.is_opening {
|
||||
sqlx::query("UPDATE forum.threads SET reply_count = reply_count + 1 WHERE id = $1")
|
||||
.bind(post.thread_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
moderation::record(
|
||||
&mut *tx,
|
||||
admin.id,
|
||||
Action::RestorePost,
|
||||
post.author_id,
|
||||
Some(post.thread_id),
|
||||
Some(id),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct React {
|
||||
kind: String,
|
||||
}
|
||||
|
||||
fn points_of(kind: &str) -> i32 {
|
||||
if kind == "down" { -1 } else { 1 }
|
||||
}
|
||||
|
||||
/// Gives (or changes) the viewer's one reaction to a post. A newcomer's
|
||||
/// reaction shows but moves no points; the ⌄ needs the Kereső rank and is
|
||||
/// not offered in listening topics.
|
||||
pub async fn react(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<React>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let member = viewer.require_writer()?;
|
||||
let (post, thread) = load(&state.db, &viewer, id).await?;
|
||||
if post.deleted_at.is_some() {
|
||||
return Err(ApiError::NotFound("post"));
|
||||
}
|
||||
open_thread(&state.db, &viewer, thread.id).await?;
|
||||
if post.author_id == Some(member.user_id) {
|
||||
return Err(ApiError::Forbidden("A saját hozzászólásodra nem reagálhatsz.".into()));
|
||||
}
|
||||
let kind = req.kind.as_str();
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let rank = member.rank(now);
|
||||
if kind == "down" {
|
||||
if thread.listening {
|
||||
return Err(ApiError::Forbidden("Ebben a témában nincs ⌄.".into()));
|
||||
}
|
||||
if !rank.may_downvote() {
|
||||
return Err(ApiError::Forbidden("A ⌄ a Kereső rangtól használható.".into()));
|
||||
}
|
||||
} else if !REACTIONS.contains(&kind) {
|
||||
return Err(ApiError::bad("Ismeretlen reakció."));
|
||||
}
|
||||
let counted = !rank.is_newcomer();
|
||||
|
||||
let mut tx = state.db.begin().await?;
|
||||
let previous: Option<(String, bool)> =
|
||||
sqlx::query_as("SELECT kind, counted FROM forum.reactions WHERE post_id = $1 AND user_id = $2 FOR UPDATE")
|
||||
.bind(id)
|
||||
.bind(member.user_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
let mut delta = if counted { points_of(kind) } else { 0 };
|
||||
if let Some((old, true)) = &previous {
|
||||
delta -= points_of(old);
|
||||
}
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.reactions (post_id, user_id, kind, counted) VALUES ($1, $2, $3, $4) \
|
||||
ON CONFLICT (post_id, user_id) DO UPDATE SET kind = EXCLUDED.kind, counted = EXCLUDED.counted, created_at = now()",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(member.user_id)
|
||||
.bind(kind)
|
||||
.bind(counted)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
add_points(&mut tx, post.author_id, delta).await?;
|
||||
tx.commit().await?;
|
||||
announce(&state, post.thread_id).await;
|
||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||
}
|
||||
|
||||
pub async fn unreact(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<Json<Value>> {
|
||||
let member = viewer.require_writer()?;
|
||||
let (post, _) = load(&state.db, &viewer, id).await?;
|
||||
let mut tx = state.db.begin().await?;
|
||||
let removed: Option<(String, bool)> =
|
||||
sqlx::query_as("DELETE FROM forum.reactions WHERE post_id = $1 AND user_id = $2 RETURNING kind, counted")
|
||||
.bind(id)
|
||||
.bind(member.user_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
if let Some((kind, true)) = removed {
|
||||
add_points(&mut tx, post.author_id, -points_of(&kind)).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
announce(&state, post.thread_id).await;
|
||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||
}
|
||||
|
||||
async fn add_points(tx: &mut sqlx::PgConnection, author: Option<uuid::Uuid>, delta: i32) -> Result<(), sqlx::Error> {
|
||||
if let (Some(author), true) = (author, delta != 0) {
|
||||
sqlx::query("UPDATE forum.members SET points = points + $2 WHERE user_id = $1")
|
||||
.bind(author)
|
||||
.bind(delta)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The thread's author marks a reply that helped (worth more than a reaction).
|
||||
pub async fn mark_helped(state: St, viewer: Viewer, path: IdPath) -> ApiResult<Json<Value>> {
|
||||
set_helped(state, viewer, path, true).await
|
||||
}
|
||||
|
||||
pub async fn unmark_helped(state: St, viewer: Viewer, path: IdPath) -> ApiResult<Json<Value>> {
|
||||
set_helped(state, viewer, path, false).await
|
||||
}
|
||||
|
||||
async fn set_helped(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
on: bool,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let member = viewer.require_writer()?;
|
||||
let (post, thread) = load(&state.db, &viewer, id).await?;
|
||||
if thread.author_id != Some(member.user_id) {
|
||||
return Err(ApiError::Forbidden("Ezt csak a szál indítója jelölheti.".into()));
|
||||
}
|
||||
if post.is_opening || post.author_id == Some(member.user_id) || post.deleted_at.is_some() {
|
||||
return Err(ApiError::bad("Ezt a hozzászólást nem jelölheted."));
|
||||
}
|
||||
let mut tx = state.db.begin().await?;
|
||||
let changed: Option<i64> = if on {
|
||||
sqlx::query_scalar("UPDATE forum.posts SET helped_at = now() WHERE id = $1 AND helped_at IS NULL RETURNING id")
|
||||
} else {
|
||||
sqlx::query_scalar(
|
||||
"UPDATE forum.posts SET helped_at = NULL WHERE id = $1 AND helped_at IS NOT NULL RETURNING id",
|
||||
)
|
||||
}
|
||||
.bind(id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
if changed.is_some() {
|
||||
add_points(&mut tx, post.author_id, if on { HELPED_POINTS } else { -HELPED_POINTS }).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
announce(&state, thread.id).await;
|
||||
let post: PostRow = sqlx::query_as(&format!("SELECT {POST_COLUMNS} FROM forum.posts WHERE id = $1"))
|
||||
.bind(id)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||
}
|
||||
|
||||
/// The sharer's link goes (as when revoked on the main site).
|
||||
async fn revoke_share(db: impl sqlx::PgExecutor<'_>, share: uuid::Uuid, owner: uuid::Uuid) -> Result<(), sqlx::Error> {
|
||||
sqlx::query("UPDATE shares SET revoked_at = now() WHERE id = $1 AND owner_id = $2 AND revoked_at IS NULL")
|
||||
.bind(share)
|
||||
.bind(owner)
|
||||
.execute(db)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The author takes the shared chart off their question: the card goes, and
|
||||
/// the link stops working.
|
||||
pub async fn detach_share(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let user = viewer.require_user()?;
|
||||
let (post, _) = load(&state.db, &viewer, id).await?;
|
||||
if post.author_id != Some(user.id) {
|
||||
return Err(ApiError::Forbidden("Csak a saját kérdésedről veheted le a képletet.".into()));
|
||||
}
|
||||
let Some(share) = post.share_id else { return Ok(StatusCode::NO_CONTENT) };
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE forum.posts SET share_id = NULL WHERE id = $1").bind(id).execute(&mut *tx).await?;
|
||||
revoke_share(&mut *tx, share, user.id).await?;
|
||||
tx.commit().await?;
|
||||
announce(&state, post.thread_id).await;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
//! "Válaszok": what answers the member. A reply to one of their posts (also
|
||||
//! a reply to a reply of theirs, `reply_to_id`), a first-level reply in a
|
||||
//! thread they opened, or a post that names them ("@Holdfény"). One stays
|
||||
//! unread until the member has read that far in the thread; the forum menu
|
||||
//! shows only this count.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Query, 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::{St, rfc3339, visible_topics};
|
||||
use crate::auth::Viewer;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
|
||||
/// The posts that answer `$1`, from the threads the viewer may read.
|
||||
fn answers(viewer: &Viewer) -> String {
|
||||
format!(
|
||||
"FROM forum.posts p \
|
||||
JOIN forum.threads th ON th.id = p.thread_id \
|
||||
JOIN forum.topics tp ON tp.id = th.topic_id \
|
||||
LEFT JOIN forum.posts target ON target.id = COALESCE(p.reply_to_id, p.parent_id) \
|
||||
LEFT JOIN forum.reads r ON r.user_id = $1 AND r.thread_id = p.thread_id \
|
||||
WHERE p.deleted_at IS NULL AND th.deleted_at IS NULL AND NOT p.is_opening AND NOT p.system \
|
||||
AND p.author_id IS DISTINCT FROM $1 AND ({}) \
|
||||
AND NOT EXISTS (SELECT 1 FROM forum.mutes mu WHERE mu.user_id = $1 AND mu.muted_id = p.author_id) \
|
||||
AND (target.author_id = $1 \
|
||||
OR (p.parent_id IS NULL AND th.author_id = $1) \
|
||||
OR EXISTS (SELECT 1 FROM forum.mentions mn WHERE mn.post_id = p.id AND mn.user_id = $1))",
|
||||
visible_topics(viewer)
|
||||
)
|
||||
}
|
||||
|
||||
const UNREAD: &str = "p.id > COALESCE(r.last_post_id, 0)";
|
||||
|
||||
/// How many answers wait unread (for the menu), at most 100.
|
||||
pub async fn unread_count(db: &PgPool, viewer: &Viewer, me: Uuid) -> Result<i64, sqlx::Error> {
|
||||
sqlx::query_scalar(&format!("SELECT count(*) FROM (SELECT 1 {} AND {UNREAD} LIMIT 100) x", answers(viewer)))
|
||||
.bind(me)
|
||||
.fetch_one(db)
|
||||
.await
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ListQuery {
|
||||
#[serde(default)]
|
||||
page: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct Row {
|
||||
id: i64,
|
||||
thread_id: i64,
|
||||
title: String,
|
||||
author_id: Option<Uuid>,
|
||||
body: String,
|
||||
created_at: OffsetDateTime,
|
||||
kind: String,
|
||||
unread: bool,
|
||||
}
|
||||
|
||||
const PAGE: i64 = 30;
|
||||
|
||||
/// The member's answers, newest first.
|
||||
pub async fn list(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Query(q), _): WithRejection<Query<ListQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let member = viewer.require_member()?;
|
||||
let page = q.page.unwrap_or(1).clamp(1, 1000);
|
||||
let rows: Vec<Row> = sqlx::query_as(&format!(
|
||||
"SELECT p.id, p.thread_id, th.title, p.author_id, p.body, p.created_at, \
|
||||
CASE WHEN target.author_id = $1 THEN 'reply' \
|
||||
WHEN p.parent_id IS NULL AND th.author_id = $1 THEN 'thread' \
|
||||
ELSE 'mention' END AS kind, \
|
||||
{UNREAD} AS unread \
|
||||
{} ORDER BY p.id DESC LIMIT {} OFFSET $2",
|
||||
answers(&viewer),
|
||||
PAGE + 1
|
||||
))
|
||||
.bind(member.user_id)
|
||||
.bind((page - 1) * PAGE)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let more = rows.len() as i64 > PAGE;
|
||||
let rows = &rows[..rows.len().min(PAGE as usize)];
|
||||
let authors = super::authors(&state.db, rows.iter().filter_map(|r| r.author_id)).await?;
|
||||
let replies: Vec<Value> = rows
|
||||
.iter()
|
||||
.map(|r| {
|
||||
json!({
|
||||
"id": r.id,
|
||||
"thread": { "id": r.thread_id, "title": r.title, "slug": crate::text::slug(&r.title) },
|
||||
"author": r.author_id.and_then(|a| authors.get(&a).cloned()),
|
||||
"excerpt": excerpt(&r.body),
|
||||
"created_at": rfc3339(r.created_at),
|
||||
"kind": r.kind,
|
||||
"unread": r.unread,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let unread = unread_count(&state.db, &viewer, member.user_id).await?;
|
||||
Ok(Json(json!({ "replies": replies, "unread": unread, "page": page, "more": more })))
|
||||
}
|
||||
|
||||
/// "Mind olvasott": the threads with unread answers count as read up to them.
|
||||
pub async fn read_all(State(state): St, viewer: Viewer) -> ApiResult<StatusCode> {
|
||||
let member = viewer.require_member()?;
|
||||
sqlx::query(&format!(
|
||||
"INSERT INTO forum.reads (user_id, thread_id, last_post_id) \
|
||||
SELECT $1, p.thread_id, max(p.id) {} AND {UNREAD} GROUP BY p.thread_id \
|
||||
ON CONFLICT (user_id, thread_id) DO UPDATE \
|
||||
SET last_post_id = GREATEST(forum.reads.last_post_id, EXCLUDED.last_post_id), read_at = now()",
|
||||
answers(&viewer)
|
||||
))
|
||||
.bind(member.user_id)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
/// The start of a post, on one line.
|
||||
fn excerpt(body: &str) -> String {
|
||||
let line = body.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
match line.char_indices().nth(160) {
|
||||
Some((at, _)) => format!("{}…", line[..at].trim_end()),
|
||||
None => line,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
//! Reports (the DSA's notice and action): any logged-in user may report a
|
||||
//! post or a private message; moderators see the open ones, act on the post
|
||||
//! (removal is in `posts`) and close the report. A reported private message
|
||||
//! is the only way a moderator sees a conversation: the message and the few
|
||||
//! before it.
|
||||
|
||||
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::moderation::{self, Action};
|
||||
use super::threads::readable_thread;
|
||||
use super::{Body, IdPath, St, authors, rfc3339};
|
||||
use crate::auth::Viewer;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::text;
|
||||
|
||||
pub const KINDS: [&str; 6] = ["spam", "ad", "rude", "crisis", "illegal", "other"];
|
||||
const NOTE_MAX: usize = 500;
|
||||
/// Reports one user may send in 24 hours.
|
||||
const PER_DAY: i64 = 20;
|
||||
/// Messages shown to moderators around a reported one.
|
||||
const MESSAGE_CONTEXT: i64 = 10;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ReportRequest {
|
||||
kind: String,
|
||||
#[serde(default)]
|
||||
note: Option<String>,
|
||||
}
|
||||
|
||||
fn check(req: &ReportRequest) -> ApiResult<String> {
|
||||
if !KINDS.contains(&req.kind.as_str()) {
|
||||
return Err(ApiError::bad("Válaszd ki, mi a gond."));
|
||||
}
|
||||
let note = req.note.as_deref().unwrap_or("").split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
if note.chars().count() > NOTE_MAX {
|
||||
return Err(ApiError::bad(format!("A megjegyzés legfeljebb {NOTE_MAX} karakter lehet.")));
|
||||
}
|
||||
if req.kind == "other" && note.chars().count() < 3 {
|
||||
return Err(ApiError::bad("Írd le röviden, mi a gond."));
|
||||
}
|
||||
Ok(note)
|
||||
}
|
||||
|
||||
async fn within_limit(db: &PgPool, user: Uuid) -> ApiResult<()> {
|
||||
let today: i64 = sqlx::query_scalar(
|
||||
"SELECT count(*) FROM forum.reports WHERE reporter_id = $1 AND created_at > now() - interval '24 hours'",
|
||||
)
|
||||
.bind(user)
|
||||
.fetch_one(db)
|
||||
.await?;
|
||||
if today >= PER_DAY {
|
||||
return Err(ApiError::Limited("Ma már sok jelentést küldtél. Holnap újra lehet.".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn received(kind: &str) -> Json<Value> {
|
||||
Json(json!({ "received": true, "crisis": kind == "crisis" }))
|
||||
}
|
||||
|
||||
/// Reports a post (not one's own). A second report of the same post by the
|
||||
/// same user while the first is open changes nothing.
|
||||
pub async fn report_post(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<ReportRequest>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let user = viewer.require_user()?;
|
||||
let note = check(&req)?;
|
||||
let post: Option<(i64, Option<Uuid>)> =
|
||||
sqlx::query_as("SELECT thread_id, author_id FROM forum.posts WHERE id = $1")
|
||||
.bind(id)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let (thread_id, author) = post.ok_or(ApiError::NotFound("post"))?;
|
||||
readable_thread(&state.db, &viewer, thread_id).await?;
|
||||
if author == Some(user.id) {
|
||||
return Err(ApiError::bad("A saját hozzászólásodat nem jelentheted."));
|
||||
}
|
||||
within_limit(&state.db, user.id).await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.reports (post_id, reporter_id, kind, note) VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(user.id)
|
||||
.bind(&req.kind)
|
||||
.bind(¬e)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
tracing::info!(post = id, kind = %req.kind, "post reported");
|
||||
crate::live::emit(&state.db, crate::live::Event { moderators: true, ..Default::default() }).await;
|
||||
Ok((StatusCode::CREATED, received(&req.kind)))
|
||||
}
|
||||
|
||||
/// Reports a private message received in one's own conversation.
|
||||
pub async fn report_message(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<ReportRequest>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let user = viewer.require_user()?;
|
||||
let note = check(&req)?;
|
||||
let found: Option<(Option<Uuid>,)> = sqlx::query_as(
|
||||
"SELECT m.sender_id FROM forum.messages m JOIN forum.conversations c ON c.id = m.conversation_id \
|
||||
WHERE m.id = $1 AND $2 IN (c.user_a, c.user_b)",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(user.id)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let (sender,) = found.ok_or(ApiError::NotFound("message"))?;
|
||||
if sender == Some(user.id) {
|
||||
return Err(ApiError::bad("A saját üzenetedet nem jelentheted."));
|
||||
}
|
||||
within_limit(&state.db, user.id).await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.reports (message_id, reporter_id, kind, note) VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(user.id)
|
||||
.bind(&req.kind)
|
||||
.bind(¬e)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
tracing::info!(message = id, kind = %req.kind, "message reported");
|
||||
crate::live::emit(&state.db, crate::live::Event { moderators: true, ..Default::default() }).await;
|
||||
Ok((StatusCode::CREATED, received(&req.kind)))
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct ReportRow {
|
||||
id: i64,
|
||||
post_id: Option<i64>,
|
||||
message_id: Option<i64>,
|
||||
reporter: Option<String>,
|
||||
kind: String,
|
||||
note: String,
|
||||
status: String,
|
||||
handled_by: Option<String>,
|
||||
handled_at: Option<OffsetDateTime>,
|
||||
created_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct PostTarget {
|
||||
id: i64,
|
||||
thread_id: i64,
|
||||
title: String,
|
||||
author_id: Option<Uuid>,
|
||||
body: String,
|
||||
deleted: bool,
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct MessageRow {
|
||||
id: i64,
|
||||
conversation_id: i64,
|
||||
sender_id: Option<Uuid>,
|
||||
body: String,
|
||||
created_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
/// Open reports (the oldest first, crisis ones before all), and the last
|
||||
/// handled ones, with what was reported.
|
||||
pub async fn list(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||
viewer.require_moderator()?;
|
||||
let rows: Vec<ReportRow> = sqlx::query_as(
|
||||
"SELECT r.id, r.post_id, r.message_id, COALESCE(rm.nickname, 'tag') AS reporter, r.kind, r.note, r.status, \
|
||||
COALESCE(hm.nickname, hu.display_name) AS handled_by, r.handled_at, r.created_at \
|
||||
FROM forum.reports r \
|
||||
LEFT JOIN forum.members rm ON rm.user_id = r.reporter_id \
|
||||
LEFT JOIN forum.members hm ON hm.user_id = r.handled_by \
|
||||
LEFT JOIN users hu ON hu.id = r.handled_by \
|
||||
WHERE r.status = 'open' OR r.handled_at > now() - interval '30 days' \
|
||||
ORDER BY r.status <> 'open', r.kind <> 'crisis', \
|
||||
CASE WHEN r.status = 'open' THEN r.created_at END, r.handled_at DESC \
|
||||
LIMIT 200",
|
||||
)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
|
||||
let post_ids: Vec<i64> = rows.iter().filter_map(|r| r.post_id).collect();
|
||||
let posts: Vec<PostTarget> = sqlx::query_as(
|
||||
"SELECT p.id, p.thread_id, th.title, p.author_id, p.body, p.deleted_at IS NOT NULL AS deleted \
|
||||
FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id WHERE p.id = ANY($1)",
|
||||
)
|
||||
.bind(&post_ids)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let message_ids: Vec<i64> = rows.iter().filter_map(|r| r.message_id).collect();
|
||||
// Each reported message with the few before it in its conversation.
|
||||
let messages: Vec<(i64, MessageRow)> = sqlx::query_as::<_, (i64, i64, i64, Option<Uuid>, String, OffsetDateTime)>(
|
||||
"SELECT r.id AS reported, m.id, m.conversation_id, m.sender_id, m.body, m.created_at \
|
||||
FROM forum.messages r \
|
||||
JOIN LATERAL (SELECT * FROM forum.messages m WHERE m.conversation_id = r.conversation_id AND m.id <= r.id \
|
||||
ORDER BY m.id DESC LIMIT $2) m ON true \
|
||||
WHERE r.id = ANY($1) ORDER BY m.id",
|
||||
)
|
||||
.bind(&message_ids)
|
||||
.bind(MESSAGE_CONTEXT)
|
||||
.fetch_all(&state.db)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|(reported, id, conversation_id, sender_id, body, created_at)| {
|
||||
(reported, MessageRow { id, conversation_id, sender_id, body, created_at })
|
||||
})
|
||||
.collect();
|
||||
let people = authors(
|
||||
&state.db,
|
||||
posts.iter().filter_map(|p| p.author_id).chain(messages.iter().filter_map(|(_, m)| m.sender_id)),
|
||||
)
|
||||
.await?;
|
||||
let open_counts: Vec<(Option<i64>, Option<i64>, i64)> =
|
||||
sqlx::query_as("SELECT post_id, message_id, count(*) FROM forum.reports WHERE status = 'open' GROUP BY 1, 2")
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
|
||||
let entries: Vec<Value> = rows
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let target = if let Some(post_id) = r.post_id {
|
||||
posts.iter().find(|p| p.id == post_id).map(|p| {
|
||||
json!({
|
||||
"type": "post",
|
||||
"id": p.id,
|
||||
"thread": { "id": p.thread_id, "title": p.title, "slug": text::slug(&p.title) },
|
||||
"author": p.author_id.and_then(|a| people.get(&a).cloned()),
|
||||
"body": p.body,
|
||||
"deleted": p.deleted,
|
||||
})
|
||||
})
|
||||
} else {
|
||||
let id = r.message_id.unwrap_or_default();
|
||||
let context: Vec<Value> = messages
|
||||
.iter()
|
||||
.filter(|(reported, _)| *reported == id)
|
||||
.map(|(_, m)| {
|
||||
json!({
|
||||
"id": m.id,
|
||||
"sender": m.sender_id.and_then(|s| people.get(&s).cloned()),
|
||||
"body": m.body,
|
||||
"created_at": rfc3339(m.created_at),
|
||||
"reported": m.id == id,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let conversation =
|
||||
messages.iter().find(|(reported, _)| *reported == id).map(|(_, m)| m.conversation_id);
|
||||
Some(json!({ "type": "message", "id": id, "conversation_id": conversation, "messages": context }))
|
||||
};
|
||||
let reports = open_counts
|
||||
.iter()
|
||||
.find(|(p, m, _)| *p == r.post_id && *m == r.message_id)
|
||||
.map(|(_, _, n)| *n)
|
||||
.unwrap_or(0);
|
||||
json!({
|
||||
"id": r.id,
|
||||
"kind": r.kind,
|
||||
"note": r.note,
|
||||
"reporter": r.reporter,
|
||||
"status": r.status,
|
||||
"handled_by": r.handled_by,
|
||||
"handled_at": r.handled_at.map(rfc3339),
|
||||
"created_at": rfc3339(r.created_at),
|
||||
"open_reports_of_target": reports,
|
||||
"target": target,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Ok(Json(json!({ "reports": entries })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Handle {
|
||||
/// `resolve`: acted on (or nothing needed beyond what was done);
|
||||
/// `dismiss`: the report was unfounded.
|
||||
action: String,
|
||||
}
|
||||
|
||||
/// Closes a report, and every other open report of the same post or message.
|
||||
pub async fn handle(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<Handle>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let moderator = viewer.require_moderator()?;
|
||||
let (status, action) = match req.action.as_str() {
|
||||
"resolve" => ("resolved", Action::ResolveReport),
|
||||
"dismiss" => ("dismissed", Action::DismissReport),
|
||||
_ => return Err(ApiError::bad("Ismeretlen művelet.")),
|
||||
};
|
||||
let report: Option<(Option<i64>, Option<i64>)> =
|
||||
sqlx::query_as("SELECT post_id, message_id FROM forum.reports WHERE id = $1")
|
||||
.bind(id)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let (post_id, message_id) = report.ok_or(ApiError::NotFound("report"))?;
|
||||
let mut tx = state.db.begin().await?;
|
||||
let reporters: Vec<Option<Uuid>> = sqlx::query_scalar(
|
||||
"UPDATE forum.reports SET status = $2, handled_by = $3, handled_at = now() \
|
||||
WHERE status = 'open' AND (id = $1 OR ($4::bigint IS NOT NULL AND post_id = $4) \
|
||||
OR ($5::bigint IS NOT NULL AND message_id = $5)) \
|
||||
RETURNING reporter_id",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(status)
|
||||
.bind(moderator.id)
|
||||
.bind(post_id)
|
||||
.bind(message_id)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
moderation::record_report(&mut *tx, moderator.id, action, id, post_id).await?;
|
||||
tx.commit().await?;
|
||||
let outcome = if status == "resolved" { "handled" } else { "no_violation" };
|
||||
crate::mail::notify_reporters(&state, &reporters, outcome).await;
|
||||
crate::live::emit(&state.db, crate::live::Event { moderators: true, ..Default::default() }).await;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
/// When a moderator removes a post, its open reports are resolved with it.
|
||||
/// Returns the reporters, to tell them.
|
||||
pub async fn resolve_for_post(
|
||||
tx: &mut sqlx::PgConnection,
|
||||
post_id: i64,
|
||||
moderator: Uuid,
|
||||
) -> Result<Vec<Option<Uuid>>, sqlx::Error> {
|
||||
sqlx::query_scalar(
|
||||
"UPDATE forum.reports SET status = 'resolved', handled_by = $2, handled_at = now() \
|
||||
WHERE post_id = $1 AND status = 'open' RETURNING reporter_id",
|
||||
)
|
||||
.bind(post_id)
|
||||
.bind(moderator)
|
||||
.fetch_all(&mut *tx)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Open reports, for the moderators' badge.
|
||||
pub async fn open_count(db: &PgPool) -> Result<i64, sqlx::Error> {
|
||||
sqlx::query_scalar("SELECT count(*) FROM forum.reports WHERE status = 'open'").fetch_one(db).await
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
//! Search in what the viewer may read: thread titles and posts, with
|
||||
//! Hungarian stems ("szálak" finds "szál") and without accents ("alvas"
|
||||
//! finds "alvás"). One result per thread, with the best matching post's
|
||||
//! words marked; muted members are left out.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Query, State};
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{St, authors, not_muted, rfc3339, visible_topics};
|
||||
use crate::auth::Viewer;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::text;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct SearchQuery {
|
||||
#[serde(default)]
|
||||
q: Option<String>,
|
||||
#[serde(default)]
|
||||
page: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct Hit {
|
||||
id: i64,
|
||||
title: String,
|
||||
topic_slug: String,
|
||||
topic_name: String,
|
||||
author_id: Option<Uuid>,
|
||||
last_post_at: OffsetDateTime,
|
||||
reply_count: i32,
|
||||
post_id: Option<i64>,
|
||||
snippet: Option<String>,
|
||||
}
|
||||
|
||||
const PAGE: i64 = 20;
|
||||
/// Around the matching words in `snippet` (the page marks them).
|
||||
pub const MARK_START: &str = "⟦";
|
||||
pub const MARK_END: &str = "⟧";
|
||||
|
||||
pub async fn search(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Query(q), _): WithRejection<Query<SearchQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let query: String = q.q.unwrap_or_default().trim().chars().take(100).collect();
|
||||
let page = q.page.unwrap_or(1).clamp(1, 50);
|
||||
if query.chars().count() < 2 {
|
||||
return Ok(Json(json!({ "query": query, "results": [], "more": false, "page": page })));
|
||||
}
|
||||
// Word beginnings without accents too: "alvas" finds "alvásban".
|
||||
let prefixes: Vec<String> = query
|
||||
.split(|c: char| !c.is_alphanumeric())
|
||||
.filter(|w| w.chars().count() >= 3)
|
||||
.take(8)
|
||||
.map(|w| format!("{w}:*"))
|
||||
.collect();
|
||||
let rows: Vec<Hit> = sqlx::query_as(&format!(
|
||||
"WITH q AS (SELECT websearch_to_tsquery('hungarian', $2) || to_tsquery('forum.plain', $6) AS q), \
|
||||
hits AS (SELECT p.thread_id, p.id, p.body, ts_rank(p.search, q.q) AS rank FROM forum.posts p, q \
|
||||
WHERE p.search @@ q.q AND p.deleted_at IS NULL AND {posts_ok}) \
|
||||
SELECT th.id, th.title, tp.slug AS topic_slug, tp.name AS topic_name, th.author_id, th.last_post_at, \
|
||||
th.reply_count, best.id AS post_id, \
|
||||
CASE WHEN best.id IS NULL THEN NULL ELSE ts_headline('hungarian', best.body, q.q, $5) END AS snippet \
|
||||
FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id CROSS JOIN q \
|
||||
LEFT JOIN LATERAL (SELECT h.id, h.body, h.rank FROM hits h WHERE h.thread_id = th.id \
|
||||
ORDER BY h.rank DESC, h.id LIMIT 1) best ON true \
|
||||
WHERE th.deleted_at IS NULL AND ({visible}) AND {threads_ok} \
|
||||
AND (th.search @@ q.q OR th.id IN (SELECT thread_id FROM hits)) \
|
||||
ORDER BY (CASE WHEN th.search @@ q.q THEN 2 * ts_rank(th.search, q.q) ELSE 0 END + COALESCE(best.rank, 0)) DESC, \
|
||||
th.last_post_at DESC \
|
||||
LIMIT $3 OFFSET $4",
|
||||
posts_ok = not_muted("p.author_id"),
|
||||
visible = visible_topics(&viewer),
|
||||
threads_ok = not_muted("th.author_id"),
|
||||
))
|
||||
.bind(viewer.user_id())
|
||||
.bind(&query)
|
||||
.bind(PAGE + 1)
|
||||
.bind((page - 1) * PAGE)
|
||||
.bind(format!(
|
||||
"StartSel={MARK_START}, StopSel={MARK_END}, MaxWords=30, MinWords=12, ShortWord=2, MaxFragments=1"
|
||||
))
|
||||
.bind(prefixes.join(" & "))
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let more = rows.len() as i64 > PAGE;
|
||||
let rows = &rows[..rows.len().min(PAGE as usize)];
|
||||
let people = authors(&state.db, rows.iter().filter_map(|r| r.author_id)).await?;
|
||||
let results: Vec<Value> = rows
|
||||
.iter()
|
||||
.map(|r| {
|
||||
json!({
|
||||
"thread": { "id": r.id, "title": r.title, "slug": text::slug(&r.title) },
|
||||
"topic": { "slug": r.topic_slug, "name": r.topic_name },
|
||||
"author": r.author_id.and_then(|a| people.get(&a).cloned()),
|
||||
"last_post_at": rfc3339(r.last_post_at),
|
||||
"reply_count": r.reply_count,
|
||||
"post_id": r.post_id,
|
||||
"snippet": r.snippet,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Ok(Json(json!({ "query": query, "results": results, "more": more, "page": page })))
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct MapThread {
|
||||
id: i64,
|
||||
title: String,
|
||||
last_post_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
/// For the sitemap: the public topics and their threads (newest activity first).
|
||||
pub async fn sitemap(State(state): St) -> ApiResult<Json<Value>> {
|
||||
let topics: Vec<(String, Option<OffsetDateTime>)> = sqlx::query_as(
|
||||
"SELECT tp.slug, (SELECT max(th.last_post_at) FROM forum.threads th \
|
||||
WHERE th.topic_id = tp.id AND th.deleted_at IS NULL) \
|
||||
FROM forum.topics tp WHERE tp.visibility = 'public' ORDER BY tp.position",
|
||||
)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let threads: Vec<MapThread> = sqlx::query_as(
|
||||
"SELECT th.id, th.title, th.last_post_at FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
|
||||
WHERE tp.visibility = 'public' AND th.deleted_at IS NULL ORDER BY th.last_post_at DESC LIMIT 5000",
|
||||
)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
Ok(Json(json!({
|
||||
"topics": topics.iter().map(|(slug, at)| json!({ "slug": slug, "updated": at.map(rfc3339) })).collect::<Vec<_>>(),
|
||||
"threads": threads.iter().map(|t| json!({
|
||||
"id": t.id, "slug": text::slug(&t.title), "updated": rfc3339(t.last_post_at),
|
||||
})).collect::<Vec<_>>(),
|
||||
})))
|
||||
}
|
||||
@@ -0,0 +1,655 @@
|
||||
//! Threads: reading one, starting one, replying, read marks, following, and
|
||||
//! the moderators' lock, pin, removal and the admin's restore.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
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::home::viewer_json;
|
||||
use super::moderation::{self, Action};
|
||||
use super::{Body, IdPath, St, authors, has_purchase, may_read, rfc3339};
|
||||
use crate::AppState;
|
||||
use crate::auth::{Member, Viewer};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::rank::{self, COLLAPSE_SCORE};
|
||||
use crate::text;
|
||||
|
||||
/// The positive reactions; each is +1, the ⌄ (`down`) is -1.
|
||||
pub const REACTIONS: [&str; 4] = ["with_you", "thanks", "me_too", "insight"];
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct ThreadRow {
|
||||
pub id: i64,
|
||||
pub topic_id: i16,
|
||||
pub topic_slug: String,
|
||||
pub topic_name: String,
|
||||
pub visibility: String,
|
||||
pub listening: bool,
|
||||
pub author_id: Option<Uuid>,
|
||||
pub title: String,
|
||||
pub intent: Option<String>,
|
||||
pub created_at: OffsetDateTime,
|
||||
pub locked: bool,
|
||||
pub pinned: bool,
|
||||
pub deleted_at: Option<OffsetDateTime>,
|
||||
pub delete_reason: Option<String>,
|
||||
pub system: bool,
|
||||
/// Its topic is archived: readable, but takes nothing new.
|
||||
pub archived: bool,
|
||||
}
|
||||
|
||||
const THREAD_SELECT: &str = "SELECT th.id, th.topic_id, tp.slug AS topic_slug, tp.name AS topic_name, tp.visibility, \
|
||||
tp.listening, th.author_id, th.title, th.intent, th.created_at, th.locked, th.pinned, th.deleted_at, \
|
||||
th.delete_reason, th.system, tp.archived_at IS NOT NULL AS archived \
|
||||
FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id";
|
||||
|
||||
/// A thread the viewer may read (deleted ones too): 404 when it does not
|
||||
/// exist or sits in a hidden topic, 401 in a members-only topic for a visitor.
|
||||
pub async fn readable_thread(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult<ThreadRow> {
|
||||
let thread: ThreadRow = sqlx::query_as(&format!("{THREAD_SELECT} WHERE th.id = $1"))
|
||||
.bind(id)
|
||||
.fetch_optional(db)
|
||||
.await?
|
||||
.ok_or(ApiError::NotFound("thread"))?;
|
||||
if !may_read(viewer, &thread.visibility, thread.topic_id) {
|
||||
return Err(if thread.visibility == "members" { ApiError::Unauthorized } else { ApiError::NotFound("thread") });
|
||||
}
|
||||
Ok(thread)
|
||||
}
|
||||
|
||||
/// A thread that can take new posts and reactions: not removed, not in an
|
||||
/// archived topic, and not locked (moderators may still write in a locked one).
|
||||
pub async fn open_thread(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult<ThreadRow> {
|
||||
let thread = readable_thread(db, viewer, id).await?;
|
||||
if thread.deleted_at.is_some() {
|
||||
return Err(ApiError::NotFound("thread"));
|
||||
}
|
||||
if thread.archived {
|
||||
return Err(ApiError::Forbidden("Ez a téma archivált: olvasható, de új hozzászólás nem írható.".into()));
|
||||
}
|
||||
if thread.locked && !viewer.is_moderator() {
|
||||
return Err(ApiError::Forbidden("Ez a szál le van zárva.".into()));
|
||||
}
|
||||
Ok(thread)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct PostRow {
|
||||
pub id: i64,
|
||||
pub thread_id: i64,
|
||||
pub parent_id: Option<i64>,
|
||||
pub is_opening: bool,
|
||||
pub author_id: Option<Uuid>,
|
||||
pub body: String,
|
||||
pub created_at: OffsetDateTime,
|
||||
pub edited_at: Option<OffsetDateTime>,
|
||||
pub helped_at: Option<OffsetDateTime>,
|
||||
pub deleted_at: Option<OffsetDateTime>,
|
||||
pub deleted_by: Option<Uuid>,
|
||||
pub delete_reason: Option<String>,
|
||||
/// Written by the site itself (the daily sky thread).
|
||||
pub system: bool,
|
||||
/// The post this one answered (which may sit on the same level).
|
||||
pub reply_to_id: Option<i64>,
|
||||
/// A chart, forecast or synastry shared with the question.
|
||||
pub share_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
pub const POST_COLUMNS: &str = "id, thread_id, parent_id, is_opening, author_id, body, created_at, edited_at, helped_at, deleted_at, deleted_by, \
|
||||
delete_reason, system, reply_to_id, share_id";
|
||||
|
||||
/// Posts as the thread page shows them: authors, reactions, the viewer's own
|
||||
/// reaction. A removed post keeps its place with the reason; only
|
||||
/// moderators still see its text.
|
||||
pub async fn posts_json(db: &PgPool, viewer: &Viewer, posts: &[PostRow]) -> ApiResult<Vec<Value>> {
|
||||
let ids: Vec<i64> = posts.iter().map(|p| p.id).collect();
|
||||
let people = authors(db, posts.iter().filter_map(|p| p.author_id)).await?;
|
||||
let shares: Vec<Uuid> = posts.iter().filter(|p| p.deleted_at.is_none()).filter_map(|p| p.share_id).collect();
|
||||
let cards = super::attachments::cards(db, viewer, &shares).await?;
|
||||
let texts: Vec<(i64, &str)> =
|
||||
posts.iter().filter(|p| p.deleted_at.is_none()).map(|p| (p.id, p.body.as_str())).collect();
|
||||
let previews = crate::links::previews(db, &texts).await?;
|
||||
let counts: Vec<(i64, String, i64)> =
|
||||
sqlx::query_as("SELECT post_id, kind, count(*) FROM forum.reactions WHERE post_id = ANY($1) GROUP BY 1, 2")
|
||||
.bind(&ids)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
let mut by_post: HashMap<i64, HashMap<String, i64>> = HashMap::new();
|
||||
for (post, kind, n) in counts {
|
||||
by_post.entry(post).or_default().insert(kind, n);
|
||||
}
|
||||
let mine: HashMap<i64, String> = match viewer.user_id() {
|
||||
Some(me) => {
|
||||
sqlx::query_as("SELECT post_id, kind FROM forum.reactions WHERE post_id = ANY($1) AND user_id = $2")
|
||||
.bind(&ids)
|
||||
.bind(me)
|
||||
.fetch_all(db)
|
||||
.await?
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
None => HashMap::new(),
|
||||
};
|
||||
let named: Vec<(i64, String)> = sqlx::query_as(
|
||||
"SELECT mn.post_id, m.nickname FROM forum.mentions mn JOIN forum.members m ON m.user_id = mn.user_id \
|
||||
WHERE mn.post_id = ANY($1)",
|
||||
)
|
||||
.bind(&ids)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
// Whom each reply answers: the author of the post it replied to.
|
||||
let answered: Vec<i64> = posts.iter().filter_map(|p| p.reply_to_id).collect();
|
||||
let answered: HashMap<i64, Option<String>> = sqlx::query_as::<_, (i64, Option<String>)>(
|
||||
"SELECT p.id, m.nickname FROM forum.posts p LEFT JOIN forum.members m ON m.user_id = p.author_id \
|
||||
WHERE p.id = ANY($1)",
|
||||
)
|
||||
.bind(&answered)
|
||||
.fetch_all(db)
|
||||
.await?
|
||||
.into_iter()
|
||||
.collect();
|
||||
let moderator = viewer.is_moderator();
|
||||
Ok(posts
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let reply_to =
|
||||
p.reply_to_id.map(|id| json!({ "id": id, "nickname": answered.get(&id).cloned().flatten() }));
|
||||
let mentions: Vec<&String> = named.iter().filter(|(id, _)| *id == p.id).map(|(_, n)| n).collect();
|
||||
let counts = by_post.remove(&p.id).unwrap_or_default();
|
||||
let positive: i64 = REACTIONS.iter().map(|k| counts.get(*k).copied().unwrap_or(0)).sum();
|
||||
let down = counts.get("down").copied().unwrap_or(0);
|
||||
let score = positive - down;
|
||||
let deleted = p.deleted_at.map(|_| {
|
||||
json!({
|
||||
"by_moderator": p.deleted_by.is_some() && p.deleted_by != p.author_id,
|
||||
"reason": p.delete_reason,
|
||||
})
|
||||
});
|
||||
let mut post = json!({
|
||||
"id": p.id,
|
||||
"parent_id": p.parent_id,
|
||||
"is_opening": p.is_opening,
|
||||
"author": p.author_id.and_then(|id| people.get(&id).cloned()),
|
||||
"own": p.author_id.is_some() && p.author_id == viewer.user_id(),
|
||||
"body": if p.deleted_at.is_none() || moderator { Some(&p.body) } else { None },
|
||||
"deleted": deleted,
|
||||
"created_at": rfc3339(p.created_at),
|
||||
"edited_at": p.edited_at.map(rfc3339),
|
||||
"helped": p.helped_at.is_some(),
|
||||
"reactions": REACTIONS.iter().map(|k| (k.to_string(), json!(counts.get(*k).copied().unwrap_or(0))))
|
||||
.collect::<serde_json::Map<_, _>>(),
|
||||
"score": score,
|
||||
"collapsed": score <= COLLAPSE_SCORE,
|
||||
"mine": mine.get(&p.id),
|
||||
"mentions": mentions,
|
||||
"system": p.system,
|
||||
"reply_to": reply_to,
|
||||
// The viewer muted the author: the page folds it up.
|
||||
"muted": p.author_id.is_some_and(|a| viewer.mutes.contains(&a)),
|
||||
"share": p.share_id.and_then(|id| cards.get(&id).cloned()),
|
||||
// Previews of the links a provider knows (YouTube).
|
||||
"links": previews.get(&p.id),
|
||||
});
|
||||
if moderator {
|
||||
post["down"] = json!(down);
|
||||
}
|
||||
post
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// A thread with all its posts, oldest first.
|
||||
pub async fn show(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<Json<Value>> {
|
||||
let thread = readable_thread(&state.db, &viewer, id).await?;
|
||||
let people = authors(&state.db, thread.author_id).await?;
|
||||
let moderator = viewer.is_moderator();
|
||||
let mut out = json!({
|
||||
"viewer": viewer_json(&viewer),
|
||||
"thread": thread_json(&thread, thread.author_id.and_then(|a| people.get(&a).cloned())),
|
||||
});
|
||||
if thread.deleted_at.is_some() && !moderator {
|
||||
out["posts"] = json!([]);
|
||||
return Ok(Json(out));
|
||||
}
|
||||
let posts: Vec<PostRow> =
|
||||
sqlx::query_as(&format!("SELECT {POST_COLUMNS} FROM forum.posts WHERE thread_id = $1 ORDER BY id"))
|
||||
.bind(id)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
out["posts"] = json!(posts_json(&state.db, &viewer, &posts).await?);
|
||||
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let (following, last_read) = match viewer.user_id() {
|
||||
Some(me) => {
|
||||
let following: bool =
|
||||
sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM forum.follows WHERE user_id = $1 AND thread_id = $2)")
|
||||
.bind(me)
|
||||
.bind(id)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
let last_read: Option<i64> =
|
||||
sqlx::query_scalar("SELECT last_post_id FROM forum.reads WHERE user_id = $1 AND thread_id = $2")
|
||||
.bind(me)
|
||||
.bind(id)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
(following, last_read)
|
||||
}
|
||||
None => (false, None),
|
||||
};
|
||||
let writer = viewer.member.as_ref().filter(|m| !m.banned(now));
|
||||
let open = thread.deleted_at.is_none() && !thread.archived && (!thread.locked || moderator);
|
||||
out["access"] = json!({
|
||||
"can_reply": open && (writer.is_some() || !viewer.logged_in() || viewer.member.is_none()),
|
||||
"can_downvote": !thread.listening && writer.is_some_and(|m| m.rank(now).may_downvote()),
|
||||
"is_thread_author": thread.author_id.is_some() && thread.author_id == viewer.user_id(),
|
||||
"following": following,
|
||||
"last_read_post_id": last_read,
|
||||
});
|
||||
Ok(Json(out))
|
||||
}
|
||||
|
||||
fn thread_json(thread: &ThreadRow, author: Option<Value>) -> Value {
|
||||
json!({
|
||||
"id": thread.id,
|
||||
"slug": text::slug(&thread.title),
|
||||
"title": thread.title,
|
||||
"intent": thread.intent,
|
||||
"topic": {
|
||||
"slug": thread.topic_slug, "name": thread.topic_name,
|
||||
"visibility": thread.visibility, "listening": thread.listening, "archived": thread.archived,
|
||||
},
|
||||
"author": author,
|
||||
"created_at": rfc3339(thread.created_at),
|
||||
"locked": thread.locked,
|
||||
"pinned": thread.pinned,
|
||||
"deleted": thread.deleted_at.map(|_| json!({ "reason": thread.delete_reason })),
|
||||
"system": thread.system,
|
||||
})
|
||||
}
|
||||
|
||||
/// Too fast, or past a newcomer's daily limit (lifted by a purchase and for moderators).
|
||||
async fn check_limits(state: &AppState, viewer: &Viewer, member: &Member, new_thread: bool) -> ApiResult<()> {
|
||||
let db = &state.db;
|
||||
let recent: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS (SELECT 1 FROM forum.posts \
|
||||
WHERE author_id = $1 AND created_at > now() - make_interval(secs => $2))",
|
||||
)
|
||||
.bind(member.user_id)
|
||||
.bind(f64::from(state.flood_secs))
|
||||
.fetch_one(db)
|
||||
.await?;
|
||||
if recent {
|
||||
return Err(ApiError::Limited("Várj pár másodpercet a következő hozzászólással.".into()));
|
||||
}
|
||||
if viewer.is_moderator() || !member.rank(OffsetDateTime::now_utc()).is_newcomer() {
|
||||
return Ok(());
|
||||
}
|
||||
let (threads, posts): (i64, i64) = sqlx::query_as(
|
||||
"SELECT count(*) FILTER (WHERE is_opening), count(*) FROM forum.posts \
|
||||
WHERE author_id = $1 AND created_at > now() - interval '24 hours'",
|
||||
)
|
||||
.bind(member.user_id)
|
||||
.fetch_one(db)
|
||||
.await?;
|
||||
let over =
|
||||
if new_thread { threads >= rank::NEWCOMER_THREADS_PER_DAY } else { posts >= rank::NEWCOMER_POSTS_PER_DAY };
|
||||
if over && !has_purchase(db, member.user_id).await? {
|
||||
return Err(ApiError::Limited(if new_thread {
|
||||
format!(
|
||||
"Új tagként naponta legfeljebb {} szálat nyithatsz. Holnap újra lehet.",
|
||||
rank::NEWCOMER_THREADS_PER_DAY
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"Új tagként naponta legfeljebb {} hozzászólást írhatsz. Holnap újra lehet.",
|
||||
rank::NEWCOMER_POSTS_PER_DAY
|
||||
)
|
||||
}));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct CreateThread {
|
||||
topic: String,
|
||||
title: String,
|
||||
body: String,
|
||||
#[serde(default)]
|
||||
intent: Option<String>,
|
||||
/// A share made for the forum on the main site (`/s/<slug>`).
|
||||
#[serde(default)]
|
||||
share: Option<String>,
|
||||
}
|
||||
|
||||
/// Starts a thread with its opening post; the author follows it.
|
||||
pub async fn create(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Json(req), _): Body<CreateThread>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let member = viewer.require_writer()?;
|
||||
let topic: Option<(i16, String, bool, bool)> =
|
||||
sqlx::query_as("SELECT id, visibility, listening, archived_at IS NOT NULL FROM forum.topics WHERE slug = $1")
|
||||
.bind(&req.topic)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let (topic_id, visibility, listening, archived) = topic.ok_or_else(|| ApiError::bad("Ismeretlen téma."))?;
|
||||
if archived {
|
||||
return Err(ApiError::bad("Ez a téma archivált, új szál nem nyitható benne."));
|
||||
}
|
||||
if !may_read(&viewer, &visibility, topic_id) {
|
||||
return Err(ApiError::bad("Ismeretlen téma."));
|
||||
}
|
||||
let title = text::title(&req.title)?;
|
||||
let body = text::body(&req.body)?;
|
||||
let share = match req.share.as_deref().filter(|s| !s.trim().is_empty()) {
|
||||
Some(slug) => Some(super::attachments::attachable(&state.db, member, slug).await?),
|
||||
None => None,
|
||||
};
|
||||
let intent = match req.intent.as_deref() {
|
||||
Some(i @ ("listen" | "advice")) => Some(i.to_string()),
|
||||
None | Some("") => listening.then(|| "listen".to_string()),
|
||||
Some(_) => return Err(ApiError::bad("Ismeretlen szándék.")),
|
||||
};
|
||||
check_limits(&state, &viewer, member, true).await?;
|
||||
|
||||
let mut tx = state.db.begin().await?;
|
||||
let thread_id: i64 = sqlx::query_scalar(
|
||||
"INSERT INTO forum.threads (topic_id, author_id, title, intent) VALUES ($1, $2, $3, $4) RETURNING id",
|
||||
)
|
||||
.bind(topic_id)
|
||||
.bind(member.user_id)
|
||||
.bind(&title)
|
||||
.bind(&intent)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
let post_id: i64 = sqlx::query_scalar(
|
||||
"INSERT INTO forum.posts (thread_id, author_id, is_opening, body, share_id) \
|
||||
VALUES ($1, $2, true, $3, $4) RETURNING id",
|
||||
)
|
||||
.bind(thread_id)
|
||||
.bind(member.user_id)
|
||||
.bind(&body)
|
||||
.bind(share)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
after_post(&mut tx, member.user_id, thread_id, post_id).await?;
|
||||
tx.commit().await?;
|
||||
tracing::info!(thread = thread_id, topic = %req.topic, "thread started");
|
||||
super::mentions::after_post(&state, thread_id, post_id, member.user_id, &body).await;
|
||||
crate::links::process(&state, &body).await;
|
||||
Ok((StatusCode::CREATED, Json(json!({ "id": thread_id, "slug": text::slug(&title) }))))
|
||||
}
|
||||
|
||||
/// After a post: the author's count, following the thread, and the read mark
|
||||
/// up to their own post.
|
||||
async fn after_post(
|
||||
tx: &mut sqlx::PgConnection,
|
||||
author: Uuid,
|
||||
thread_id: i64,
|
||||
post_id: i64,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
sqlx::query("UPDATE forum.members SET post_count = post_count + 1 WHERE user_id = $1")
|
||||
.bind(author)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("INSERT INTO forum.follows (user_id, thread_id) VALUES ($1, $2) ON CONFLICT DO NOTHING")
|
||||
.bind(author)
|
||||
.bind(thread_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
upsert_read(&mut *tx, author, thread_id, post_id).await
|
||||
}
|
||||
|
||||
async fn upsert_read(
|
||||
db: impl sqlx::PgExecutor<'_>,
|
||||
user: Uuid,
|
||||
thread_id: i64,
|
||||
post_id: i64,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.reads (user_id, thread_id, last_post_id) VALUES ($1, $2, $3) \
|
||||
ON CONFLICT (user_id, thread_id) DO UPDATE \
|
||||
SET last_post_id = GREATEST(forum.reads.last_post_id, EXCLUDED.last_post_id), read_at = now()",
|
||||
)
|
||||
.bind(user)
|
||||
.bind(thread_id)
|
||||
.bind(post_id)
|
||||
.execute(db)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Reply {
|
||||
body: String,
|
||||
/// The post answered; a reply to a reply goes under the same first-level
|
||||
/// post (two levels at most), a reply to the opening post is first-level.
|
||||
#[serde(default)]
|
||||
parent_id: Option<i64>,
|
||||
}
|
||||
|
||||
pub async fn reply(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<Reply>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let member = viewer.require_writer()?;
|
||||
open_thread(&state.db, &viewer, id).await?;
|
||||
let body = text::body(&req.body)?;
|
||||
// The post answered (shown as "↪ Holdfény"), and where the reply goes:
|
||||
// under the first-level post (two levels at most).
|
||||
let reply_to = req.parent_id;
|
||||
let parent = match req.parent_id {
|
||||
None => None,
|
||||
Some(parent_id) => {
|
||||
let parent: Option<(Option<i64>, bool, bool)> = sqlx::query_as(
|
||||
"SELECT parent_id, is_opening, deleted_at IS NOT NULL FROM forum.posts WHERE id = $1 AND thread_id = $2",
|
||||
)
|
||||
.bind(parent_id)
|
||||
.bind(id)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let (grandparent, is_opening, deleted) = parent.ok_or_else(|| ApiError::bad("Ismeretlen hozzászólás."))?;
|
||||
if deleted {
|
||||
return Err(ApiError::bad("Törölt hozzászólásra nem lehet válaszolni."));
|
||||
}
|
||||
if is_opening { None } else { Some(grandparent.unwrap_or(parent_id)) }
|
||||
}
|
||||
};
|
||||
let reply_to = reply_to.filter(|_| parent.is_some());
|
||||
check_limits(&state, &viewer, member, false).await?;
|
||||
|
||||
let mut tx = state.db.begin().await?;
|
||||
let post: PostRow = sqlx::query_as(&format!(
|
||||
"INSERT INTO forum.posts (thread_id, author_id, parent_id, reply_to_id, body) VALUES ($1, $2, $3, $4, $5) \
|
||||
RETURNING {POST_COLUMNS}"
|
||||
))
|
||||
.bind(id)
|
||||
.bind(member.user_id)
|
||||
.bind(parent)
|
||||
.bind(reply_to)
|
||||
.bind(&body)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("UPDATE forum.threads SET last_post_at = now(), reply_count = reply_count + 1 WHERE id = $1")
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
after_post(&mut tx, member.user_id, id, post.id).await?;
|
||||
tx.commit().await?;
|
||||
// The one answered hears of it (on the second level, not the branch's first post).
|
||||
crate::mail::after_reply(&state, id, post.id, member.user_id, post.reply_to_id.or(post.parent_id), &body).await;
|
||||
super::mentions::after_post(&state, id, post.id, member.user_id, &body).await;
|
||||
crate::links::process(&state, &body).await;
|
||||
let followers = crate::live::followers(&state.db, id, member.user_id).await;
|
||||
crate::live::emit(&state.db, crate::live::Event { thread: Some(id), ..Default::default() }.for_users(followers))
|
||||
.await;
|
||||
let post = posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0);
|
||||
Ok((StatusCode::CREATED, Json(post)))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ReadMark {
|
||||
post_id: i64,
|
||||
}
|
||||
|
||||
/// Read up to that post (never backwards).
|
||||
pub async fn mark_read(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<ReadMark>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let member = viewer.require_member()?;
|
||||
readable_thread(&state.db, &viewer, id).await?;
|
||||
let last: Option<i64> = sqlx::query_scalar("SELECT max(id) FROM forum.posts WHERE thread_id = $1")
|
||||
.bind(id)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
let Some(last) = last else { return Ok(StatusCode::NO_CONTENT) };
|
||||
upsert_read(&state.db, member.user_id, id, req.post_id.min(last)).await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
pub async fn follow(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
|
||||
let member = viewer.require_member()?;
|
||||
readable_thread(&state.db, &viewer, id).await?;
|
||||
sqlx::query("INSERT INTO forum.follows (user_id, thread_id) VALUES ($1, $2) ON CONFLICT DO NOTHING")
|
||||
.bind(member.user_id)
|
||||
.bind(id)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
pub async fn unfollow(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
|
||||
let member = viewer.require_member()?;
|
||||
sqlx::query("DELETE FROM forum.follows WHERE user_id = $1 AND thread_id = $2")
|
||||
.bind(member.user_id)
|
||||
.bind(id)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ThreadChange {
|
||||
#[serde(default)]
|
||||
locked: Option<bool>,
|
||||
#[serde(default)]
|
||||
pinned: Option<bool>,
|
||||
}
|
||||
|
||||
/// Moderators lock (no more replies) or pin (first in its topic) a thread.
|
||||
pub async fn update(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<ThreadChange>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let moderator = viewer.require_moderator()?;
|
||||
let thread = readable_thread(&state.db, &viewer, id).await?;
|
||||
let mut tx = state.db.begin().await?;
|
||||
if let Some(locked) = req.locked.filter(|l| *l != thread.locked) {
|
||||
sqlx::query("UPDATE forum.threads SET locked = $2 WHERE id = $1")
|
||||
.bind(id)
|
||||
.bind(locked)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
let action = if locked { Action::Lock } else { Action::Unlock };
|
||||
moderation::record(&mut *tx, moderator.id, action, thread.author_id, Some(id), None, None, None).await?;
|
||||
}
|
||||
if let Some(pinned) = req.pinned.filter(|p| *p != thread.pinned) {
|
||||
sqlx::query("UPDATE forum.threads SET pinned = $2 WHERE id = $1")
|
||||
.bind(id)
|
||||
.bind(pinned)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
let action = if pinned { Action::Pin } else { Action::Unpin };
|
||||
moderation::record(&mut *tx, moderator.id, action, thread.author_id, Some(id), None, None, None).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Reason {
|
||||
#[serde(default)]
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
/// A moderator removes a whole thread; its place keeps the reason.
|
||||
pub async fn remove(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<Reason>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let moderator = viewer.require_moderator()?;
|
||||
let thread = readable_thread(&state.db, &viewer, id).await?;
|
||||
if thread.deleted_at.is_some() {
|
||||
return Ok(StatusCode::NO_CONTENT);
|
||||
}
|
||||
let reason = text::reason(req.reason.as_deref().unwrap_or(""))?;
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE forum.threads SET deleted_at = now(), deleted_by = $2, delete_reason = $3 WHERE id = $1")
|
||||
.bind(id)
|
||||
.bind(moderator.id)
|
||||
.bind(&reason)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
moderation::record(
|
||||
&mut *tx,
|
||||
moderator.id,
|
||||
Action::DeleteThread,
|
||||
thread.author_id,
|
||||
Some(id),
|
||||
None,
|
||||
Some(&reason),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
tracing::info!(thread = id, moderator = %moderator.id, "thread removed");
|
||||
if let Some(author) = thread.author_id {
|
||||
let payload = json!({
|
||||
"url": crate::mail::rules_url(&state),
|
||||
"action": "thread_removed",
|
||||
"reason": reason,
|
||||
"thread_title": thread.title,
|
||||
});
|
||||
crate::mail::notify_user(&state, author, "forum_moderation", payload).await;
|
||||
}
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
/// The admin undoes a thread's removal.
|
||||
pub async fn restore(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
|
||||
let admin = viewer.require_user()?;
|
||||
if !viewer.is_admin() {
|
||||
return Err(ApiError::Forbidden("Visszaállítani csak az admin tud.".into()));
|
||||
}
|
||||
let thread = readable_thread(&state.db, &viewer, id).await?;
|
||||
if thread.deleted_at.is_none() {
|
||||
return Ok(StatusCode::NO_CONTENT);
|
||||
}
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE forum.threads SET deleted_at = NULL, deleted_by = NULL, delete_reason = NULL WHERE id = $1")
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
moderation::record(&mut *tx, admin.id, Action::RestoreThread, thread.author_id, Some(id), None, None, None).await?;
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
//! Topics: the admin creates and edits them; a restricted topic is read and
|
||||
//! written only by its approved members (and moderators): members ask to
|
||||
//! join, moderators approve or turn them down.
|
||||
|
||||
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 uuid::Uuid;
|
||||
|
||||
use super::moderation::{self, Action};
|
||||
use super::{Body, St, authors, rfc3339};
|
||||
use crate::auth::Viewer;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::text;
|
||||
|
||||
const NAME_MAX: usize = 60;
|
||||
const DESCRIPTION_MAX: usize = 160;
|
||||
const NOTE_MAX: usize = 300;
|
||||
|
||||
fn require_admin(viewer: &Viewer) -> ApiResult<Uuid> {
|
||||
let user = viewer.require_user()?;
|
||||
if viewer.is_admin() { Ok(user.id) } else { Err(ApiError::Forbidden("Témát csak az admin kezelhet.".into())) }
|
||||
}
|
||||
|
||||
fn visibility(raw: &str) -> ApiResult<String> {
|
||||
match raw {
|
||||
"public" | "members" | "restricted" => Ok(raw.to_string()),
|
||||
_ => Err(ApiError::bad("Ismeretlen láthatóság.")),
|
||||
}
|
||||
}
|
||||
|
||||
fn one_line(raw: &str, max: usize, what: &str) -> ApiResult<String> {
|
||||
let text: String = raw.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
let len = text.chars().count();
|
||||
if len < 2 || len > max {
|
||||
return Err(ApiError::bad(format!("A {what} 2–{max} karakter legyen.")));
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct NewTopic {
|
||||
name: String,
|
||||
description: String,
|
||||
#[serde(default = "public")]
|
||||
visibility: String,
|
||||
#[serde(default)]
|
||||
listening: bool,
|
||||
}
|
||||
|
||||
fn public() -> String {
|
||||
"public".into()
|
||||
}
|
||||
|
||||
/// The admin opens a topic (last in the list); its address comes from the name.
|
||||
pub async fn create(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Json(req), _): Body<NewTopic>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let admin = require_admin(&viewer)?;
|
||||
let name = one_line(&req.name, NAME_MAX, "név")?;
|
||||
let description = one_line(&req.description, DESCRIPTION_MAX, "leírás")?;
|
||||
let visibility = visibility(&req.visibility)?;
|
||||
let slug = text::slug(&name);
|
||||
if slug.is_empty() {
|
||||
return Err(ApiError::bad("A névből nem lesz cím: írj bele betűket."));
|
||||
}
|
||||
let mut tx = state.db.begin().await?;
|
||||
let created: Result<i16, sqlx::Error> = sqlx::query_scalar(
|
||||
"INSERT INTO forum.topics (id, slug, name, description, visibility, listening, position) \
|
||||
SELECT COALESCE(max(id), 0) + 1, $1, $2, $3, $4, $5, COALESCE(max(position), 0) + 1 FROM forum.topics \
|
||||
RETURNING id",
|
||||
)
|
||||
.bind(&slug)
|
||||
.bind(&name)
|
||||
.bind(&description)
|
||||
.bind(&visibility)
|
||||
.bind(req.listening)
|
||||
.fetch_one(&mut *tx)
|
||||
.await;
|
||||
let id = match created {
|
||||
Ok(id) => id,
|
||||
Err(sqlx::Error::Database(e)) if e.is_unique_violation() => {
|
||||
return Err(ApiError::conflict("topic_exists", "Ilyen nevű téma már van."));
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
moderation::record(&mut *tx, admin, Action::Topic, None, None, None, Some(&format!("új téma: {name}")), None)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok((StatusCode::CREATED, Json(json!({ "id": id, "slug": slug }))))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct TopicChange {
|
||||
#[serde(default)]
|
||||
name: Option<String>,
|
||||
#[serde(default)]
|
||||
description: Option<String>,
|
||||
#[serde(default)]
|
||||
visibility: Option<String>,
|
||||
#[serde(default)]
|
||||
listening: Option<bool>,
|
||||
#[serde(default)]
|
||||
position: Option<i16>,
|
||||
/// Archive (true) or bring back (false).
|
||||
#[serde(default)]
|
||||
archived: Option<bool>,
|
||||
}
|
||||
|
||||
/// The admin renames, describes, moves or changes the visibility of a topic
|
||||
/// (its address stays, so links keep working).
|
||||
pub async fn update(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(slug), _): WithRejection<Path<String>, ApiError>,
|
||||
WithRejection(Json(req), _): Body<TopicChange>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let admin = require_admin(&viewer)?;
|
||||
let name = req.name.as_deref().map(|n| one_line(n, NAME_MAX, "név")).transpose()?;
|
||||
let description = req.description.as_deref().map(|d| one_line(d, DESCRIPTION_MAX, "leírás")).transpose()?;
|
||||
let visibility = req.visibility.as_deref().map(visibility).transpose()?;
|
||||
let mut tx = state.db.begin().await?;
|
||||
let changed = sqlx::query(
|
||||
"UPDATE forum.topics SET name = COALESCE($2, name), description = COALESCE($3, description), \
|
||||
visibility = COALESCE($4, visibility), listening = COALESCE($5, listening), \
|
||||
position = COALESCE($6, position), \
|
||||
archived_at = CASE WHEN $7::boolean IS NULL THEN archived_at \
|
||||
WHEN $7 THEN COALESCE(archived_at, now()) ELSE NULL END \
|
||||
WHERE slug = $1",
|
||||
)
|
||||
.bind(&slug)
|
||||
.bind(&name)
|
||||
.bind(&description)
|
||||
.bind(&visibility)
|
||||
.bind(req.listening)
|
||||
.bind(req.position)
|
||||
.bind(req.archived)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
if changed.rows_affected() == 0 {
|
||||
return Err(ApiError::NotFound("topic"));
|
||||
}
|
||||
moderation::record(
|
||||
&mut *tx,
|
||||
admin,
|
||||
Action::Topic,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Some(&match req.archived {
|
||||
Some(true) => format!("téma archiválva: {slug}"),
|
||||
Some(false) => format!("téma visszaállítva: {slug}"),
|
||||
None => format!("téma módosítva: {slug}"),
|
||||
}),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct JoinRequest {
|
||||
#[serde(default)]
|
||||
note: Option<String>,
|
||||
}
|
||||
|
||||
/// A member asks to join a restricted topic (with a few words, if they like).
|
||||
pub async fn join(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(slug), _): WithRejection<Path<String>, ApiError>,
|
||||
WithRejection(Json(req), _): Body<JoinRequest>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let member = viewer.require_writer()?;
|
||||
let topic: Option<(i16, String)> = sqlx::query_as("SELECT id, visibility FROM forum.topics WHERE slug = $1")
|
||||
.bind(&slug)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let (id, visibility) = topic.ok_or(ApiError::NotFound("topic"))?;
|
||||
if visibility != "restricted" {
|
||||
return Err(ApiError::bad("Ebbe a témába nem kell jelentkezni."));
|
||||
}
|
||||
let note: String = req.note.as_deref().unwrap_or("").split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
if note.chars().count() > NOTE_MAX {
|
||||
return Err(ApiError::bad(format!("Legfeljebb {NOTE_MAX} karakter.")));
|
||||
}
|
||||
sqlx::query("INSERT INTO forum.topic_members (topic_id, user_id, note) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING")
|
||||
.bind(id)
|
||||
.bind(member.user_id)
|
||||
.bind(¬e)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
crate::live::emit(&state.db, crate::live::Event { moderators: true, ..Default::default() }).await;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
/// Leaving a restricted topic, or taking back the request.
|
||||
pub async fn leave(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(slug), _): WithRejection<Path<String>, ApiError>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let member = viewer.require_member()?;
|
||||
sqlx::query(
|
||||
"DELETE FROM forum.topic_members WHERE user_id = $1 AND topic_id = (SELECT id FROM forum.topics WHERE slug = $2)",
|
||||
)
|
||||
.bind(member.user_id)
|
||||
.bind(&slug)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct RequestRow {
|
||||
topic_slug: String,
|
||||
topic_name: String,
|
||||
user_id: Uuid,
|
||||
status: String,
|
||||
note: String,
|
||||
requested_at: time::OffsetDateTime,
|
||||
}
|
||||
|
||||
/// For moderators: who waits to join a restricted topic, and who is in.
|
||||
pub async fn requests(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||
viewer.require_moderator()?;
|
||||
let rows: Vec<RequestRow> = sqlx::query_as(
|
||||
"SELECT tp.slug AS topic_slug, tp.name AS topic_name, tm.user_id, tm.status, tm.note, tm.requested_at \
|
||||
FROM forum.topic_members tm JOIN forum.topics tp ON tp.id = tm.topic_id \
|
||||
ORDER BY tm.status <> 'pending', tp.position, tm.requested_at",
|
||||
)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let people = authors(&state.db, rows.iter().map(|r| r.user_id)).await?;
|
||||
Ok(Json(json!({
|
||||
"requests": rows.iter().map(|r| json!({
|
||||
"topic": { "slug": r.topic_slug, "name": r.topic_name },
|
||||
"member": people.get(&r.user_id),
|
||||
"status": r.status,
|
||||
"note": r.note,
|
||||
"requested_at": rfc3339(r.requested_at),
|
||||
})).collect::<Vec<_>>(),
|
||||
})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Decision {
|
||||
topic: String,
|
||||
nickname: String,
|
||||
/// `approve`, `reject` (a request) or `remove` (a member).
|
||||
action: String,
|
||||
}
|
||||
|
||||
/// A moderator approves or turns down a request, or removes a member.
|
||||
pub async fn decide(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Json(req), _): Body<Decision>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let moderator = viewer.require_moderator()?;
|
||||
let found: Option<(i16, Uuid)> = sqlx::query_as(
|
||||
"SELECT tp.id, m.user_id FROM forum.topics tp, forum.members m WHERE tp.slug = $1 AND m.nickname_key = $2",
|
||||
)
|
||||
.bind(&req.topic)
|
||||
.bind(text::nickname_key(&req.nickname))
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let (topic, user) = found.ok_or(ApiError::NotFound("request"))?;
|
||||
let mut tx = state.db.begin().await?;
|
||||
let (done, action) = match req.action.as_str() {
|
||||
"approve" => (
|
||||
sqlx::query(
|
||||
"UPDATE forum.topic_members SET status = 'approved', decided_at = now(), decided_by = $3 \
|
||||
WHERE topic_id = $1 AND user_id = $2",
|
||||
)
|
||||
.bind(topic)
|
||||
.bind(user)
|
||||
.bind(moderator.id)
|
||||
.execute(&mut *tx)
|
||||
.await?,
|
||||
Action::ApproveMember,
|
||||
),
|
||||
"reject" | "remove" => (
|
||||
sqlx::query("DELETE FROM forum.topic_members WHERE topic_id = $1 AND user_id = $2")
|
||||
.bind(topic)
|
||||
.bind(user)
|
||||
.execute(&mut *tx)
|
||||
.await?,
|
||||
if req.action == "reject" { Action::RejectMember } else { Action::RemoveMember },
|
||||
),
|
||||
_ => return Err(ApiError::bad("Ismeretlen döntés.")),
|
||||
};
|
||||
if done.rows_affected() == 0 {
|
||||
return Err(ApiError::NotFound("request"));
|
||||
}
|
||||
moderation::record(&mut *tx, moderator.id, action, Some(user), None, None, Some(&req.topic), None).await?;
|
||||
tx.commit().await?;
|
||||
let event = crate::live::Event { moderators: true, ..Default::default() }.for_users(vec![user]);
|
||||
crate::live::emit(&state.db, event).await;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,279 @@
|
||||
//! Rules for what members type: nicknames, titles, posts, the bio, avatars.
|
||||
|
||||
use crate::error::ApiError;
|
||||
|
||||
pub const NICKNAME_MIN: usize = 3;
|
||||
pub const NICKNAME_MAX: usize = 24;
|
||||
pub const TITLE_MIN: usize = 4;
|
||||
pub const TITLE_MAX: usize = 120;
|
||||
pub const BODY_MAX: usize = 10_000;
|
||||
pub const BIO_MAX: usize = 500;
|
||||
pub const REASON_MIN: usize = 3;
|
||||
pub const REASON_MAX: usize = 300;
|
||||
|
||||
/// The starter avatars: a glyph on a background colour, `<glyph>-<colour>`.
|
||||
/// The frontend draws them (`src/components/forum/Avatar.tsx`).
|
||||
pub const AVATAR_GLYPHS: [&str; 8] = ["hold", "csillag", "nap", "hullam", "level", "lotusz", "kristaly", "toll"];
|
||||
pub const AVATAR_COLOURS: [&str; 6] = ["ejkek", "lila", "tenger", "borostyan", "rozsa", "erdo"];
|
||||
|
||||
/// Words a nickname may not contain (compared folded, see [`nickname_key`]).
|
||||
const RESERVED: [&str; 7] = ["admin", "moderator", "sorsfonalak", "rendszer", "ugyfelszolgalat", "torolttag", "forum"];
|
||||
|
||||
const SEPARATORS: [char; 4] = [' ', '-', '_', '.'];
|
||||
|
||||
/// A nickname as it will be shown: trimmed, inner spaces collapsed, checked.
|
||||
/// Letters (accented ones too), digits, and single spaces, `-`, `_` or `.`
|
||||
/// between them; it starts with a letter.
|
||||
pub fn nickname(raw: &str) -> Result<String, ApiError> {
|
||||
let name = raw.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
let len = name.chars().count();
|
||||
if !(NICKNAME_MIN..=NICKNAME_MAX).contains(&len) {
|
||||
return Err(ApiError::bad(format!("Az álnév {NICKNAME_MIN}–{NICKNAME_MAX} karakter legyen.")));
|
||||
}
|
||||
if !name.chars().next().is_some_and(latin_letter) {
|
||||
return Err(ApiError::bad("Az álnév betűvel kezdődjön."));
|
||||
}
|
||||
let mut previous_separator = false;
|
||||
for c in name.chars() {
|
||||
let separator = SEPARATORS.contains(&c);
|
||||
if !(separator || latin_letter(c) || c.is_ascii_digit()) {
|
||||
return Err(ApiError::bad("Az álnévben betűk, számok, szóköz, kötőjel, aláhúzás és pont lehet."));
|
||||
}
|
||||
if separator && previous_separator {
|
||||
return Err(ApiError::bad("Az álnévben ne legyen két elválasztó jel egymás után."));
|
||||
}
|
||||
previous_separator = separator;
|
||||
}
|
||||
if previous_separator {
|
||||
return Err(ApiError::bad("Az álnév ne végződjön elválasztó jellel."));
|
||||
}
|
||||
let key = nickname_key(&name);
|
||||
if RESERVED.iter().any(|word| key.contains(&nickname_key(word))) {
|
||||
return Err(ApiError::bad("Ezt az álnevet nem választhatod."));
|
||||
}
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// A letter of the Latin script (accented ones included), so look-alike
|
||||
/// letters of other scripts cannot imitate a nickname.
|
||||
fn latin_letter(c: char) -> bool {
|
||||
c.is_alphabetic()
|
||||
&& matches!(c as u32,
|
||||
0x41..=0x5A | 0x61..=0x7A // ASCII
|
||||
| 0xC0..=0x24F // Latin-1 Supplement, Latin Extended-A and -B
|
||||
| 0x1E00..=0x1EFF) // Latin Extended Additional
|
||||
}
|
||||
|
||||
/// The nickname folded for uniqueness: no accents, case or separators, and
|
||||
/// characters that look alike made the same (`I`, `l`, `1` → `l`; `0` → `o`),
|
||||
/// so "Holdfény", "holdfeny" and "Ho1d-feny" are one name.
|
||||
pub fn nickname_key(name: &str) -> String {
|
||||
deunicode::deunicode(name)
|
||||
.to_lowercase()
|
||||
.chars()
|
||||
.filter(|c| c.is_ascii_alphanumeric())
|
||||
.map(|c| match c {
|
||||
'i' | '1' => 'l',
|
||||
'0' => 'o',
|
||||
other => other,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A thread title: one line, spaces collapsed.
|
||||
pub fn title(raw: &str) -> Result<String, ApiError> {
|
||||
let title: String = raw.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
let len = title.chars().count();
|
||||
if len < TITLE_MIN {
|
||||
return Err(ApiError::bad(format!("A cím legalább {TITLE_MIN} karakter legyen.")));
|
||||
}
|
||||
if len > TITLE_MAX {
|
||||
return Err(ApiError::bad(format!("A cím legfeljebb {TITLE_MAX} karakter lehet.")));
|
||||
}
|
||||
Ok(smileys(&title))
|
||||
}
|
||||
|
||||
/// A post: control characters removed, at most one empty line in a row,
|
||||
/// trailing spaces dropped, the old smileys turned into emoji.
|
||||
pub fn body(raw: &str) -> Result<String, ApiError> {
|
||||
let text = clean_multiline(raw, 2);
|
||||
if text.is_empty() {
|
||||
return Err(ApiError::bad("A hozzászólás nem lehet üres."));
|
||||
}
|
||||
if text.chars().count() > BODY_MAX {
|
||||
return Err(ApiError::bad(format!("A hozzászólás legfeljebb {BODY_MAX} karakter lehet.")));
|
||||
}
|
||||
Ok(smileys(&text))
|
||||
}
|
||||
|
||||
/// The profile's short introduction: no links (old-school profile spam).
|
||||
pub fn bio(raw: &str) -> Result<String, ApiError> {
|
||||
let text = clean_multiline(raw, 1);
|
||||
if text.chars().count() > BIO_MAX {
|
||||
return Err(ApiError::bad(format!("A bemutatkozás legfeljebb {BIO_MAX} karakter lehet.")));
|
||||
}
|
||||
let lower = text.to_lowercase();
|
||||
if lower.contains("http") || lower.contains("www.") {
|
||||
return Err(ApiError::bad("A bemutatkozásba nem tehetsz linket."));
|
||||
}
|
||||
Ok(smileys(&text))
|
||||
}
|
||||
|
||||
/// A moderator's reason, shown in place of what was removed.
|
||||
pub fn reason(raw: &str) -> Result<String, ApiError> {
|
||||
let text: String = raw.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
let len = text.chars().count();
|
||||
if !(REASON_MIN..=REASON_MAX).contains(&len) {
|
||||
return Err(ApiError::bad(format!("Az indoklás {REASON_MIN}–{REASON_MAX} karakter legyen.")));
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
pub fn avatar(raw: &str) -> Result<String, ApiError> {
|
||||
let valid = raw
|
||||
.split_once('-')
|
||||
.is_some_and(|(glyph, colour)| AVATAR_GLYPHS.contains(&glyph) && AVATAR_COLOURS.contains(&colour));
|
||||
if valid { Ok(raw.to_string()) } else { Err(ApiError::bad("Ismeretlen avatar.")) }
|
||||
}
|
||||
|
||||
/// A default avatar for a new member, picked from the nickname.
|
||||
pub fn default_avatar(key: &str) -> String {
|
||||
let n: usize = key.bytes().map(usize::from).sum();
|
||||
format!("{}-{}", AVATAR_GLYPHS[n % AVATAR_GLYPHS.len()], AVATAR_COLOURS[(n / 7) % AVATAR_COLOURS.len()])
|
||||
}
|
||||
|
||||
/// The readable part of a thread's address: `nem-tudom-elengedni-anyukam-hazat`.
|
||||
pub fn slug(title: &str) -> String {
|
||||
let ascii = deunicode::deunicode(title).to_lowercase();
|
||||
let mut slug = String::new();
|
||||
for word in ascii.split(|c: char| !c.is_ascii_alphanumeric()).filter(|w| !w.is_empty()) {
|
||||
if !slug.is_empty() && slug.len() + 1 + word.len() > 60 {
|
||||
break;
|
||||
}
|
||||
if !slug.is_empty() {
|
||||
slug.push('-');
|
||||
}
|
||||
slug.push_str(word);
|
||||
}
|
||||
slug
|
||||
}
|
||||
|
||||
/// Lines with control characters removed and trailing spaces dropped; at most
|
||||
/// `max_breaks` line breaks in a row; trimmed.
|
||||
fn clean_multiline(raw: &str, max_breaks: usize) -> String {
|
||||
let normalized = raw.replace("\r\n", "\n").replace('\r', "\n");
|
||||
let mut out = String::with_capacity(normalized.len());
|
||||
let mut breaks = 0;
|
||||
for line in normalized.split('\n') {
|
||||
let line: String = line.chars().map(|c| if c == '\t' { ' ' } else { c }).filter(|c| !c.is_control()).collect();
|
||||
let line = line.trim_end();
|
||||
if line.trim().is_empty() {
|
||||
breaks += 1;
|
||||
continue;
|
||||
}
|
||||
if !out.is_empty() {
|
||||
out.push_str(&"\n".repeat(breaks.clamp(1, max_breaks)));
|
||||
}
|
||||
breaks = 1;
|
||||
out.push_str(line);
|
||||
}
|
||||
out.trim().to_string()
|
||||
}
|
||||
|
||||
/// The old forums' character smileys and their emoji. A smiley becomes the
|
||||
/// emoji only standing alone (between spaces), so links and the like stay as
|
||||
/// typed. The frontend converts the same list while typing
|
||||
/// (`src/lib/emoticons.ts`); this catches what it did not.
|
||||
pub const EMOTICONS: [(&str, &str); 27] = [
|
||||
(":)", "🙂"),
|
||||
(":-)", "🙂"),
|
||||
("(:", "🙂"),
|
||||
(":D", "😄"),
|
||||
(":-D", "😄"),
|
||||
("xD", "😆"),
|
||||
("XD", "😆"),
|
||||
(";)", "😉"),
|
||||
(";-)", "😉"),
|
||||
(":(", "🙁"),
|
||||
(":-(", "🙁"),
|
||||
(":'(", "😢"),
|
||||
(":P", "😛"),
|
||||
(":-P", "😛"),
|
||||
(":p", "😛"),
|
||||
(":O", "😮"),
|
||||
(":o", "😮"),
|
||||
(":-O", "😮"),
|
||||
(":*", "😘"),
|
||||
(":-*", "😘"),
|
||||
(":/", "😕"),
|
||||
(":|", "😐"),
|
||||
("B)", "😎"),
|
||||
("^^", "😊"),
|
||||
("^_^", "😊"),
|
||||
("<3", "❤️"),
|
||||
("</3", "💔"),
|
||||
];
|
||||
|
||||
fn smileys(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut word = String::new();
|
||||
let flush = |word: &mut String, out: &mut String| {
|
||||
let emoji = EMOTICONS.iter().find(|(code, _)| code == word).map(|(_, e)| *e);
|
||||
out.push_str(emoji.unwrap_or(word));
|
||||
word.clear();
|
||||
};
|
||||
for c in text.chars() {
|
||||
if c.is_whitespace() {
|
||||
flush(&mut word, &mut out);
|
||||
out.push(c);
|
||||
} else {
|
||||
word.push(c);
|
||||
}
|
||||
}
|
||||
flush(&mut word, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn nicknames() {
|
||||
assert_eq!(nickname(" Hold fény ").unwrap(), "Hold fény");
|
||||
assert_eq!(nickname("Csendesvíz").unwrap(), "Csendesvíz");
|
||||
assert!(nickname("ab").is_err());
|
||||
assert!(nickname("1abc").is_err());
|
||||
assert!(nickname("abc--def").is_err());
|
||||
assert!(nickname("abc-").is_err());
|
||||
assert!(nickname("Admin Anna").is_err());
|
||||
assert!(nickname("Sorsfona1ak").is_err());
|
||||
assert!(nickname("Мария").is_err(), "Cyrillic look-alikes are refused");
|
||||
assert!(nickname("név😀").is_err());
|
||||
assert_eq!(nickname_key("Holdfény"), nickname_key("ho1d-feny"));
|
||||
assert_eq!(nickname_key("Ilona"), nickname_key("1lona"));
|
||||
assert_eq!(nickname_key("Olga"), nickname_key("0lga"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bodies() {
|
||||
assert_eq!(body(" Szia :)\r\n\r\n\r\n\r\nMi újság? <3 ").unwrap(), "Szia 🙂\n\nMi újság? ❤️");
|
||||
assert_eq!(body("Hiányzol :'( xD ^^").unwrap(), "Hiányzol 😢 😆 😊");
|
||||
assert_eq!(body("http://x.hu/:)").unwrap(), "http://x.hu/:)", "only smileys standing alone");
|
||||
assert!(body(" \n\t ").is_err());
|
||||
assert_eq!(body("a\u{0007}b").unwrap(), "ab");
|
||||
assert!(bio("Látogass meg: www.pelda.hu").is_err());
|
||||
assert_eq!(bio("Első sor\n\n\nMásodik").unwrap(), "Első sor\nMásodik");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn titles_slugs_avatars() {
|
||||
assert_eq!(title(" Nem tudom elengedni ").unwrap(), "Nem tudom elengedni");
|
||||
assert!(title("abc").is_err());
|
||||
assert_eq!(slug("Nem tudom elengedni anyukám házát!"), "nem-tudom-elengedni-anyukam-hazat");
|
||||
assert!(slug(&"hosszú ".repeat(30)).len() <= 60);
|
||||
assert!(avatar("hold-ejkek").is_ok());
|
||||
assert!(avatar("hold-piros").is_err());
|
||||
assert!(avatar(&default_avatar("csendesvlz")).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { Rich } from "@/components/Rich";
|
||||
import { TarotCard, TarotCardBack } from "@/components/tarot/TarotCard";
|
||||
import { PublicHeader } from "@/components/SiteHeader";
|
||||
import { ChristmasTree } from "@/components/ChristmasTree";
|
||||
import { forumEnabled } from "@/lib/forumServer";
|
||||
import { isChristmasTime } from "@/lib/season";
|
||||
import example from "@/content/pelda.json";
|
||||
import { tarotCard } from "@/lib/tarot";
|
||||
@@ -134,6 +135,20 @@ export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean;
|
||||
</h2>
|
||||
</div>
|
||||
<div className="lp-free-grid">
|
||||
{forumEnabled() && (
|
||||
<Link href="/forum" className="card lp-free-card lp-free-featured">
|
||||
<span className="lp-free-featured-label">Közösség</span>
|
||||
<strong>Fórum</strong>
|
||||
<span className="lp-free-featured-text">
|
||||
Tartalmas beszélgetések, ahol álnéven, a valódi neved nélkül oszthatod meg, ami foglalkoztat vagy a
|
||||
szívedet nyomja. Spiritualitás, álmok, az égbolt, és bármi, amiről jólesik beszélni.
|
||||
</span>
|
||||
<span className="lp-free-featured-quiet">
|
||||
Pörgő videók helyett csendes, figyelmes beszélgetés: itt az elmélyülés a lényeg.
|
||||
</span>
|
||||
<span className="lp-free-go">Benézek →</span>
|
||||
</Link>
|
||||
)}
|
||||
<Link href="/szuletesi-horoszkop" className="card lp-free-card">
|
||||
<strong>Születési horoszkóp</strong>
|
||||
<span className="muted">
|
||||
|
||||
@@ -147,6 +147,61 @@ export default async function PrivacyPage() {
|
||||
<td>Hibák kijavítása, kérdések megválaszolása</td>
|
||||
<td>Jogos érdek (6. cikk (1) f)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Fórumprofilod: az álneved (a korábbiakat 90 napig, hogy más ne vehesse fel), az avatarod vagy a
|
||||
feltöltött saját képed (kicsinyítve, a kép rejtett adatai, például a helyszín nélkül), a
|
||||
bemutatkozásod, a képletedből megosztott jegyek, hogy önkéntes kísérő vagy-e, a Támogató
|
||||
jelvény (ha bekapcsolod, mások látják, hogy vásároltál), hogy az első tizenöt tag közé tartozol-e
|
||||
(Alapító tag), a láthatatlan mód és az e-mail-értesítések beállítása
|
||||
</td>
|
||||
<td>Részvétel a fórumon; a jegyek megosztása és a jelvények a saját döntésed</td>
|
||||
<td>Szerződés teljesítése</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
A fórumon írt szálaid és hozzászólásaid, a reakcióid és „Ez segített” jelöléseid, a pontjaid és a
|
||||
rangod; kiket említettél (@álnév); hogy mit olvastál el, mely szálakat követed, és kiket
|
||||
némítottál el
|
||||
</td>
|
||||
<td>A fórum működése, a rangok, az újdonságok jelzése</td>
|
||||
<td>Szerződés teljesítése</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
A fórumkérdéseidhez csatolt képlet, éves előrejelzés vagy összevetés megosztó linkje
|
||||
</td>
|
||||
<td>Hogy a tagok lássák, amiről kérdezel; a csatolás a saját döntésed</td>
|
||||
<td>Szerződés teljesítése</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Zárt témákba küldött jelentkezéseid (a pár szavas indoklással) és a tagságaid</td>
|
||||
<td>A zárt témák: a moderátorok döntenek a felvételről</td>
|
||||
<td>Szerződés teljesítése</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Mikor jártál utoljára a fórumon</td>
|
||||
<td>Az online jelzés (zöld pötty); a láthatatlan móddal kikapcsolhatod</td>
|
||||
<td>Szerződés teljesítése</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Privát beszélgetéseid: a kérések bemutatkozása, az elfogadás, elutasítás vagy tiltás, és az
|
||||
üzenetek
|
||||
</td>
|
||||
<td>Privát beszélgetés más tagokkal</td>
|
||||
<td>Szerződés teljesítése</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Jelentések (ki, mit, milyen okból jelentett), a moderálási napló (ki, mikor, mit és miért döntött), az
|
||||
eltiltások ideje és oka
|
||||
</td>
|
||||
<td>A házirend betartatása, a bejelentések kezelése, a döntések visszakereshetősége</td>
|
||||
<td>
|
||||
Jogi kötelezettség ((EU) 2022/2065 rendelet, DSA; 6. cikk (1) c); jogos érdek (6. cikk (1) f)
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>IP-cím, böngésző adatai, a kérések ideje (szervernaplók)</td>
|
||||
<td>Biztonság, hibakeresés, visszaélések kiszűrése</td>
|
||||
@@ -170,6 +225,25 @@ export default async function PrivacyPage() {
|
||||
képlet rajzát és a legfrissebb rövid összefoglalót. Nevet és születési adatot nem tesz közzé, a keresők nem
|
||||
listázzák, és a linket bármikor visszavonhatod.
|
||||
</p>
|
||||
<p>
|
||||
<strong>Fórum:</strong> amit a nyilvános témákban írsz, bárki láthatja, a keresők is; a csak tagoknak szóló
|
||||
témákat csak belépett felhasználók látják, a zárt témákat csak a jóváhagyott tagjaik. A hozzászólásaid
|
||||
mellett az álneved, az avatarod, a rangod, az általad megosztott jegyek és a bekapcsolt jelvényeid
|
||||
(Kísérő, Támogató) látszanak; a valódi neved, az e-mail-címed és a születési adataid nem, és a
|
||||
képletedből soha nem mutatunk fokokat. A privát üzeneteidet csak a beszélgetés két résztvevője látja; a
|
||||
moderátorok csak akkor, ha valaki egy üzenetet jelent, és akkor is csak a jelentett üzenetet és az előtte
|
||||
lévő néhányat. A moderátorok (az üzemeltető által kijelölt tagok) a valódi nevedet és az e-mail-címedet nem
|
||||
látják. Ha egy kérdésedhez csatolod a képletedet, az éves előrejelzésedet vagy egy összevetést, azt csak a
|
||||
belépett tagok látják: a rajzot fokokkal és házakkal, a rövid összefoglalót vagy az előrejelzés szövegét,
|
||||
nevek, születési dátum, idő és hely nélkül. A fokokból egy jártas asztrológus nagyjából kiszámolhatja a
|
||||
születési napot és időt, az előrejelzés kezdőnapjából pedig a születésnap kiderül. A csatolt képletet
|
||||
bármikor leveheted, és a kérdés törlésével a link is megszűnik. Ha egy hozzászólásban YouTube-link van, a
|
||||
videó címét és képét a szerverünk kéri le, és a saját szerverünkről mutatjuk: a fórum olvasásakor a YouTube
|
||||
nem kap rólad adatot. Ha a videót a fórumon elindítod, a lejátszó a YouTube (Google) szerveréről töltődik be
|
||||
(youtube-nocookie.com), amely látja az IP-címedet és a lejátszás adatait; telefonon a megnyitás a YouTube
|
||||
alkalmazásába visz. A fórum szabályai az{" "}
|
||||
<Link href="/aszf#forum">ÁSZF 8. pontjában</Link> vannak.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
@@ -186,7 +260,8 @@ export default async function PrivacyPage() {
|
||||
</ul>
|
||||
<p>
|
||||
<strong>Mire használjuk:</strong> a fiókod létrehozására és arra, hogy belépéskor felismerjünk; az
|
||||
e-mail-címedet a rendszerlevelekhez (például ha elkészült egy elemzésed vagy elfogadták a meghívódat); a
|
||||
e-mail-címedet a rendszerlevelekhez (például ha elkészült egy elemzésed, elfogadták a meghívódat, vagy
|
||||
válasz érkezett vagy megemlítettek a fórumon, illetve a fórum heti összefoglalója, ha ezeket kérted); a
|
||||
nevedet a megjelenítéshez; a nyelvet az oldal és az elemzések nyelvéhez.
|
||||
</p>
|
||||
<p>
|
||||
@@ -234,6 +309,10 @@ export default async function PrivacyPage() {
|
||||
kérdéseidbe se írj neveket vagy érzékeny adatot (például egészségügyi adatot). Az elemzés szórakoztató és
|
||||
önismereti célú szöveg, nem minősül egészségügyi, pénzügyi, jogi vagy más szakmai tanácsnak.
|
||||
</p>
|
||||
<p>
|
||||
A fórumon írt hozzászólásokat és a privát üzeneteket nem küldjük el mesterséges intelligenciának. Ha ezt
|
||||
később bevezetnénk (például a kéretlen hirdetések kiszűrésére), előtte itt jelezzük.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
@@ -301,14 +380,30 @@ export default async function PrivacyPage() {
|
||||
törlése után név és megjegyzés nélkül, statisztikaként megtartjuk.
|
||||
</li>
|
||||
<li>A számlázáshoz szükséges adatokat a számviteli törvény szerinti ideig (8 évig) őrizzük.</li>
|
||||
<li>
|
||||
A fórumprofilodat (a saját képeddel együtt), a privát beszélgetéseidet, a reakcióidat, a követéseidet és
|
||||
a zárt témák tagságát a fiókod törléséig; az elutasított jelentkezést azonnal töröljük. A fiók
|
||||
törlésekor a privát beszélgetéseid a másik fél számára is törlődnek. A szálaid és a hozzászólásaid „Törölt
|
||||
tag” néven megmaradnak, hogy a beszélgetések érthetők maradjanak; ha a törlésüket is kéred, írj a fenti
|
||||
e-mail-címre.
|
||||
</li>
|
||||
<li>
|
||||
A moderátor által eltávolított hozzászólás szövegét az esetleges kifogás miatt 1 évig őrizzük, utána csak a
|
||||
helye és az indoklás marad. A lezárt jelentéseket és a lejárt eltiltások okát 1 évig, a moderálási naplót
|
||||
2 évig őrizzük.
|
||||
</li>
|
||||
<li>
|
||||
Az el nem fogadott beszélgetési kéréseket 90 nap után töröljük. A korábbi álneveidet 90 napig foglaljuk le.
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>8. Sütik</h2>
|
||||
<p>
|
||||
Csak egy, a működéshez feltétlenül szükséges sütit használunk (<code>sf_session</code>), amely belépve
|
||||
tart. Reklám- vagy követő sütiket, illetve látogatottságmérőt nem használunk.
|
||||
A működéshez feltétlenül szükséges sütit használunk (<code>sf_session</code>), amely belépve tart. Ha a
|
||||
fórumon világos vagy sötét témát választasz, a választásodat egy második süti (<code>sf_forum_theme</code>)
|
||||
őrzi egy évig; mást nem tárol. Reklám- vagy követő sütiket, illetve látogatottságmérőt nem használunk.
|
||||
</p>
|
||||
<p>
|
||||
A belépés nélküli <Link href="/szuletesi-horoszkop">születési horoszkópnál</Link> a megadott születési adatokat
|
||||
@@ -325,13 +420,15 @@ export default async function PrivacyPage() {
|
||||
<ul>
|
||||
<li>
|
||||
<strong>Hozzáférés és adathordozhatóság:</strong> a <Link href="/profil#adataim">Profil</Link> oldalon
|
||||
egy kattintással letöltheted minden adatodat.
|
||||
egy kattintással letöltheted minden adatodat, a fórumon írtakat és beállítottakat is.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Helyesbítés:</strong> a nevedet és a születési adataidat a Profil oldalon módosíthatod.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Törlés:</strong> a fiókodat és minden adatodat a Profil oldalon törölheted.
|
||||
<strong>Törlés:</strong> a fiókodat és minden adatodat a Profil oldalon törölheted. A fórumon a saját
|
||||
hozzászólásaidat egyenként is törölheted; a fiók törlése után „Törölt tag” néven maradók törlését
|
||||
e-mailben kérheted.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Korlátozás és tiltakozás:</strong> a fenti e-mail-címen kérheted.
|
||||
|
||||
@@ -9,7 +9,7 @@ import { ROLE_LABELS, formatDate } from "@/lib/astro";
|
||||
import type { AdminUser, Package, Role } from "@/lib/types";
|
||||
|
||||
const PAGE_SIZE = 25;
|
||||
const EDITABLE_ROLES: Role[] = ["user", "creator", "admin"];
|
||||
const EDITABLE_ROLES: Role[] = ["user", "creator", "moderator", "admin"];
|
||||
type UnitKind = "natal" | "synastry" | "forecast" | "question" | "tarot";
|
||||
|
||||
/** `short`: the mark in the list, where the names do not fit (explained under it). */
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
// Forwards /api/v1/* to the backend, so the browser talks to one origin and
|
||||
// the session cookie belongs to the frontend's host (no CORS needed).
|
||||
// Forwards /api/v1/* to the backend (and /api/v1/forum/* to the forum
|
||||
// service), so the browser talks to one origin and the session cookie belongs
|
||||
// to the frontend's host (no CORS needed).
|
||||
import { revalidateTag } from "next/cache";
|
||||
import type { NextRequest } from "next/server";
|
||||
|
||||
import { CELEBRITIES_TAG } from "@/lib/celebrities";
|
||||
import { FORUM_URL } from "@/lib/forumServer";
|
||||
import { BACKEND_URL } from "@/lib/server";
|
||||
import { SHARES_TAG } from "@/lib/share";
|
||||
|
||||
@@ -22,7 +24,13 @@ const SKIP_RESPONSE_HEADERS = new Set(["connection", "content-encoding", "conten
|
||||
|
||||
async function forward(req: NextRequest, ctx: { params: Promise<{ path: string[] }> }) {
|
||||
const { path } = await ctx.params;
|
||||
const target = `${BACKEND_URL}/v1/${path.map(encodeURIComponent).join("/")}${req.nextUrl.search}`;
|
||||
// The forum is a service of its own; without FORUM_URL it is switched off.
|
||||
const forum = path[0] === "forum";
|
||||
if (forum && !FORUM_URL) {
|
||||
return Response.json({ error: { code: "not_found", message: "A fórum nincs bekapcsolva." } }, { status: 404 });
|
||||
}
|
||||
const base = forum ? FORUM_URL : BACKEND_URL;
|
||||
const target = `${base}/v1/${path.map(encodeURIComponent).join("/")}${req.nextUrl.search}`;
|
||||
|
||||
const headers = new Headers();
|
||||
for (const name of REQUEST_HEADERS) {
|
||||
@@ -53,7 +61,9 @@ async function forward(req: NextRequest, ctx: { params: Promise<{ path: string[]
|
||||
});
|
||||
for (const cookie of res.headers.getSetCookie()) out.append("set-cookie", cookie);
|
||||
// A revoked link must disappear at once from the cached share pages.
|
||||
if (req.method === "DELETE" && path[0] === "shares" && res.ok) revalidateTag(SHARES_TAG, { expire: 0 });
|
||||
// A revoked link (also a chart taken off a forum question, or the question deleted) goes from the cache.
|
||||
const revokes = path[0] === "shares" || (path[0] === "forum" && path[1] === "posts");
|
||||
if (req.method === "DELETE" && revokes && res.ok) revalidateTag(SHARES_TAG, { expire: 0 });
|
||||
// An admin's change to a famous person shows on the public pages at once.
|
||||
if (req.method !== "GET" && path[0] === "admin" && path[1] === "celebrities" && res.ok) {
|
||||
revalidateTag(CELEBRITIES_TAG, { expire: 0 });
|
||||
|
||||
@@ -35,7 +35,8 @@ export default async function TermsPage() {
|
||||
megadott születési adatokból kiszámítja és megrajzolja a születési képletet, és ingyenes rövid összefoglalót
|
||||
ad. Csomagok vásárlásával a felhasználó szoftveresen (mesterséges intelligenciával) előállított, személyre
|
||||
szabott szöveges tartalmakat kérhet: részletes képletelemzést, kapcsolati elemzést, éves előrejelzést,
|
||||
kártyajóslást és kérdésekre adott válaszokat, valamint további személyeket vehet fel.
|
||||
kártyajóslást és kérdésekre adott válaszokat, valamint további személyeket vehet fel. A Sorsfonalak része egy
|
||||
ingyenes közösségi fórum is (8. pont).
|
||||
</p>
|
||||
<p>
|
||||
A tartalmak szórakoztató és önismereti célúak. Nem minősülnek orvosi, pszichológiai, pénzügyi, jogi vagy
|
||||
@@ -136,17 +137,123 @@ export default async function TermsPage() {
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>8. A fiók megszüntetése</h2>
|
||||
<section id="forum">
|
||||
<h2>8. A fórum</h2>
|
||||
<p>
|
||||
A fiók a Profil oldalon bármikor törölhető. A fel nem használt egységek ezzel megszűnnek; ezekért
|
||||
visszatérítés nem jár, kivéve, ha a törlést a szolgáltatás hibája tette szükségessé. A jogszabálysértő
|
||||
vagy a szolgáltatással visszaélő felhasználó fiókját felfüggeszthetjük vagy megszüntethetjük.
|
||||
A Sorsfonalak része egy ingyenes közösségi fórum (sorsfonalak.hu/forum). Ez a pont a fórum szabályait
|
||||
(házirend), a moderálás rendjét és a jogsértő tartalmak bejelentését írja le, az Európai Unió digitális
|
||||
szolgáltatásokról szóló (EU) 2022/2065 rendelete (DSA) szerint.
|
||||
</p>
|
||||
|
||||
<h3>8.1. Olvasás, írás, álnév</h3>
|
||||
<p>
|
||||
A nyilvános témákat bárki olvashatja, és a keresők is megjeleníthetik. A csak tagoknak szóló témákat
|
||||
(például „Ami a szívemen van”) csak belépve lehet olvasni, és a keresők nem látják. A zárt témákat csak a jóváhagyott tagjaik olvashatják; a
|
||||
csatlakozásról egy moderátor dönt. Írni, reagálni és üzenni
|
||||
belépve, egy választott álnévvel lehet. Az álnév ne legyen a valódi neved, ha nem szeretnéd, hogy
|
||||
felismerjenek; nem lehet sértő vagy megtévesztő, és nem utánozhat más tagot, moderátort vagy a
|
||||
Sorsfonalakat. A valódi neved, az e-mail-címed és a születési adataid a fórumon nem jelennek meg; a
|
||||
képletedből csak annyi látszik, amennyit a fórumprofilodban megosztasz, fokok nélkül.
|
||||
A Kereső rangtól saját képet is feltölthetsz avatarnak: csak olyat, amelyhez jogod van, és amelyen más nem
|
||||
ismerhető fel a hozzájárulása nélkül; a moderátorok a nem odaillő képet eltávolíthatják.
|
||||
</p>
|
||||
|
||||
<h3>8.2. Házirend</h3>
|
||||
<p>A fórum a nyugodt beszélgetés és a meghallgatás helye. Kérjük:</p>
|
||||
<ul>
|
||||
<li>tisztelettel írj másokról és másokhoz, kioktatás és gúnyolódás nélkül;</li>
|
||||
<li>ha valaki csak meghallgatást kér, ne adj neki kéretlen tanácsot;</li>
|
||||
<li>vitatkozz gondolatokkal, ne mások hitével, világnézetével vagy életével.</li>
|
||||
</ul>
|
||||
<p>Tilos:</p>
|
||||
<ul>
|
||||
<li>mások zaklatása, fenyegetése, sértegetése, a gyűlöletkeltés;</li>
|
||||
<li>jogsértő tartalom, például szerzői jogot sértő szöveg vagy bűncselekményre való felhívás;</li>
|
||||
<li>
|
||||
más személyes adatainak (név, elérhetőség, születési adatok, fénykép) közzététele az érintett
|
||||
hozzájárulása nélkül;
|
||||
</li>
|
||||
<li>
|
||||
szolgáltatás vagy termék hirdetése és árusítása (például jóslás, energetikai gyógyítás, tanfolyam),
|
||||
reklám, kéretlen üzenetek;
|
||||
</li>
|
||||
<li>pénz, adatok vagy szívességek kérése megtévesztéssel, más nevében való fellépés;</li>
|
||||
<li>biztatás orvosi kezelés abbahagyására vagy helyettesítésére.</li>
|
||||
</ul>
|
||||
<p>
|
||||
A fórum nem helyettesíti az orvost, a pszichológust és más szakembert. Ha te vagy valaki más veszélyben van,
|
||||
hívd a 112-t. A lelki elsősegély-szolgálat ingyenes, éjjel-nappal hívható száma: 116-123.
|
||||
</p>
|
||||
|
||||
<h3>8.3. A hozzászólások</h3>
|
||||
<p>
|
||||
A hozzászólásaidért te felelsz. A szerzői jogod a tiéd marad; a közzététellel ingyenes, nem kizárólagos
|
||||
engedélyt adsz arra, hogy a hozzászólást a fórumon megjelenítsük (a nyilvános témákban a keresők számára
|
||||
is), amíg ott van. A saját hozzászólásodat szerkesztheted és törölheted. Ha a fiókodat törlöd, a szálaid és
|
||||
a hozzászólásaid „Törölt tag” néven megmaradnak, hogy a beszélgetések érthetők maradjanak. Ha ezt nem
|
||||
szeretnéd, előtte töröld őket, vagy kérd a törlésüket a {email} címen.
|
||||
</p>
|
||||
|
||||
<h3>8.4. Privát üzenetek</h3>
|
||||
<p>
|
||||
Privát beszélgetést a Kereső rangtól, egy rövid bemutatkozást tartalmazó kéréssel lehet kezdeményezni. A
|
||||
címzett elfogadhatja, elutasíthatja (erről a küldő nem kap értesítést), vagy letilthatja a küldőt. A privát
|
||||
üzeneteket a moderátorok nem olvassák. Ha valaki egy üzenetet jelent, a moderátorok a jelentett üzenetet és
|
||||
az előtte lévő néhány üzenetet látják, hogy dönteni tudjanak.
|
||||
</p>
|
||||
|
||||
<h3>8.5. Rangok és korlátok</h3>
|
||||
<p>
|
||||
A rang a hozzászólásokra kapott reakciókból és a tagság idejéből jön; pénzbeli értéke nincs, és nem
|
||||
vásárolható meg. Az új tagok (Vándor rang) naponta legfeljebb 3 szálat nyithatnak és 20 hozzászólást
|
||||
írhatnak; ezt a korlátot egy csomag megvásárlása feloldja. A visszaélések megelőzésére további korlátok is
|
||||
vannak, például néhány másodperc két hozzászólás között, és napi felső határ a beszélgetési kérésekre és a
|
||||
jelentésekre.
|
||||
</p>
|
||||
|
||||
<h3>8.6. Bejelentés és moderálás</h3>
|
||||
<p>
|
||||
Jogsértő vagy a házirendbe ütköző tartalmat a hozzászólás (vagy a neked küldött üzenet) melletti „Jelentés”
|
||||
gombbal jelezhetsz; fiók nélkül a {email} címen, a tartalom linkjével és azzal, hogy mi vele a gond. A
|
||||
gombbal küldött jelentés beérkezését azonnal visszaigazoljuk, és a döntésről e-mailben értesítünk.
|
||||
</p>
|
||||
<p>
|
||||
A fórumot és a jelentéseket az üzemeltető által kijelölt moderátorok figyelik. Minden döntést ember hoz;
|
||||
automatikus (algoritmikus) moderálást jelenleg nem használunk, és ha bevezetjük, itt jelezzük. A lehetséges
|
||||
intézkedések: a hozzászólás vagy a szál eltávolítása (a helyén az indoklás látszik), a szál lezárása, és a
|
||||
tag eltiltása az írástól meghatározott időre vagy véglegesen. Az eltiltott tag olvashat, de nem írhat; az
|
||||
eltiltás a megvásárolt szolgáltatásokat nem érinti. Az intézkedésről és az indokáról az érintett tagot
|
||||
e-mailben is tájékoztatjuk.
|
||||
</p>
|
||||
<p>
|
||||
Ha szerinted egy döntés téves, a {email} címen kifogást tehetsz: a döntést egy másik moderátor vagy az
|
||||
üzemeltető vizsgálja felül, és válaszolunk. A 10. pontban írt jogorvoslati lehetőségek ezen túl is
|
||||
megilletnek.
|
||||
</p>
|
||||
<p>
|
||||
Kapcsolattartási pont a hatóságok és a felhasználók számára (DSA 11. és 12. cikk): {email}, magyar nyelven.
|
||||
</p>
|
||||
|
||||
<h3>8.7. Értesítések</h3>
|
||||
<p>
|
||||
A fórum e-mailben értesíthet a neked írt válaszokról, a követett szálakról és a privát üzenetekről. Ezeket a
|
||||
fórumprofilodban állíthatod be, és minden ilyen levél alján egy kattintással leiratkozhatsz. A moderálásról
|
||||
és a jelentéseid elbírálásáról szóló leveleket ettől függetlenül elküldjük.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>9. Panaszkezelés, jogorvoslat</h2>
|
||||
<h2>9. A fiók megszüntetése</h2>
|
||||
<p>
|
||||
A fiók a Profil oldalon bármikor törölhető. A fel nem használt egységek ezzel megszűnnek; ezekért
|
||||
visszatérítés nem jár, kivéve, ha a törlést a szolgáltatás hibája tette szükségessé. A jogszabálysértő
|
||||
vagy a szolgáltatással visszaélő felhasználó fiókját felfüggeszthetjük vagy megszüntethetjük. A fórumon írt
|
||||
hozzászólások a fiók törlése után „Törölt tag” néven megmaradnak (8.3. pont).
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>10. Panaszkezelés, jogorvoslat</h2>
|
||||
<p>
|
||||
Panaszt a {email} címen tehetsz; 30 napon belül írásban válaszolunk. Ha a panaszt nem rendezzük, a
|
||||
szolgáltató székhelye szerint illetékes békéltető testülethez fordulhatsz ({ARBITRATION_BOARD.name},{" "}
|
||||
@@ -157,7 +264,7 @@ export default async function TermsPage() {
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>10. Egyéb</h2>
|
||||
<h2>11. Egyéb</h2>
|
||||
<p>
|
||||
Az ÁSZF módosítása a módosítás után kötött vásárlásokra vonatkozik; a lényeges változásokat az oldalon
|
||||
jelezzük. A szerződés és a szolgáltatás nyelve magyar, a szerződésre a magyar jog irányadó.
|
||||
@@ -165,7 +272,7 @@ export default async function TermsPage() {
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>11. A szolgáltató adatai</h2>
|
||||
<h2>12. A szolgáltató adatai</h2>
|
||||
<OperatorDetails hosting />
|
||||
</section>
|
||||
</main>
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
|
||||
import { ThreadList } from "@/components/forum/ThreadList";
|
||||
import type { TopicPage } from "@/lib/forum";
|
||||
import { forumGet } from "@/lib/forumServer";
|
||||
|
||||
type Props = { params: Promise<{ tema: string }>; searchParams: Promise<{ oldal?: string }> };
|
||||
|
||||
async function load(slug: string, page: number) {
|
||||
return forumGet<TopicPage>(`/v1/forum/topics/${encodeURIComponent(slug)}?page=${page}`);
|
||||
}
|
||||
|
||||
function pageOf(raw: string | undefined): number {
|
||||
const n = Number(raw ?? 1);
|
||||
return Number.isInteger(n) && n > 0 ? n : 1;
|
||||
}
|
||||
|
||||
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||
const { tema } = await params;
|
||||
const res = await load(tema, 1);
|
||||
if (!res.ok) return { title: "Fórum" };
|
||||
const { topic } = res.data;
|
||||
// Members-only topics stay out of search engines.
|
||||
return {
|
||||
title: topic.name,
|
||||
description: topic.description,
|
||||
robots: topic.visibility === "public" ? undefined : { index: false, follow: false },
|
||||
};
|
||||
}
|
||||
|
||||
/** A topic's threads: pinned ones first, then by the latest post. */
|
||||
export default async function TopicPageView({ params, searchParams }: Props) {
|
||||
const { tema } = await params;
|
||||
const page = pageOf((await searchParams).oldal);
|
||||
const res = await load(tema, page);
|
||||
if (!res.ok) {
|
||||
if (res.status === 401) redirect(`/belepes?vissza=/forum/${tema}`);
|
||||
notFound();
|
||||
}
|
||||
const { topic, threads, has_more, viewer } = res.data;
|
||||
return (
|
||||
<div className="fh">
|
||||
<nav className="forum-crumbs" aria-label="Morzsamenü">
|
||||
<Link href="/forum">Fórum</Link>
|
||||
</nav>
|
||||
<header className="ftopic-head">
|
||||
<div>
|
||||
<h1>{topic.name}</h1>
|
||||
<p className="muted">{topic.description}</p>
|
||||
{topic.visibility !== "public" && (
|
||||
<p className="ftopic-private">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<rect x="5" y="11" width="14" height="9" rx="2" />
|
||||
<path d="M8 11V8a4 4 0 0 1 8 0v3" />
|
||||
</svg>
|
||||
{topic.visibility === "members"
|
||||
? "Ezt a témát csak belépett tagok látják: amit itt írsz, kívülről és a keresőkből nem olvasható."
|
||||
: "Zárt kör: ezt a témát csak a jóváhagyott tagjai látják."}
|
||||
</p>
|
||||
)}
|
||||
{topic.archived && (
|
||||
<p className="ftopic-private">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<rect x="3.5" y="4.5" width="17" height="4.5" rx="1" />
|
||||
<path d="M5 9v9.5a1.5 1.5 0 0 0 1.5 1.5h11a1.5 1.5 0 0 0 1.5-1.5V9M10 13h4" />
|
||||
</svg>
|
||||
Archivált téma: a szálak olvashatók, de új szál és hozzászólás már nem írható.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{!topic.archived && (
|
||||
<Link
|
||||
href={viewer.logged_in ? `/forum/uj?tema=${topic.slug}` : `/belepes?vissza=/forum/uj?tema=${topic.slug}`}
|
||||
className="btn btn-primary"
|
||||
>
|
||||
Új szál
|
||||
</Link>
|
||||
)}
|
||||
</header>
|
||||
{threads.length === 0 ? (
|
||||
<p className="fh-card fh-empty">Ebben a témában még nincs szál. Nyisd meg te az elsőt!</p>
|
||||
) : (
|
||||
<div className="fh-card fh-flush">
|
||||
<ThreadList threads={threads} showTopic={false} />
|
||||
</div>
|
||||
)}
|
||||
{(page > 1 || has_more) && (
|
||||
<nav className="forum-pager" aria-label="Lapozás">
|
||||
{page > 1 ? <Link href={`/forum/${topic.slug}?oldal=${page - 1}`}>‹ Újabbak</Link> : <span />}
|
||||
<span className="hint">{page}. oldal</span>
|
||||
{has_more ? <Link href={`/forum/${topic.slug}?oldal=${page + 1}`}>Régebbiek ›</Link> : <span />}
|
||||
</nav>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { Avatar } from "@/components/forum/Avatar";
|
||||
import { api } from "@/lib/api";
|
||||
import type { ForumAuthor } from "@/lib/forum";
|
||||
|
||||
/** The members the viewer muted, each with "Feloldás". */
|
||||
export function MutedList() {
|
||||
const [muted, setMuted] = useState<ForumAuthor[] | null>(null);
|
||||
useEffect(() => {
|
||||
api<{ muted: ForumAuthor[] }>("/forum/me/mutes")
|
||||
.then((res) => setMuted(res.muted))
|
||||
.catch(() => setMuted([]));
|
||||
}, []);
|
||||
if (!muted || muted.length === 0) return null;
|
||||
return (
|
||||
<fieldset className="fnew-set">
|
||||
<legend>Elnémított tagok</legend>
|
||||
<ul className="fmuted">
|
||||
{muted.map((m) => (
|
||||
<li key={m.nickname}>
|
||||
<span className="fh-online-item">
|
||||
<Avatar avatar={m.avatar} size={28} />
|
||||
{m.nickname}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-ghost"
|
||||
onClick={async () => {
|
||||
await api(`/forum/members/${encodeURIComponent(m.nickname)}/mute`, { method: "DELETE" });
|
||||
setMuted((list) => (list ?? []).filter((x) => x.nickname !== m.nickname));
|
||||
}}
|
||||
>
|
||||
Feloldás
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<span className="hint">
|
||||
Az elnémított tagok szálai nem jelennek meg a listáidban, és nem kapsz értesítést tőlük.
|
||||
</span>
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { AVATAR_COLOURS, AVATAR_GLYPHS, Avatar, GLYPH_NAMES } from "@/components/forum/Avatar";
|
||||
import { signsText } from "@/components/forum/AuthorLine";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { withEmoji } from "@/lib/emoticons";
|
||||
import { type ChartShare, type EmailSettings, type ForumMe, banText, memberHref } from "@/lib/forum";
|
||||
|
||||
import { MutedList } from "./MutedList";
|
||||
|
||||
const SHARE_LEVELS: { value: ChartShare; label: string }[] = [
|
||||
{ value: "none", label: "Semmit" },
|
||||
{ value: "sun", label: "Csak a Nap-jegyemet" },
|
||||
{ value: "big3", label: "Nap, Hold és Aszcendens" },
|
||||
{ value: "planets", label: "Minden bolygó jegyét" },
|
||||
];
|
||||
|
||||
export function ProfileForm({ me, back }: { me: ForumMe; back: string | null }) {
|
||||
const router = useRouter();
|
||||
const member = me.member;
|
||||
const [nickname, setNickname] = useState(member?.nickname ?? "");
|
||||
const [check, setCheck] = useState<{ ok: boolean; message?: string } | null>(null);
|
||||
const [avatar, setAvatar] = useState(member?.avatar ?? "");
|
||||
const [bio, setBio] = useState(member?.bio ?? "");
|
||||
const [share, setShare] = useState<ChartShare>(member?.chart_share ?? "none");
|
||||
const [invisible, setInvisible] = useState(member?.invisible ?? false);
|
||||
const [email, setEmail] = useState<EmailSettings>(
|
||||
member?.email ?? {
|
||||
replies: "daily",
|
||||
followed: "off",
|
||||
messages: "instant",
|
||||
mentions: "instant",
|
||||
listener: "off",
|
||||
weekly: false,
|
||||
},
|
||||
);
|
||||
const [listener, setListener] = useState(member?.listener ?? false);
|
||||
const [supporter, setSupporter] = useState(member?.supporter_badge ?? false);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const uploaded = avatar.startsWith("upload:");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [saved, setSaved] = useState(false);
|
||||
|
||||
// While typing: valid and free? (Not for the member's own current name.)
|
||||
useEffect(() => {
|
||||
const name = nickname.trim();
|
||||
if (!name || name === member?.nickname) {
|
||||
setCheck(null);
|
||||
return;
|
||||
}
|
||||
const timer = window.setTimeout(() => {
|
||||
api<{ ok: boolean; message?: string }>(`/forum/nickname-check?name=${encodeURIComponent(name)}`)
|
||||
.then(setCheck)
|
||||
.catch(() => setCheck(null));
|
||||
}, 400);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [nickname, member?.nickname]);
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setSaved(false);
|
||||
try {
|
||||
const res = await api<ForumMe>("/forum/me", {
|
||||
method: "PUT",
|
||||
body: {
|
||||
nickname,
|
||||
avatar: avatar || null,
|
||||
bio,
|
||||
chart_share: share,
|
||||
invisible,
|
||||
email,
|
||||
listener,
|
||||
supporter_badge: supporter,
|
||||
},
|
||||
});
|
||||
if (back) {
|
||||
router.push(back);
|
||||
} else if (!member && res.member) {
|
||||
router.push(memberHref(res.member.nickname));
|
||||
} else {
|
||||
setSaved(true);
|
||||
}
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
setError(errorText(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const preview = share === "none" ? null : me.chart?.[share];
|
||||
|
||||
return (
|
||||
<form className="fprof" onSubmit={submit}>
|
||||
{member?.banned_until && (
|
||||
<p className="fh-banner fh-banner-warn">
|
||||
Most nem írhatsz a fórumba ({banText(member.banned_until)}).
|
||||
{member.ban_reason && ` Indok: ${member.ban_reason}`}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="field">
|
||||
<label htmlFor="fprof-nick">Álnév</label>
|
||||
<input
|
||||
id="fprof-nick"
|
||||
className="inp"
|
||||
value={nickname}
|
||||
onChange={(e) => setNickname(e.target.value)}
|
||||
maxLength={24}
|
||||
required
|
||||
autoComplete="off"
|
||||
aria-describedby="fprof-nick-hint"
|
||||
/>
|
||||
<span id="fprof-nick-hint" className={check && !check.ok ? "hint warn" : "hint"}>
|
||||
{check && !check.ok
|
||||
? check.message
|
||||
: check?.ok
|
||||
? "Szabad, választhatod."
|
||||
: "Ne a valódi neved legyen, ha nem szeretnéd, hogy felismerjenek. 3–24 karakter: betűk, számok, szóköz, kötőjel."}
|
||||
</span>
|
||||
{member?.nickname_change_after && (
|
||||
<span className="hint">
|
||||
Új álnevet{" "}
|
||||
{new Date(member.nickname_change_after).toLocaleDateString("hu-HU", { month: "long", day: "numeric" })} után
|
||||
választhatsz (az ékezet és a kis- és nagybetű javítható addig is).
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<fieldset className="fnew-set">
|
||||
<legend>Avatar</legend>
|
||||
<div className="fprof-avatars">
|
||||
{AVATAR_COLOURS.flatMap((colour) =>
|
||||
AVATAR_GLYPHS.map((glyph) => {
|
||||
const value = `${glyph}-${colour}`;
|
||||
return (
|
||||
<label key={value} className="fprof-avatar" title={GLYPH_NAMES[glyph]}>
|
||||
<input
|
||||
type="radio"
|
||||
name="avatar"
|
||||
value={value}
|
||||
checked={avatar === value}
|
||||
onChange={() => setAvatar(value)}
|
||||
className="sr-only"
|
||||
/>
|
||||
<Avatar avatar={value} size={44} />
|
||||
<span className="sr-only">{GLYPH_NAMES[glyph]}</span>
|
||||
</label>
|
||||
);
|
||||
}),
|
||||
)}
|
||||
</div>
|
||||
{!avatar && <span className="hint">Ha nem választasz, az álneved alapján kapsz egyet.</span>}
|
||||
{member?.can_upload_avatar && (
|
||||
<div className="fprof-upload">
|
||||
{uploaded && <Avatar avatar={avatar} size={56} />}
|
||||
<label className="btn btn-sm fprof-upload-btn">
|
||||
{uploading ? "Feltöltés…" : uploaded ? "Másik kép" : "Saját kép feltöltése"}
|
||||
<input
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp"
|
||||
className="sr-only"
|
||||
disabled={uploading}
|
||||
onChange={async (e) => {
|
||||
const file = e.target.files?.[0];
|
||||
e.target.value = "";
|
||||
if (!file) return;
|
||||
setUploading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch("/api/v1/forum/me/avatar", {
|
||||
method: "PUT",
|
||||
body: file,
|
||||
headers: { "content-type": file.type || "application/octet-stream" },
|
||||
credentials: "same-origin",
|
||||
});
|
||||
const data = await res.json().catch(() => null);
|
||||
if (!res.ok) throw new Error(data?.error?.message ?? "A feltöltés nem sikerült.");
|
||||
setAvatar(data.avatar);
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : errorText(err));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<span className="hint">
|
||||
JPEG, PNG vagy WebP, legfeljebb 8 MB. Négyzetre vágjuk és kicsinyítjük, a kép adatait (hely, gép)
|
||||
eltávolítjuk. Ha egy kezdő avatart választasz, a saját kép törlődik.
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</fieldset>
|
||||
|
||||
<div className="field">
|
||||
<label htmlFor="fprof-bio">Bemutatkozás</label>
|
||||
<textarea
|
||||
id="fprof-bio"
|
||||
className="fc-text"
|
||||
rows={4}
|
||||
maxLength={500}
|
||||
value={bio}
|
||||
onChange={(e) => withEmoji(e, setBio)}
|
||||
placeholder="Pár mondat magadról, ha szeretnéd."
|
||||
/>
|
||||
<span className="hint">{bio.length}/500 · link nem tehető bele</span>
|
||||
</div>
|
||||
|
||||
<fieldset className="fnew-set">
|
||||
<legend>Mit mutatsz meg a képletedből?</legend>
|
||||
<div className="fnew-intents">
|
||||
{SHARE_LEVELS.map((level) => (
|
||||
<label key={level.value} className="fnew-intent">
|
||||
<input type="radio" name="share" checked={share === level.value} onChange={() => setShare(level.value)} />
|
||||
<span>
|
||||
<strong>{level.label}</strong>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<span className="hint">
|
||||
{me.chart === null
|
||||
? "Még nincs saját képleted, így most semmi nem látszana."
|
||||
: preview
|
||||
? `Így látszik a neved mellett: ${signsText(preview)}`
|
||||
: share === "none"
|
||||
? "Semmi nem látszik a képletedből."
|
||||
: "Ehhez a szinthez nincs adat a képletedben."}{" "}
|
||||
Fokokat soha nem mutatunk, mert azokból kiszámolható a születési időd.
|
||||
</span>
|
||||
</fieldset>
|
||||
|
||||
<label className="fprof-check">
|
||||
<input type="checkbox" checked={invisible} onChange={(e) => setInvisible(e.target.checked)} />
|
||||
<span>
|
||||
<strong>Láthatatlan mód</strong>
|
||||
<span className="hint">Nem jelenik meg mellettem a zöld pötty, és az sem, mikor jártam itt utoljára.</span>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
{member?.can_listen && (
|
||||
<label className="fprof-check">
|
||||
<input type="checkbox" checked={listener} onChange={(e) => setListener(e.target.checked)} />
|
||||
<span>
|
||||
<strong>Önkéntes kísérő vagyok</strong>
|
||||
<span className="hint">
|
||||
Szívesen válaszolok azoknak, akik meghallgatást kérnek. A nevem mellett megjelenik a „Kísérő” jelvény, és
|
||||
a fórum főoldalán látom, hány ilyen szál vár válaszra. E-mailt is kérhetsz róla lent.
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
|
||||
{me.can_supporter && (
|
||||
<label className="fprof-check">
|
||||
<input type="checkbox" checked={supporter} onChange={(e) => setSupporter(e.target.checked)} />
|
||||
<span>
|
||||
<strong>Támogató jelvény</strong>
|
||||
<span className="hint">
|
||||
Vásároltál csomagot: ha szeretnéd, a neved mellett megjelenik a „Támogató” jelvény. Rangot nem ad.
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
|
||||
<fieldset className="fnew-set">
|
||||
<legend>Értesítések e-mailben</legend>
|
||||
<div className="fprof-mail">
|
||||
<label htmlFor="fprof-mail-replies">Ha valaki válaszol nekem (a szálamban vagy a hozzászólásomra)</label>
|
||||
<select
|
||||
id="fprof-mail-replies"
|
||||
className="inp"
|
||||
value={email.replies}
|
||||
onChange={(e) => setEmail({ ...email, replies: e.target.value as EmailSettings["replies"] })}
|
||||
>
|
||||
<option value="daily">Napi összesítőben, este</option>
|
||||
<option value="instant">Azonnal (szálanként óránként legfeljebb egy levél)</option>
|
||||
<option value="off">Ne küldjetek</option>
|
||||
</select>
|
||||
<label htmlFor="fprof-mail-followed">Új hozzászólás a követett szálaimban</label>
|
||||
<select
|
||||
id="fprof-mail-followed"
|
||||
className="inp"
|
||||
value={email.followed}
|
||||
onChange={(e) => setEmail({ ...email, followed: e.target.value as EmailSettings["followed"] })}
|
||||
>
|
||||
<option value="off">Ne küldjetek</option>
|
||||
<option value="daily">Napi összesítőben, este</option>
|
||||
</select>
|
||||
<label htmlFor="fprof-mail-messages">Privát üzenet vagy beszélgetési kérés</label>
|
||||
<select
|
||||
id="fprof-mail-messages"
|
||||
className="inp"
|
||||
value={email.messages}
|
||||
onChange={(e) => setEmail({ ...email, messages: e.target.value as EmailSettings["messages"] })}
|
||||
>
|
||||
<option value="instant">Azonnal</option>
|
||||
<option value="off">Ne küldjetek</option>
|
||||
</select>
|
||||
<label htmlFor="fprof-mail-mentions">Ha valaki megemlít (@{nickname || "álnév"})</label>
|
||||
<select
|
||||
id="fprof-mail-mentions"
|
||||
className="inp"
|
||||
value={email.mentions}
|
||||
onChange={(e) => setEmail({ ...email, mentions: e.target.value as EmailSettings["mentions"] })}
|
||||
>
|
||||
<option value="instant">Azonnal</option>
|
||||
<option value="off">Ne küldjetek</option>
|
||||
</select>
|
||||
{listener && (
|
||||
<>
|
||||
<label htmlFor="fprof-mail-listener">
|
||||
Kísérőként: ha egy meghallgatást kérő szál két órája válasz nélkül vár
|
||||
</label>
|
||||
<select
|
||||
id="fprof-mail-listener"
|
||||
className="inp"
|
||||
value={email.listener}
|
||||
onChange={(e) => setEmail({ ...email, listener: e.target.value as EmailSettings["listener"] })}
|
||||
>
|
||||
<option value="off">Ne küldjetek</option>
|
||||
<option value="instant">Azonnal (hat óránként legfeljebb egy levél)</option>
|
||||
</select>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<label className="fprof-check fprof-check-plain">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={email.weekly}
|
||||
onChange={(e) => setEmail({ ...email, weekly: e.target.checked })}
|
||||
/>
|
||||
<span>
|
||||
<strong>Heti összefoglaló</strong>
|
||||
<span className="hint">Vasárnap este: a hét legélénkebb szálai, és ami még válaszra vár.</span>
|
||||
</span>
|
||||
</label>
|
||||
<span className="hint">
|
||||
Ha éppen itt vagy a fórumon, nem küldünk levelet: a válaszokat a Válaszok fülön, az üzeneteket az Üzenetek
|
||||
fülön látod. A privát üzenetek szövege nem kerül bele a levélbe.
|
||||
</span>
|
||||
</fieldset>
|
||||
|
||||
{member && <MutedList />}
|
||||
|
||||
{member && (
|
||||
<div className="fprof-rank">
|
||||
<span className="eyebrow">Rangod</span>
|
||||
<strong>{member.rank_name}</strong>
|
||||
<span className="hint">
|
||||
{member.points} pont · {member.post_count} hozzászólás
|
||||
{member.next_rank &&
|
||||
` · a ${member.next_rank.name} ranghoz ${member.next_rank.points} pont és ${member.next_rank.days} nap tagság kell`}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{saved && <p className="msg">Elmentve.</p>}
|
||||
<button type="submit" className="btn btn-primary" disabled={busy || !nickname.trim() || check?.ok === false}>
|
||||
{busy ? "Mentés…" : member ? "Mentés" : "Álnév mentése"}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import type { ForumMe } from "@/lib/forum";
|
||||
import { forumGet } from "@/lib/forumServer";
|
||||
|
||||
import { ProfileForm } from "./ProfileForm";
|
||||
|
||||
export const metadata = { title: "Fórumprofil", robots: { index: false } };
|
||||
|
||||
type Props = { searchParams: Promise<{ vissza?: string }> };
|
||||
|
||||
/** The member's forum profile: the nickname first, then avatar, bio, signs, visibility. */
|
||||
export default async function ForumSettingsPage({ searchParams }: Props) {
|
||||
const { vissza } = await searchParams;
|
||||
const res = await forumGet<ForumMe>("/v1/forum/me");
|
||||
if (!res.ok) redirect(`/belepes?vissza=${encodeURIComponent("/forum/beallitasok")}`);
|
||||
// Only back into the forum.
|
||||
const back = vissza?.startsWith("/forum") ? vissza : null;
|
||||
const me = res.data;
|
||||
return (
|
||||
<div className="fh">
|
||||
<h1 className="fpage-title">{me.member ? "Fórumprofil" : "Válassz álnevet"}</h1>
|
||||
{!me.member && (
|
||||
<p className="muted">
|
||||
A fórumon mindenki álnéven ír. A valódi neved, az e-mail-címed és a születési adataid soha nem jelennek meg
|
||||
itt.
|
||||
</p>
|
||||
)}
|
||||
<ProfileForm me={me} back={back} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,727 @@
|
||||
/* The forum: phones first (most members write from a phone), big touch
|
||||
targets and text for the 50+ readers. Light by default, dark on request
|
||||
(data-theme on .forum, from a cookie): both redefine the site's colour
|
||||
tokens for the forum's part of the page, so the shared .btn, .inp, .hint
|
||||
and links follow. */
|
||||
|
||||
/* --- themes --- */
|
||||
.forum {
|
||||
/* Colour emoji wherever the system has them (no monochrome symbol fonts). */
|
||||
--font-body: var(--font-inter), Inter, system-ui, "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", sans-serif;
|
||||
font-family: var(--font-body);
|
||||
--f-hover: rgba(255, 255, 255, 0.04);
|
||||
--f-tint: rgba(217, 180, 106, 0.1);
|
||||
--f-tint-strong: rgba(217, 180, 106, 0.14);
|
||||
--f-nav-bg: rgba(13, 18, 32, 0.97);
|
||||
--f-shadow: 0 16px 40px rgba(0, 0, 0, 0.45);
|
||||
--f-border-hover: #5a6790;
|
||||
--f-online: #9fd8b0;
|
||||
--f-blue-tint: rgba(127, 176, 224, 0.12);
|
||||
--f-orange-tint: rgba(240, 163, 94, 0.12);
|
||||
--f-red-tint: rgba(242, 160, 160, 0.08);
|
||||
--f-green-tint: rgba(159, 216, 176, 0.12);
|
||||
--r-with_you: #e58aa6;
|
||||
--r-thanks: #d9b46a;
|
||||
--r-me_too: #7fb0e0;
|
||||
--r-insight: #c3a6f0;
|
||||
color: var(--ink);
|
||||
}
|
||||
.forum[data-theme="light"] {
|
||||
--bg: #f6f3ed;
|
||||
--panel: #ffffff;
|
||||
--panel-2: #faf8f4;
|
||||
--line: #e6dfd2;
|
||||
--line-2: #d3c9b6;
|
||||
--ink: #1b2236;
|
||||
--ink-2: #3a4259;
|
||||
--muted: #5c6376;
|
||||
--gold: #8a6a24;
|
||||
--gold-hover: #6e5419;
|
||||
--gold-ink: #ffffff;
|
||||
--danger: #b03a3a;
|
||||
--ok: #2d7a4c;
|
||||
--harmonic: #2c66a0;
|
||||
--square: #9c520e;
|
||||
--f-hover: rgba(27, 34, 54, 0.04);
|
||||
--f-tint: rgba(167, 128, 47, 0.09);
|
||||
--f-tint-strong: rgba(167, 128, 47, 0.14);
|
||||
--f-nav-bg: rgba(255, 255, 255, 0.97);
|
||||
--f-shadow: 0 12px 32px rgba(27, 34, 54, 0.14);
|
||||
--f-border-hover: #a99d86;
|
||||
--f-online: #2fa865;
|
||||
--f-blue-tint: rgba(44, 102, 160, 0.09);
|
||||
--f-orange-tint: rgba(156, 82, 14, 0.09);
|
||||
--f-red-tint: rgba(176, 58, 58, 0.07);
|
||||
--f-green-tint: rgba(45, 122, 76, 0.1);
|
||||
--r-with_you: #b4466a;
|
||||
--r-thanks: #8a6a24;
|
||||
--r-me_too: #2c66a0;
|
||||
--r-insight: #6b4fa0;
|
||||
color-scheme: light;
|
||||
}
|
||||
/* The light forum takes the whole page between the (dark) header and footer
|
||||
(the body rule; the background here is for browsers without :has). */
|
||||
.forum[data-theme="light"] { background: var(--bg); min-height: 70vh; }
|
||||
body:has(.forum[data-theme="light"]) { background: #f6f3ed; }
|
||||
body:has(.forum[data-theme="light"]) .night-sky { display: none; }
|
||||
body:has(.forum[data-theme="light"]) .site-footer { background: #0d1220; }
|
||||
.forum[data-theme="light"] .inp:focus { background-color: var(--panel); box-shadow: 0 0 0 3px rgba(167, 128, 47, 0.22); }
|
||||
.forum[data-theme="light"] .inp::placeholder { color: #8b8f9c; }
|
||||
.forum[data-theme="light"] .btn:hover { border-color: var(--f-border-hover); background: var(--f-hover); }
|
||||
.forum[data-theme="light"] .moon-phase-icon .moon-dark { fill: #ebe5d8; stroke: #b99550; }
|
||||
.forum[data-theme="light"] .moon-phase-icon .moon-lit { fill: #d9b46a; }
|
||||
|
||||
/* --- frame --- */
|
||||
.forum-inner { max-width: 1180px; margin: 0 auto; padding: 8px 16px 104px; }
|
||||
.forum-main { display: flex; flex-direction: column; }
|
||||
.forum h1, .forum h2 { font-family: var(--font-display); font-weight: 600; color: var(--ink); }
|
||||
.forum-bar { display: flex; align-items: center; justify-content: space-between; gap: 12px; min-height: 52px; margin-bottom: 8px; }
|
||||
.forum-mark { font-family: var(--font-display); font-size: 26px; font-weight: 600; color: var(--ink); text-decoration: none; }
|
||||
.forum-mark:hover { color: var(--gold); }
|
||||
.forum-theme {
|
||||
display: inline-flex; align-items: center; gap: 8px; min-width: 44px; min-height: 44px; padding: 0 10px; justify-content: center;
|
||||
border: 1px solid var(--line-2); border-radius: 999px; background: var(--panel); color: var(--ink-2);
|
||||
font: 500 14px var(--font-body); cursor: pointer;
|
||||
}
|
||||
.forum-theme:hover { color: var(--gold); border-color: var(--f-border-hover); }
|
||||
.forum-theme svg { width: 20px; height: 20px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.forum-theme-label { display: none; }
|
||||
.forum-tools { display: flex; align-items: center; gap: 8px; }
|
||||
.forum-search { padding: 0; width: 44px; }
|
||||
|
||||
/* The forum's menu: a bar at the bottom on phones, tabs in the forum bar on wider screens. */
|
||||
.forum-nav {
|
||||
position: fixed; left: 0; right: 0; bottom: 0; z-index: 25;
|
||||
display: grid; grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
background: var(--f-nav-bg); border-top: 1px solid var(--line);
|
||||
padding-bottom: env(safe-area-inset-bottom);
|
||||
box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
.fn-item {
|
||||
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px;
|
||||
min-height: 62px; color: var(--ink-2); text-decoration: none; font-size: 12px;
|
||||
}
|
||||
.fn-item[aria-current="page"] { color: var(--gold); font-weight: 600; }
|
||||
.fn-item:hover { color: var(--gold); }
|
||||
.fn-icon-wrap { position: relative; display: inline-flex; }
|
||||
.fn-icon { width: 24px; height: 24px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.fn-badge {
|
||||
position: absolute; top: -6px; right: -11px; min-width: 18px; height: 18px; padding: 0 5px; box-sizing: border-box;
|
||||
border-radius: 999px; background: var(--gold); color: var(--gold-ink); font-size: 11px; font-weight: 600; line-height: 18px; text-align: center;
|
||||
}
|
||||
@media (min-width: 760px) {
|
||||
.forum-inner { padding: 20px 24px 64px; }
|
||||
.forum-bar {
|
||||
gap: 16px; margin-bottom: 24px; padding: 6px 6px 6px 18px;
|
||||
background: var(--panel); border: 1px solid var(--line); border-radius: 16px;
|
||||
}
|
||||
.forum-nav {
|
||||
position: static; flex: 1; display: flex; gap: 4px; padding: 0;
|
||||
background: none; border: 0; box-shadow: none;
|
||||
}
|
||||
.fn-item { flex-direction: row; gap: 8px; min-height: 44px; padding: 0 14px; border-radius: 10px; font-size: 15px; }
|
||||
.fn-item[aria-current="page"] { background: var(--f-tint); }
|
||||
.fn-icon { width: 20px; height: 20px; }
|
||||
.forum-theme { padding: 0 14px; }
|
||||
.forum-search { padding: 0; }
|
||||
.forum-theme-label { display: inline; }
|
||||
}
|
||||
|
||||
/* --- avatars and the author line --- */
|
||||
.av { position: relative; display: inline-flex; flex: none; --av-bg: #1c2540; --av-ink: #d9b46a; }
|
||||
.av svg { display: block; }
|
||||
.av-lila { --av-bg: #2a2342; }
|
||||
.av-tenger { --av-bg: #1d3038; }
|
||||
.av-borostyan { --av-bg: #33291c; }
|
||||
.av-rozsa { --av-bg: #3a2230; }
|
||||
.av-erdo { --av-bg: #1f3326; }
|
||||
/* Light theme: a pale tint and a darker glyph (a night circle read as a black blot). */
|
||||
.forum[data-theme="light"] .av-ejkek { --av-bg: #e4e8f3; --av-ink: #2f3d6b; }
|
||||
.forum[data-theme="light"] .av-lila { --av-bg: #ece6f5; --av-ink: #5b4691; }
|
||||
.forum[data-theme="light"] .av-tenger { --av-bg: #e0eff0; --av-ink: #2a6670; }
|
||||
.forum[data-theme="light"] .av-borostyan { --av-bg: #f5ead7; --av-ink: #8a6a24; }
|
||||
.forum[data-theme="light"] .av-rozsa { --av-bg: #f6e3ea; --av-ink: #9b3f5f; }
|
||||
.forum[data-theme="light"] .av-erdo { --av-bg: #e2efe4; --av-ink: #3d6b47; }
|
||||
.av-bg { fill: var(--av-bg); }
|
||||
.av-glyph { fill: none; stroke: var(--av-ink); stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.av-glyph .av-fill { fill: var(--av-ink); stroke: none; }
|
||||
.av-online {
|
||||
position: absolute; right: -1px; bottom: -1px; width: 28%; height: 28%; min-width: 9px; min-height: 9px;
|
||||
border-radius: 50%; background: var(--f-online); border: 2px solid var(--panel); box-sizing: border-box;
|
||||
}
|
||||
.fa-line { display: flex; align-items: center; gap: 10px; min-width: 0; }
|
||||
.fa-avatar { display: inline-flex; }
|
||||
.fa-meta { display: flex; flex-direction: column; gap: 1px; min-width: 0; }
|
||||
.fa-names { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; }
|
||||
.fa-name { font-size: 16px; font-weight: 600; color: var(--ink); text-decoration: none; }
|
||||
.fa-name:hover { color: var(--gold); }
|
||||
.fa-rank { font-size: 12px; color: var(--ink-2); border: 1px solid var(--line-2); border-radius: 6px; padding: 0 6px; }
|
||||
.fa-badge { font-size: 12px; border-radius: 6px; padding: 0 6px; }
|
||||
.fa-rank, .fa-badge { display: inline-flex; align-items: center; gap: 3px; line-height: 18px; white-space: nowrap; }
|
||||
.fa-icon {
|
||||
width: 12px; height: 12px; flex: none; fill: none; stroke: currentColor; stroke-width: 2;
|
||||
stroke-linecap: round; stroke-linejoin: round;
|
||||
}
|
||||
.fa-badge-new .fa-icon { display: none; }
|
||||
/* The higher ranks: a golden icon. */
|
||||
.fa-rank-fono .fa-icon, .fa-rank-csillagfono .fa-icon, .fa-rank-sorsfono .fa-icon { color: var(--gold); }
|
||||
.fa-badge-mod { color: var(--ok); background: var(--f-green-tint); }
|
||||
.fa-badge-starter { color: var(--gold); border: 1px solid var(--line-2); }
|
||||
.fa-badge-new { color: var(--gold-ink); background: var(--gold); font-weight: 600; }
|
||||
.fa-sub { font-size: 13px; color: var(--muted); }
|
||||
|
||||
/* --- cards, banners, sections --- */
|
||||
.fh { display: flex; flex-direction: column; gap: 22px; }
|
||||
.fh-card { background: var(--panel); border: 1px solid var(--line); border-radius: 16px; padding: 18px; }
|
||||
.forum[data-theme="light"] .fh-card { box-shadow: 0 1px 2px rgba(27, 34, 54, 0.04); }
|
||||
.fh-flush { padding: 0; overflow: hidden; }
|
||||
.fh-empty { color: var(--muted); }
|
||||
.fh-card-head { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; margin-bottom: 12px; }
|
||||
.fh-intro { display: flex; flex-direction: column; gap: 12px; align-items: flex-start; }
|
||||
.fh-intro h1 { font-size: 36px; }
|
||||
.fh-banner {
|
||||
display: flex; align-items: center; gap: 12px; justify-content: space-between;
|
||||
min-height: 52px; padding: 12px 14px; border-radius: 12px;
|
||||
background: var(--f-tint); border: 1px solid var(--line-2); color: var(--ink); text-decoration: none;
|
||||
}
|
||||
.fh-banner strong { color: var(--gold); font-weight: 600; }
|
||||
.fh-banner:hover { color: var(--ink); background: var(--f-tint-strong); }
|
||||
.fh-banner-warn { background: var(--f-red-tint); border-color: var(--danger); }
|
||||
.fh-section { display: flex; flex-direction: column; gap: 12px; }
|
||||
.fh-section-head { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }
|
||||
.fh-section-head h2 { font-size: 24px; }
|
||||
.fh-sky-body { display: flex; gap: 16px; align-items: flex-start; }
|
||||
.fh-moon .moon-phase-icon { width: 56px; height: 56px; }
|
||||
.fh-sky-text { display: flex; flex-direction: column; gap: 6px; min-width: 0; }
|
||||
.fh-sky-text h2 { font-size: 24px; line-height: 1.15; }
|
||||
.fh-sky-text p { color: var(--ink-2); font-size: 16px; }
|
||||
.fh-waiting-grid { display: grid; gap: 12px; }
|
||||
@media (min-width: 760px) { .fh-waiting-grid { grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); } }
|
||||
.fh-me { display: flex; flex-direction: column; gap: 14px; }
|
||||
.fh-me-head { display: flex; align-items: center; gap: 12px; }
|
||||
.fh-me-names { display: flex; flex-direction: column; gap: 4px; align-items: flex-start; }
|
||||
.fh-me-actions { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||
|
||||
/* Front page: one column on phones in reading order (the two columns'
|
||||
blocks interleave), main column and sidebar from 1024 px. */
|
||||
.fh-home .fh-col { display: contents; }
|
||||
.o-1 { order: 1; } .o-2 { order: 2; } .o-3 { order: 3; } .o-4 { order: 4; }
|
||||
.o-5 { order: 5; } .o-6 { order: 6; } .o-7 { order: 7; } .o-8 { order: 8; }
|
||||
@media (min-width: 1024px) {
|
||||
.fh-home { display: grid; grid-template-columns: minmax(0, 1fr) 340px; gap: 28px; align-items: start; }
|
||||
.fh-home .fh-col { display: flex; flex-direction: column; gap: 22px; }
|
||||
.fh-home .fh-col-side { position: sticky; top: 88px; }
|
||||
}
|
||||
|
||||
/* --- topics --- */
|
||||
.fh-topics { list-style: none; margin: 0; }
|
||||
.fh-topics li + li { border-top: 1px solid var(--line); }
|
||||
.fh-topic { display: flex; align-items: center; gap: 14px; padding: 14px 16px; min-height: 76px; color: var(--ink); text-decoration: none; }
|
||||
.fh-topic:hover { color: var(--ink); background: var(--f-hover); }
|
||||
.fh-topic-icon {
|
||||
flex: none; width: 44px; height: 44px; border-radius: 12px; background: var(--f-tint);
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
}
|
||||
.topic-icon { width: 24px; height: 24px; fill: none; stroke: var(--gold); stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.fh-topic-text { display: flex; flex-direction: column; gap: 2px; flex: 1; min-width: 0; }
|
||||
.fh-topic-name { display: flex; align-items: center; gap: 8px; font-size: 17px; font-weight: 600; }
|
||||
.fh-lock { width: 14px; height: 14px; fill: none; stroke: var(--muted); stroke-width: 2; stroke-linecap: round; }
|
||||
.fh-topic-desc { font-size: 14px; color: var(--muted); }
|
||||
.fh-topic-last { display: flex; align-items: center; gap: 6px; font-size: 13px; color: var(--muted); }
|
||||
.fh-topic-count { display: none; flex: none; font-size: 14px; color: var(--muted); text-align: right; min-width: 64px; }
|
||||
.fh-topic-count strong { color: var(--ink); font-weight: 600; }
|
||||
@media (min-width: 640px) { .fh-topic-count { display: block; } }
|
||||
|
||||
/* --- thread lists: a meta line on phones, columns on wider screens --- */
|
||||
.ft-list { list-style: none; margin: 0; padding: 0; }
|
||||
.ft-list li + li { border-top: 1px solid var(--line); }
|
||||
.ft-row { display: flex; align-items: center; gap: 12px; padding: 14px 16px; min-height: 64px; color: var(--ink); text-decoration: none; }
|
||||
.ft-row:hover { color: var(--ink); background: var(--f-hover); }
|
||||
.ft-main { display: flex; flex-direction: column; gap: 4px; flex: 1; min-width: 0; }
|
||||
.ft-title { font-size: 17px; font-weight: 600; line-height: 1.35; }
|
||||
.ft-row:hover .ft-title { color: var(--gold); }
|
||||
.ft-excerpt { font-size: 14px; color: var(--ink-2); display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
|
||||
.ft-meta { display: flex; align-items: center; gap: 8px; font-size: 14px; color: var(--muted); }
|
||||
.ft-col { display: none; }
|
||||
.ft-new {
|
||||
flex: none; font-size: 13px; font-weight: 600; color: var(--gold-ink); background: var(--gold);
|
||||
border-radius: 999px; padding: 2px 9px; white-space: nowrap;
|
||||
}
|
||||
.ft-read { flex: none; font-size: 13px; color: var(--muted); }
|
||||
@media (min-width: 760px) {
|
||||
.ft-row { display: grid; grid-template-columns: minmax(0, 1fr) 110px 100px 72px; gap: 16px; padding: 14px 20px; }
|
||||
.ft-m-narrow { display: none; }
|
||||
.ft-col { display: flex; flex-direction: column; align-items: flex-end; font-size: 14px; color: var(--muted); }
|
||||
.ft-col strong { color: var(--ink); font-weight: 600; font-size: 16px; }
|
||||
.ft-col-replies { flex-direction: row; gap: 4px; align-items: baseline; justify-content: flex-end; flex-wrap: wrap; }
|
||||
.ft-col-replies .hint { flex-basis: 100%; text-align: right; }
|
||||
.ft-new, .ft-read { justify-self: end; }
|
||||
}
|
||||
.ft-pin {
|
||||
display: inline-block; margin-right: 8px; vertical-align: 2px; font-size: 12px; font-weight: 500;
|
||||
color: var(--ink-2); border: 1px solid var(--line-2); border-radius: 6px; padding: 0 6px;
|
||||
}
|
||||
.ft-intent { align-self: flex-start; font-size: 13px; font-weight: 500; border-radius: 999px; padding: 3px 10px; }
|
||||
.ft-intent-listen { color: var(--harmonic); background: var(--f-blue-tint); }
|
||||
.ft-intent-advice { color: var(--square); background: var(--f-orange-tint); }
|
||||
.ft-waiting {
|
||||
display: flex; flex-direction: column; gap: 10px; padding: 16px; border-radius: 14px;
|
||||
background: var(--panel); border: 1px solid var(--line);
|
||||
}
|
||||
.ft-waiting-title { font-size: 18px; font-weight: 600; line-height: 1.35; color: var(--ink); text-decoration: none; }
|
||||
.ft-waiting-title:hover { color: var(--gold); }
|
||||
.ft-answer { align-self: flex-start; min-height: 44px; border-color: var(--gold); color: var(--gold); margin-top: auto; }
|
||||
|
||||
/* --- topic page and the other headings --- */
|
||||
.forum-crumbs { display: flex; gap: 8px; align-items: center; font-size: 14px; color: var(--muted); }
|
||||
.forum-crumbs a { color: var(--ink-2); text-decoration: none; min-height: 32px; display: inline-flex; align-items: center; }
|
||||
.forum-crumbs a:hover { color: var(--gold); }
|
||||
.ftopic-head { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: flex-start; gap: 16px; }
|
||||
.ftopic-head h1, .fpage-title { font-size: 34px; line-height: 1.1; }
|
||||
.ftopic-head > div { display: flex; flex-direction: column; gap: 6px; max-width: 620px; }
|
||||
.forum-pager { display: flex; justify-content: space-between; align-items: center; min-height: 44px; }
|
||||
|
||||
/* --- thread view --- */
|
||||
.ftv { display: flex; flex-direction: column; gap: 12px; width: 100%; max-width: 980px; margin: 0 auto; }
|
||||
.ftv-toolbar { display: flex; justify-content: flex-end; gap: 8px; flex-wrap: wrap; }
|
||||
.ftv-toolbar:empty { display: none; }
|
||||
.ftv-mod { position: relative; }
|
||||
.ftv-mod summary { list-style: none; cursor: pointer; }
|
||||
.ftv-mod summary::-webkit-details-marker { display: none; }
|
||||
.ftv-mod-menu {
|
||||
position: absolute; right: 0; top: calc(100% + 6px); z-index: 10; min-width: 200px; padding: 6px;
|
||||
display: flex; flex-direction: column; background: var(--panel); border: 1px solid var(--line-2); border-radius: 12px;
|
||||
box-shadow: var(--f-shadow);
|
||||
}
|
||||
.ftv-mod-menu button {
|
||||
min-height: 44px; padding: 0 12px; border: 0; border-radius: 8px; background: none; color: var(--ink);
|
||||
font: inherit; font-size: 15px; text-align: left; cursor: pointer;
|
||||
}
|
||||
.ftv-mod-menu button:hover { background: var(--f-hover); color: var(--gold); }
|
||||
.ftv-mod-menu button.danger { color: var(--danger); }
|
||||
.ftv-intent {
|
||||
display: flex; flex-direction: column; gap: 4px; padding: 12px 14px; border-radius: 12px;
|
||||
background: var(--f-blue-tint); font-size: 14px; line-height: 1.45; color: var(--ink-2);
|
||||
}
|
||||
.ftv-intent strong { color: var(--harmonic); font-weight: 600; }
|
||||
.ftv-intent-advice { background: var(--f-orange-tint); }
|
||||
.ftv-intent-advice strong { color: var(--square); }
|
||||
.ftv-title { font-size: 30px; line-height: 1.12; }
|
||||
.ftv-intent-line { display: flex; align-items: center; flex-wrap: wrap; gap: 4px 8px; margin-top: -4px; font-size: 14px; color: var(--muted); }
|
||||
.ftv-intent-line .ft-intent { align-self: center; padding: 1px 10px; font-weight: 600; }
|
||||
.ftv-count { display: flex; justify-content: space-between; align-items: baseline; padding-top: 6px; }
|
||||
.ftv .ftv-count h2 { font-family: var(--font-body); font-size: 15px; color: var(--ink-2); }
|
||||
.ftv-branch { display: flex; flex-direction: column; }
|
||||
.ftv-children { margin-left: 17px; padding-left: 14px; border-left: 2px solid var(--line); display: flex; flex-direction: column; }
|
||||
.ftv-marker { display: flex; align-items: center; gap: 10px; margin: 8px 0 0; color: var(--gold); font-size: 13px; font-weight: 600; }
|
||||
.ftv-marker::before, .ftv-marker::after { content: ""; flex: 1; height: 1px; background: var(--gold); opacity: 0.5; }
|
||||
.ftv-incoming {
|
||||
position: sticky; bottom: 84px; align-self: center; z-index: 5;
|
||||
display: inline-flex; align-items: center; min-height: 44px; padding: 0 18px; border: 0; border-radius: 999px;
|
||||
background: var(--gold); color: var(--gold-ink); font: 600 15px var(--font-body); cursor: pointer;
|
||||
box-shadow: var(--f-shadow);
|
||||
}
|
||||
.ftv-compose { display: flex; flex-direction: column; gap: 8px; padding-top: 14px; border-top: 1px solid var(--line); scroll-margin-top: 90px; }
|
||||
.ftv-hint { font-size: 14px; color: var(--harmonic); }
|
||||
.ftv-replyto { display: flex; align-items: center; gap: 6px; font-size: 14px; color: var(--ink-2); }
|
||||
.ftv-gate { padding: 16px; border-radius: 12px; background: var(--panel); border: 1px solid var(--line); }
|
||||
|
||||
/* --- posts: a one-line head (avatar, name, rank, signs, time), the text, a
|
||||
small action row; on wide screens the text lines up under the name --- */
|
||||
.fp {
|
||||
display: grid; grid-template-columns: auto minmax(0, 1fr);
|
||||
grid-template-areas: "av head" "body body" "actions actions" "report report";
|
||||
column-gap: 10px; row-gap: 6px; padding: 12px 0; border-bottom: 1px solid var(--line); scroll-margin-top: 90px;
|
||||
}
|
||||
.fp-av { grid-area: av; display: inline-flex; align-self: center; }
|
||||
.fp-av a { display: inline-flex; }
|
||||
.fp-head { grid-area: head; display: flex; align-items: center; gap: 8px; min-width: 0; }
|
||||
.fp-names { display: flex; align-items: baseline; flex-wrap: wrap; gap: 4px 6px; flex: 1; min-width: 0; }
|
||||
.fp-names .fa-name { font-size: 15px; }
|
||||
.fp-signs { font-size: 13px; color: var(--muted); letter-spacing: 0.5px; }
|
||||
.fp-time { flex: none; font-size: 13px; color: var(--muted); }
|
||||
.fp-content { grid-area: body; min-width: 0; display: flex; flex-direction: column; gap: 8px; }
|
||||
.fp-actions { grid-area: actions; display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
|
||||
.fp-report { grid-area: report; }
|
||||
/* The question (the opening post) stands apart: a card; the replies sit on the page. */
|
||||
.fp.fp-opening {
|
||||
margin: 6px 0 10px; padding: 16px 18px 14px; border: 1px solid var(--line); border-radius: 16px;
|
||||
background: var(--panel);
|
||||
}
|
||||
.forum[data-theme="light"] .fp.fp-opening { box-shadow: 0 1px 3px rgba(27, 34, 54, 0.06); }
|
||||
.fp-opening .fp-body { font-size: 17px; }
|
||||
.fp-opening .fp-names .fa-name { font-size: 16px; }
|
||||
.ftv-children .fp:last-child { border-bottom: 0; }
|
||||
.fp-nested { padding: 8px 0; row-gap: 4px; }
|
||||
.fp-nested .fp-body { font-size: 15px; }
|
||||
.fp-body { font-size: 16px; line-height: 1.55; overflow-wrap: anywhere; color: var(--ink); }
|
||||
.fp-body p + p { margin-top: 8px; }
|
||||
.fp.fp-removed { display: flex; flex-direction: column; }
|
||||
.fp-removed {
|
||||
gap: 4px; margin: 10px 0; padding: 12px 14px; border: 1px dashed var(--line-2);
|
||||
border-radius: 12px; color: var(--ink-2); font-size: 15px;
|
||||
}
|
||||
.fp-mod-note { font-size: 13px; color: var(--danger); }
|
||||
.fp-collapsed {
|
||||
align-self: flex-start; min-height: 40px; padding: 0; border: 0; background: none; color: var(--muted);
|
||||
font: inherit; font-size: 15px; text-decoration: underline; cursor: pointer;
|
||||
}
|
||||
.fp-helped { display: inline-flex; align-items: center; gap: 4px; margin-right: 2px; font-size: 12px; font-weight: 500; color: var(--ok); }
|
||||
.fp-helped svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2.4; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.fp-spacer { flex: 1; }
|
||||
.fp-reply {
|
||||
display: inline-flex; align-items: center; gap: 5px; min-height: 32px; padding: 0 8px; border: 0; border-radius: 8px;
|
||||
background: none; color: var(--ink-2); font: 500 13px var(--font-body); cursor: pointer;
|
||||
}
|
||||
.fp-reply:hover { color: var(--gold); background: var(--f-hover); }
|
||||
.fp-reply svg { width: 15px; height: 15px; fill: none; stroke: currentColor; stroke-width: 1.9; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.fp-more {
|
||||
display: inline-flex; align-items: center; justify-content: center; width: 32px; height: 32px; border: 0; border-radius: 8px;
|
||||
background: none; color: var(--muted); cursor: pointer;
|
||||
}
|
||||
.fp-more:hover, .fp-more[aria-expanded="true"] { color: var(--ink); background: var(--f-hover); }
|
||||
.fp-more svg { width: 18px; height: 18px; fill: currentColor; }
|
||||
@media (min-width: 760px) {
|
||||
.fp { grid-template-columns: 44px minmax(0, 1fr); grid-template-areas: "av head" ". body" ". actions" ". report"; column-gap: 14px; }
|
||||
.fp-av { justify-content: center; }
|
||||
.fp-nested { grid-template-columns: 30px minmax(0, 1fr); column-gap: 10px; }
|
||||
.ftv-incoming { bottom: 20px; }
|
||||
}
|
||||
|
||||
/* --- reactions: the forum's own marks, an icon and a count --- */
|
||||
.ri { fill: none; stroke-width: 1.9; stroke-linecap: round; stroke-linejoin: round; flex: none; }
|
||||
.ri-with_you { stroke: var(--r-with_you); }
|
||||
.ri-thanks { stroke: var(--r-thanks); }
|
||||
.ri-me_too { stroke: var(--r-me_too); }
|
||||
.ri-insight { stroke: var(--r-insight); }
|
||||
.ri-filled.ri-with_you { fill: color-mix(in srgb, var(--r-with_you) 28%, transparent); }
|
||||
.ri-filled.ri-thanks { fill: color-mix(in srgb, var(--r-thanks) 28%, transparent); }
|
||||
.ri-filled.ri-me_too { fill: color-mix(in srgb, var(--r-me_too) 24%, transparent); }
|
||||
.ri-filled.ri-insight { fill: color-mix(in srgb, var(--r-insight) 28%, transparent); }
|
||||
.ri-filled .ri-line { fill: none; }
|
||||
.fr-row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
|
||||
.fr-chip {
|
||||
display: inline-flex; align-items: center; gap: 5px; min-height: 32px; min-width: 32px; padding: 0 10px; box-sizing: border-box;
|
||||
border-radius: 999px; border: 1px solid var(--line); background: var(--panel); color: var(--ink);
|
||||
font: 500 13px var(--font-body); cursor: pointer; justify-content: center;
|
||||
}
|
||||
.fp-nested .fr-chip { min-height: 30px; }
|
||||
.fr-chip:disabled { cursor: default; }
|
||||
.fr-chip:hover:not(:disabled) { border-color: var(--line-2); }
|
||||
.fr-chip[aria-pressed="true"]:has(.ri-with_you) { border-color: var(--r-with_you); background: color-mix(in srgb, var(--r-with_you) 9%, var(--panel)); }
|
||||
.fr-chip[aria-pressed="true"]:has(.ri-thanks) { border-color: var(--r-thanks); background: color-mix(in srgb, var(--r-thanks) 9%, var(--panel)); }
|
||||
.fr-chip[aria-pressed="true"]:has(.ri-me_too) { border-color: var(--r-me_too); background: color-mix(in srgb, var(--r-me_too) 9%, var(--panel)); }
|
||||
.fr-chip[aria-pressed="true"]:has(.ri-insight) { border-color: var(--r-insight); background: color-mix(in srgb, var(--r-insight) 9%, var(--panel)); }
|
||||
.fr-add { padding: 0; border-style: dashed; border-color: var(--line-2); background: none; color: var(--muted); }
|
||||
.fr-add svg, .fr-down svg { width: 15px; height: 15px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.fr-down { padding: 0; border-color: transparent; background: none; color: var(--muted); }
|
||||
.fr-down svg { width: 18px; height: 18px; }
|
||||
.fr-down[aria-pressed="true"] { background: var(--f-hover); color: var(--ink); }
|
||||
|
||||
/* --- small menus (the + of reactions, the ⋯ of a post) --- */
|
||||
.fpop-wrap { position: relative; display: inline-flex; }
|
||||
.fpop {
|
||||
position: absolute; left: 0; top: calc(100% + 6px); z-index: 20; min-width: 210px; padding: 6px;
|
||||
display: flex; flex-direction: column; background: var(--panel); border: 1px solid var(--line-2); border-radius: 12px;
|
||||
box-shadow: var(--f-shadow);
|
||||
}
|
||||
.fpop-right { left: auto; right: 0; }
|
||||
.fpop-item {
|
||||
display: flex; align-items: center; gap: 10px; min-height: 40px; padding: 0 12px; border: 0; border-radius: 8px;
|
||||
background: none; color: var(--ink); font: 400 15px var(--font-body); text-align: left; cursor: pointer; white-space: nowrap;
|
||||
}
|
||||
.fpop-item:hover, .fpop-item[aria-pressed="true"] { background: var(--f-hover); }
|
||||
.fpop-danger { color: var(--danger); }
|
||||
|
||||
/* --- composer --- */
|
||||
.fc { display: flex; flex-direction: column; gap: 8px; }
|
||||
.fc-text {
|
||||
width: 100%; min-height: 96px; box-sizing: border-box; padding: 12px 14px; border-radius: 12px;
|
||||
border: 1px solid var(--line-2); background: var(--panel-2); color: var(--ink); font: 400 16px/1.45 var(--font-body);
|
||||
resize: vertical; caret-color: var(--gold);
|
||||
}
|
||||
.fc-text::placeholder { color: var(--muted); }
|
||||
.fc-text:focus { outline: none; border-color: var(--gold); box-shadow: 0 0 0 3px var(--f-tint-strong); background: var(--panel); }
|
||||
.fc-actions { display: flex; align-items: center; gap: 8px; }
|
||||
.fc-spacer { flex: 1; }
|
||||
.fc-icon-btn {
|
||||
width: 44px; height: 44px; flex: none; display: inline-flex; align-items: center; justify-content: center;
|
||||
border: 0; border-radius: 10px; background: none; color: var(--ink-2); cursor: pointer;
|
||||
}
|
||||
.fc-icon-btn:hover, .fc-icon-btn[aria-expanded="true"] { color: var(--gold); background: var(--f-tint); }
|
||||
.fc-icon-btn svg { width: 24px; height: 24px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; }
|
||||
/* --- new thread and profile forms --- */
|
||||
.fnew, .fprof { display: flex; flex-direction: column; gap: 22px; width: 100%; max-width: 760px; }
|
||||
.fnew-set { border: 0; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 10px; min-width: 0; }
|
||||
.fnew-set legend { font-size: 14px; font-weight: 500; margin-bottom: 8px; padding: 0; }
|
||||
.fnew-topics, .fnew-intents { display: grid; gap: 8px; }
|
||||
@media (min-width: 640px) { .fnew-topics { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
.fnew-topic, .fnew-intent, .fprof-check {
|
||||
display: flex; align-items: flex-start; gap: 10px; padding: 12px 14px; border: 1px solid var(--line-2);
|
||||
border-radius: 12px; cursor: pointer; background: var(--panel);
|
||||
}
|
||||
.fnew-topic:has(input:checked), .fnew-intent:has(input:checked) { border-color: var(--gold); background: var(--f-tint); }
|
||||
.fnew-topic > span, .fnew-intent > span, .fprof-check > span { display: flex; flex-direction: column; gap: 2px; }
|
||||
.fnew-topic input, .fnew-intent input, .fprof-check input { margin-top: 4px; accent-color: var(--gold); width: 18px; height: 18px; flex: none; }
|
||||
.fprof-avatars { display: grid; grid-template-columns: repeat(auto-fill, minmax(54px, 1fr)); gap: 6px; }
|
||||
.fprof-avatar {
|
||||
display: inline-flex; align-items: center; justify-content: center; padding: 3px; border-radius: 50%;
|
||||
border: 2px solid transparent; cursor: pointer; justify-self: center;
|
||||
}
|
||||
.fprof-avatar:has(input:checked) { border-color: var(--gold); }
|
||||
.fprof-avatar:has(input:focus-visible) { outline: 2px solid var(--gold); outline-offset: 2px; }
|
||||
.fprof-rank { display: flex; flex-direction: column; gap: 4px; padding: 14px 16px; border-radius: 12px; background: var(--panel); border: 1px solid var(--line); }
|
||||
|
||||
/* --- member page (two columns on wide screens) and moderation --- */
|
||||
.fmember { display: flex; flex-direction: column; gap: 12px; align-items: flex-start; }
|
||||
.fmember-head { display: flex; align-items: center; gap: 16px; }
|
||||
.fmember-names { display: flex; flex-direction: column; gap: 4px; }
|
||||
.fmember-names h1 { font-size: 30px; line-height: 1.1; }
|
||||
.fmember-badges { display: flex; gap: 6px; flex-wrap: wrap; }
|
||||
.fmember-signs { color: var(--ink-2); }
|
||||
@media (min-width: 900px) {
|
||||
.fh-member { display: grid; grid-template-columns: 340px minmax(0, 1fr); gap: 28px; align-items: start; }
|
||||
.fh-member .fmember { position: sticky; top: 88px; }
|
||||
}
|
||||
.fban { align-self: stretch; }
|
||||
.fban summary { list-style: none; cursor: pointer; display: inline-flex; }
|
||||
.fban summary::-webkit-details-marker { display: none; }
|
||||
.fban-body { display: flex; flex-direction: column; gap: 12px; margin-top: 12px; padding: 14px; border: 1px solid var(--line-2); border-radius: 12px; }
|
||||
.fmodlog { list-style: none; margin: 0; }
|
||||
.fmodlog li { display: flex; flex-direction: column; gap: 2px; padding: 12px 16px; }
|
||||
.fmodlog li + li { border-top: 1px solid var(--line); }
|
||||
|
||||
/* --- reports --- */
|
||||
.frep { flex-basis: 100%; display: flex; flex-direction: column; gap: 10px; margin-top: 6px; padding: 14px; border: 1px solid var(--line-2); border-radius: 12px; background: var(--panel); }
|
||||
.frep-kind { display: flex; align-items: center; gap: 10px; min-height: 40px; font-size: 15px; cursor: pointer; }
|
||||
.frep-kind input { accent-color: var(--gold); width: 18px; height: 18px; flex: none; }
|
||||
.frep-crisis { padding: 10px 12px; border-radius: 10px; background: var(--f-blue-tint); color: var(--ink); font-size: 15px; line-height: 1.45; }
|
||||
.frep-crisis strong { color: var(--harmonic); }
|
||||
.forum-modchip {
|
||||
display: inline-flex; align-items: center; min-height: 36px; padding: 0 12px; border-radius: 999px;
|
||||
background: var(--f-red-tint); border: 1px solid var(--danger); color: var(--danger); font-size: 14px; font-weight: 600;
|
||||
text-decoration: none; white-space: nowrap;
|
||||
}
|
||||
.forum-modchip:hover { color: var(--danger); background: var(--f-tint); }
|
||||
@media (max-width: 759px) { .forum-bar { flex-wrap: wrap; } .forum-modchip { order: 3; } }
|
||||
|
||||
/* --- moderation page --- */
|
||||
.fmod-tabs { display: flex; gap: 4px; padding: 4px; border-radius: 12px; background: var(--panel); border: 1px solid var(--line); align-self: flex-start; }
|
||||
.fmod-tabs a { min-height: 40px; display: inline-flex; align-items: center; padding: 0 16px; border-radius: 9px; color: var(--ink-2); text-decoration: none; font-weight: 500; }
|
||||
.fmod-tabs a[aria-current="page"] { background: var(--f-tint-strong); color: var(--gold); }
|
||||
.fmod-report { display: flex; flex-direction: column; gap: 10px; }
|
||||
.fmod-crisis { border-color: var(--harmonic); box-shadow: 0 0 0 1px var(--harmonic); }
|
||||
.fmod-report-head { display: flex; justify-content: space-between; align-items: baseline; gap: 10px; flex-wrap: wrap; }
|
||||
.fmod-note { color: var(--ink-2); font-style: italic; }
|
||||
.fmod-target { display: flex; flex-direction: column; gap: 6px; padding: 12px 14px; border-radius: 10px; background: var(--panel-2); border: 1px solid var(--line); }
|
||||
.fmod-target .fp-body { font-size: 15px; }
|
||||
.fmod-chat { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; font-size: 15px; }
|
||||
.fmod-chat-reported { padding: 4px 8px; border-radius: 6px; background: var(--f-red-tint); }
|
||||
|
||||
/* --- private messages --- */
|
||||
.fmsg-h { font-family: var(--font-body) !important; font-size: 16px; font-weight: 600; color: var(--ink-2); }
|
||||
.fmsg-request { display: flex; flex-direction: column; gap: 12px; }
|
||||
.fmsg-intro { font-style: italic; color: var(--ink-2); }
|
||||
.fmsg-actions { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||
.ft-row.fmsg-row { display: flex; }
|
||||
.fmsg-when { display: flex; flex-direction: column; align-items: flex-end; gap: 4px; font-size: 13px; color: var(--muted); flex: none; }
|
||||
.freq { display: flex; flex-direction: column; gap: 8px; align-self: stretch; }
|
||||
.freq label { font-size: 14px; font-weight: 500; }
|
||||
.fchat { display: flex; flex-direction: column; gap: 12px; width: 100%; max-width: 820px; margin: 0 auto; }
|
||||
.fchat-head { display: flex; align-items: center; gap: 12px; padding-bottom: 12px; border-bottom: 1px solid var(--line); }
|
||||
.fchat-who { display: flex; flex-direction: column; gap: 4px; align-items: flex-start; flex: 1; min-width: 0; }
|
||||
.fchat-intro { font-size: 15px; color: var(--ink-2); font-style: italic; }
|
||||
.fchat-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
|
||||
.fchat-msg { display: flex; flex-direction: column; align-items: flex-start; gap: 2px; max-width: 86%; }
|
||||
.fchat-mine { align-self: flex-end; align-items: flex-end; }
|
||||
.fchat-bubble { padding: 10px 14px; border-radius: 16px 16px 16px 4px; background: var(--panel); border: 1px solid var(--line); }
|
||||
.fchat-mine .fchat-bubble { border-radius: 16px 16px 4px 16px; background: var(--f-tint-strong); border-color: transparent; }
|
||||
.fchat-bubble .fp-body { font-size: 16px; line-height: 1.5; }
|
||||
.fchat-meta { display: flex; align-items: center; gap: 6px; font-size: 12px; color: var(--muted); }
|
||||
.fchat-report { min-height: 32px; padding: 0 6px; border: 0; background: none; color: var(--muted); font: 400 12px var(--font-body); cursor: pointer; }
|
||||
.fchat-report:hover { color: var(--danger); }
|
||||
.fchat-msg .frep { width: min(420px, 86vw); }
|
||||
.fchat-compose { display: flex; flex-direction: column; gap: 6px; padding-top: 12px; border-top: 1px solid var(--line); }
|
||||
@media (min-width: 760px) { .forum-nav .fn-item { padding: 0 12px; } }
|
||||
|
||||
/* --- e-mail settings --- */
|
||||
.fprof-mail { display: grid; gap: 6px; }
|
||||
.fprof-mail label { font-size: 14px; font-weight: 500; margin-top: 8px; }
|
||||
.fprof-mail label:first-child { margin-top: 0; }
|
||||
|
||||
/* --- "… gépel" --- */
|
||||
.ftyping { min-height: 22px; display: flex; align-items: center; gap: 8px; font-size: 14px; color: var(--muted); margin: 0; }
|
||||
.ftyping-dots { display: inline-flex; gap: 3px; }
|
||||
.ftyping-dots span { width: 5px; height: 5px; border-radius: 50%; background: var(--muted); animation: ftyping 1.2s infinite ease-in-out; }
|
||||
.ftyping-dots span:nth-child(2) { animation-delay: 0.15s; }
|
||||
.ftyping-dots span:nth-child(3) { animation-delay: 0.3s; }
|
||||
@keyframes ftyping { 0%, 60%, 100% { opacity: 0.25; transform: translateY(0); } 30% { opacity: 1; transform: translateY(-3px); } }
|
||||
@media (prefers-reduced-motion: reduce) { .ftyping-dots span { animation: none; opacity: 0.6; } }
|
||||
.fp-link { min-height: 32px; padding: 0 8px; border: 0; background: none; color: var(--gold); font: 500 15px var(--font-body); cursor: pointer; }
|
||||
.fp-link:hover { color: var(--gold-hover); }
|
||||
|
||||
/* --- whom a reply answers, mentions, badges --- */
|
||||
.fp-replyto { display: inline-flex; align-items: center; gap: 3px; font-size: 13px; color: var(--muted); }
|
||||
.fp-replyto svg { width: 13px; height: 13px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.fp-mention { color: var(--gold); font-weight: 500; text-decoration: none; background: var(--f-tint); border-radius: 4px; padding: 0 2px; }
|
||||
.fp-mention:hover { color: var(--gold-hover); }
|
||||
.fa-badge-listener { color: var(--harmonic); background: var(--f-blue-tint); }
|
||||
.fa-badge-supporter { color: var(--gold); background: var(--f-tint); }
|
||||
.fa-badge-founder { color: var(--ok); border: 1px solid var(--line-2); }
|
||||
|
||||
/* --- own pictures and the site's mark --- */
|
||||
.av-picture img { display: block; width: 100%; height: 100%; border-radius: 50%; object-fit: cover; }
|
||||
.av-site { --av-bg: #1c2540; }
|
||||
.av-site-mark { stroke: #d9b46a; }
|
||||
.forum[data-theme="light"] .av-site { --av-bg: #f5ead7; }
|
||||
.forum[data-theme="light"] .av-site-mark { stroke: #8a6a24; }
|
||||
|
||||
/* --- "@" suggestions while typing --- */
|
||||
.fc-suggest {
|
||||
display: flex; flex-direction: column; align-self: flex-start; min-width: 220px; max-width: 320px; padding: 4px;
|
||||
background: var(--panel); border: 1px solid var(--line-2); border-radius: 12px; box-shadow: var(--f-shadow);
|
||||
}
|
||||
.fc-suggest-item {
|
||||
display: flex; align-items: center; gap: 8px; min-height: 40px; padding: 0 10px; border: 0; border-radius: 8px;
|
||||
background: none; color: var(--ink); font: 400 15px var(--font-body); text-align: left; cursor: pointer;
|
||||
}
|
||||
.fc-suggest-item:hover, .fc-suggest-item:focus-visible { background: var(--f-hover); }
|
||||
|
||||
/* --- who is here, restricted topics --- */
|
||||
.fh-online { display: flex; flex-direction: column; gap: 10px; }
|
||||
.forum .fh-online-title { font-family: var(--font-body); font-size: 15px; font-weight: 600; color: var(--ink-2); }
|
||||
.fh-online-list { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 8px 12px; }
|
||||
.fh-online-item { display: inline-flex; align-items: center; gap: 6px; font-size: 14px; color: var(--ink); text-decoration: none; }
|
||||
a.fh-online-item:hover { color: var(--gold); }
|
||||
.fh-topic-closed { flex-wrap: wrap; }
|
||||
.fjoin { flex-basis: 100%; display: flex; flex-direction: column; gap: 8px; }
|
||||
|
||||
/* --- profile form extras, the topics tab --- */
|
||||
.fprof-upload { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-top: 6px; }
|
||||
.fprof-upload-btn { cursor: pointer; }
|
||||
.fprof-check-plain { border: 0; padding: 6px 0 0; background: none; }
|
||||
.fmodlog li.ftop-member { flex-direction: row; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
|
||||
.ftop-vis { width: auto; min-height: 36px; }
|
||||
|
||||
/* --- members-only and restricted topics: said plainly, also to members --- */
|
||||
.ftopic-private { display: flex; align-items: flex-start; gap: 8px; font-size: 14px; color: var(--ink-2); }
|
||||
.ftopic-private svg, .ftv-private svg { width: 15px; height: 15px; flex: none; margin-top: 2px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; }
|
||||
.ftv-private { display: inline-flex; align-items: center; gap: 4px; margin-left: 4px; font-size: 13px; color: var(--muted); }
|
||||
.ftv-private svg { margin-top: 0; width: 13px; height: 13px; }
|
||||
|
||||
/* --- "Válaszok": answers to the member --- */
|
||||
.frep-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
|
||||
.fanswers { list-style: none; margin: 0; padding: 0; }
|
||||
.fanswers li + li { border-top: 1px solid var(--line); }
|
||||
.fanswer {
|
||||
display: grid; grid-template-columns: 36px minmax(0, 1fr) auto; gap: 12px; align-items: start;
|
||||
padding: 14px 16px; color: var(--ink); text-decoration: none;
|
||||
}
|
||||
.fanswer:hover { background: var(--f-hover); }
|
||||
.fanswer-new { background: var(--f-tint); }
|
||||
.fanswer-text { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
|
||||
.fanswer-who { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; font-size: 15px; }
|
||||
.fanswer-thread { font-size: 14px; color: var(--ink-2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.fanswer-excerpt {
|
||||
font-size: 14px; color: var(--muted); overflow: hidden;
|
||||
display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical;
|
||||
}
|
||||
.fanswer-time { font-size: 12px; color: var(--muted); white-space: nowrap; }
|
||||
|
||||
/* The reply box at the bottom of a branch, where the answers to that post go. */
|
||||
.ftv-inline {
|
||||
display: flex; flex-direction: column; gap: 6px; margin: 4px 0 8px 17px; padding: 8px 0 4px 14px;
|
||||
border-left: 2px solid var(--gold); scroll-margin: 96px 0 120px;
|
||||
}
|
||||
.ftv-inline .ftv-replyto { display: flex; align-items: center; gap: 5px; margin: 0; }
|
||||
.ftv-inline .ftv-replyto svg {
|
||||
width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round;
|
||||
}
|
||||
|
||||
/* Phones, while typing: the bottom menu and the floating button step aside
|
||||
for the keyboard (KeyboardSafe sets kb-open), and a focused box keeps room
|
||||
around it for its send button. */
|
||||
@media (max-width: 759px) {
|
||||
.kb-open .forum-nav, .kb-open .ftv-incoming { display: none; }
|
||||
}
|
||||
.forum textarea, .forum input { scroll-margin: 88px 0 96px; }
|
||||
|
||||
/* The small links at the bottom of the side column: rows in one card. */
|
||||
.fh-links { display: flex; flex-direction: column; }
|
||||
.fh-link {
|
||||
display: flex; align-items: center; gap: 12px; min-height: 56px; padding: 10px 16px;
|
||||
color: var(--ink); text-decoration: none;
|
||||
}
|
||||
.fh-link + .fh-link { border-top: 1px solid var(--line); }
|
||||
.fh-link:hover { background: var(--f-hover); }
|
||||
.fh-link svg {
|
||||
width: 20px; height: 20px; flex: none; fill: none; stroke: var(--gold); stroke-width: 1.8;
|
||||
stroke-linecap: round; stroke-linejoin: round;
|
||||
}
|
||||
.fh-link-text { display: flex; flex-direction: column; flex: 1; min-width: 0; font-size: 15px; font-weight: 500; }
|
||||
.fh-link-text .hint { font-size: 13px; font-weight: 400; }
|
||||
.fh-link-arrow { color: var(--muted); font-size: 20px; line-height: 1; }
|
||||
/* The same row at the foot of a card, or framed inside one. */
|
||||
.fh-link-foot { margin: 14px -18px -18px; border-top: 1px solid var(--line); border-radius: 0 0 16px 16px; }
|
||||
.fh-link-boxed { min-height: 52px; padding: 8px 12px; border: 1px solid var(--line); border-radius: 12px; }
|
||||
|
||||
/* --- search --- */
|
||||
.fsearch-form { display: flex; gap: 8px; }
|
||||
.fsearch-form .inp { flex: 1; min-width: 0; }
|
||||
.fsearch-results { list-style: none; margin: 0; padding: 0; }
|
||||
.fsearch-results li + li { border-top: 1px solid var(--line); }
|
||||
.fsearch-hit { display: flex; flex-direction: column; gap: 4px; padding: 14px 16px; color: var(--ink); text-decoration: none; }
|
||||
.fsearch-hit:hover { background: var(--f-hover); }
|
||||
.fsearch-title { font-size: 17px; font-weight: 600; }
|
||||
.fsearch-meta { font-size: 13px; color: var(--muted); }
|
||||
.fsearch-snippet { font-size: 15px; color: var(--ink-2); }
|
||||
.fsearch-snippet mark { background: var(--f-tint-strong); color: var(--ink); border-radius: 3px; padding: 0 2px; }
|
||||
|
||||
/* --- muted members --- */
|
||||
.fp-muted { padding: 4px 0; }
|
||||
.fmute { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
|
||||
.fmuted { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
|
||||
.fmuted li { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
|
||||
/* --- archived topics --- */
|
||||
.fh-archived { margin-top: 10px; }
|
||||
.fh-archived summary { min-height: 44px; display: flex; align-items: center; color: var(--ink-2); font-size: 15px; cursor: pointer; }
|
||||
.fh-archived .fh-links { list-style: none; margin: 0; padding: 0; }
|
||||
.fh-archived li + li .fh-link { border-top: 1px solid var(--line); }
|
||||
|
||||
/* --- a chart shared with a question --- */
|
||||
.fshare {
|
||||
display: flex; flex-direction: column; align-items: flex-start; gap: 6px; margin-top: 12px; padding: 14px 16px;
|
||||
border: 1px solid var(--line-2); border-radius: 14px; background: var(--f-tint);
|
||||
}
|
||||
.fshare-quiet { background: none; border-style: dashed; }
|
||||
.fshare-head { display: flex; align-items: center; justify-content: space-between; width: 100%; }
|
||||
.fshare-title { font-size: 16px; }
|
||||
.fshare-summary { font-family: var(--font-display); font-size: 19px; color: var(--ink-2); }
|
||||
.fshare-points { list-style: none; margin: 2px 0; padding: 0; display: flex; flex-wrap: wrap; gap: 4px 16px; font-size: 15px; }
|
||||
.fshare-open { margin-top: 4px; }
|
||||
.fnew-share { display: flex; flex-direction: column; gap: 8px; }
|
||||
.fnew-share .fshare { margin-top: 0; }
|
||||
|
||||
/* --- link previews (YouTube) --- */
|
||||
.flinks { display: flex; flex-direction: column; gap: 10px; margin-top: 10px; }
|
||||
.flink {
|
||||
display: flex; flex-direction: column; max-width: 480px; overflow: hidden;
|
||||
border: 1px solid var(--line-2); border-radius: 14px; background: var(--panel);
|
||||
}
|
||||
.flink-thumb { position: relative; display: block; aspect-ratio: 16 / 9; background: #0e1424; }
|
||||
.flink-thumb img { display: block; width: 100%; height: 100%; object-fit: cover; }
|
||||
.flink-noimg { display: block; width: 100%; height: 100%; }
|
||||
.flink-play {
|
||||
position: absolute; left: 50%; top: 50%; width: 56px; height: 40px; transform: translate(-50%, -50%);
|
||||
display: grid; place-items: center; border-radius: 12px; background: rgba(15, 15, 15, 0.78);
|
||||
transition: background 0.15s;
|
||||
}
|
||||
.flink-play svg { width: 22px; height: 22px; fill: #fff; }
|
||||
.flink-thumb:hover .flink-play, .flink-thumb:focus-visible .flink-play { background: #d32020; }
|
||||
.flink-meta { display: flex; flex-direction: column; gap: 2px; padding: 10px 14px 12px; }
|
||||
.flink-title { font-weight: 600; font-size: 15px; line-height: 1.35; }
|
||||
.flink-here { align-self: flex-start; margin-top: 4px; }
|
||||
.flink-frame { position: relative; aspect-ratio: 16 / 9; background: #000; }
|
||||
.flink-frame iframe { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; }
|
||||
.flink .fp-link { display: inline-flex; align-items: center; padding: 0; text-decoration: none; }
|
||||
@@ -0,0 +1,103 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
|
||||
import { ago, threadHref } from "@/lib/forum";
|
||||
import { forumGet } from "@/lib/forumServer";
|
||||
|
||||
export const metadata: Metadata = { title: "Keresés a fórumban", robots: { index: false, follow: true } };
|
||||
|
||||
interface SearchResult {
|
||||
thread: { id: number; title: string; slug: string };
|
||||
topic: { slug: string; name: string };
|
||||
author: { nickname: string } | null;
|
||||
last_post_at: string;
|
||||
reply_count: number;
|
||||
post_id: number | null;
|
||||
/** The matching words between ⟦ and ⟧. */
|
||||
snippet: string | null;
|
||||
}
|
||||
|
||||
/** The words the search found, marked. */
|
||||
function Marked({ text }: { text: string }) {
|
||||
return (
|
||||
<>
|
||||
{text
|
||||
.split(/(⟦[^⟧]*⟧)/)
|
||||
.map((part, i) =>
|
||||
part.startsWith("⟦") ? <mark key={i}>{part.slice(1, -1)}</mark> : <span key={i}>{part}</span>,
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Search in the threads and posts the visitor may read. */
|
||||
export default async function SearchPage({ searchParams }: { searchParams: Promise<{ q?: string; oldal?: string }> }) {
|
||||
const params = await searchParams;
|
||||
const q = (params.q ?? "").trim();
|
||||
const page = Math.max(1, Number(params.oldal) || 1);
|
||||
const res =
|
||||
q.length >= 2
|
||||
? await forumGet<{ results: SearchResult[]; more: boolean }>(
|
||||
`/v1/forum/search?q=${encodeURIComponent(q)}&page=${page}`,
|
||||
)
|
||||
: null;
|
||||
const results = res?.ok ? res.data.results : [];
|
||||
const more = res?.ok ? res.data.more : false;
|
||||
const link = (p: number) => `/forum/kereses?q=${encodeURIComponent(q)}&oldal=${p}`;
|
||||
return (
|
||||
<div className="fh">
|
||||
<h1 className="fpage-title">Keresés</h1>
|
||||
<form className="fsearch-form" action="/forum/kereses" role="search">
|
||||
<label htmlFor="fsearch-q" className="sr-only">
|
||||
Mit keresel?
|
||||
</label>
|
||||
<input
|
||||
id="fsearch-q"
|
||||
name="q"
|
||||
type="search"
|
||||
className="inp"
|
||||
defaultValue={q}
|
||||
placeholder="Mit keresel? Például: alvás, telihold, gyász"
|
||||
minLength={2}
|
||||
maxLength={100}
|
||||
autoFocus={!q}
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary">
|
||||
Keresés
|
||||
</button>
|
||||
</form>
|
||||
{q.length >= 2 &&
|
||||
(results.length === 0 ? (
|
||||
<p className="fh-card fh-empty">Erre nincs találat. Próbáld más szóval, vagy rövidebben.</p>
|
||||
) : (
|
||||
<ul className="fh-card fh-flush fsearch-results">
|
||||
{results.map((r) => (
|
||||
<li key={r.thread.id}>
|
||||
<Link href={threadHref(r.thread, r.post_id ?? undefined)} className="fsearch-hit">
|
||||
<span className="fsearch-title">{r.thread.title}</span>
|
||||
<span className="fsearch-meta">
|
||||
{r.topic.name} · {r.author?.nickname ?? "Törölt tag"} · {r.reply_count} válasz · utoljára{" "}
|
||||
<time suppressHydrationWarning dateTime={r.last_post_at}>
|
||||
{ago(r.last_post_at)}
|
||||
</time>
|
||||
</span>
|
||||
{r.snippet && (
|
||||
<span className="fsearch-snippet">
|
||||
<Marked text={r.snippet} />
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
))}
|
||||
{(page > 1 || more) && (
|
||||
<nav className="forum-pager" aria-label="Lapozás">
|
||||
{page > 1 ? <Link href={link(page - 1)}>‹ Előző</Link> : <span />}
|
||||
<span className="hint">{page}. oldal</span>
|
||||
{more ? <Link href={link(page + 1)}>Következő ›</Link> : <span />}
|
||||
</nav>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { RepliesTabs } from "@/components/forum/RepliesTabs";
|
||||
import { ThreadList } from "@/components/forum/ThreadList";
|
||||
import type { ForumViewer, ThreadCard } from "@/lib/forum";
|
||||
import { forumGet } from "@/lib/forumServer";
|
||||
|
||||
export const metadata = { title: "Követett szálak", robots: { index: false } };
|
||||
|
||||
/** The threads the member follows (their own and the ones they replied to), with what is new. */
|
||||
export default async function FollowedPage() {
|
||||
const res = await forumGet<{ viewer: ForumViewer; threads: ThreadCard[] }>("/v1/forum/followed");
|
||||
if (!res.ok) redirect("/belepes?vissza=/forum/kovetett");
|
||||
const { threads } = res.data;
|
||||
return (
|
||||
<div className="fh">
|
||||
<h1 className="fpage-title">Válaszok</h1>
|
||||
<RepliesTabs current="followed" />
|
||||
<p className="muted">A saját szálaid, azok, amelyekhez hozzászóltál, és amelyeket követni kezdtél.</p>
|
||||
{threads.length === 0 ? (
|
||||
<p className="fh-card fh-empty">Még nem követsz egy szálat sem.</p>
|
||||
) : (
|
||||
<div className="fh-card fh-flush">
|
||||
<ThreadList threads={threads} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { Metadata } from "next";
|
||||
import { cookies } from "next/headers";
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { ForumNav } from "@/components/forum/ForumNav";
|
||||
import { ThemeToggle } from "@/components/forum/ThemeToggle";
|
||||
import { PublicHeader } from "@/components/SiteHeader";
|
||||
import { FORUM_THEME_COOKIE, type ForumNavData, type ForumTheme } from "@/lib/forum";
|
||||
import { forumEnabled, forumGet } from "@/lib/forumServer";
|
||||
|
||||
import "./forum.css";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: { default: "Fórum", template: "%s · Fórum · Sorsfonalak" },
|
||||
description: "Spirituális fórum a Sorsfonalakon: beszélgetés, meghallgatás, asztrológia, álmok.",
|
||||
};
|
||||
|
||||
/**
|
||||
* The live connection's address: in production Caddy sends `/api/v1/forum/ws`
|
||||
* straight to the forum service; in development FORUM_WS_URL points at it.
|
||||
*
|
||||
* The forum's frame: the visitor header (the logged-in one comes from the
|
||||
* root layout), the forum's bar with its menu and the light/dark switch.
|
||||
* Light by default; the choice lives in a cookie.
|
||||
*/
|
||||
export default async function ForumLayout({ children }: { children: React.ReactNode }) {
|
||||
if (!forumEnabled()) notFound();
|
||||
const [nav, jar] = await Promise.all([forumGet<ForumNavData>("/v1/forum/nav"), cookies()]);
|
||||
const viewer = nav.ok ? nav.data.viewer : null;
|
||||
const theme: ForumTheme = jar.get(FORUM_THEME_COOKIE)?.value === "dark" ? "dark" : "light";
|
||||
return (
|
||||
<>
|
||||
{!viewer?.logged_in && <PublicHeader current="forum" />}
|
||||
<div className="forum" data-theme={theme}>
|
||||
<div className="forum-inner">
|
||||
<div className="forum-bar">
|
||||
<Link href="/forum" className="forum-mark">
|
||||
Fórum
|
||||
</Link>
|
||||
<ForumNav
|
||||
member={viewer?.member?.nickname ?? null}
|
||||
loggedIn={viewer?.logged_in ?? false}
|
||||
initial={{
|
||||
replies: nav.ok ? (nav.data.replies ?? 0) : 0,
|
||||
messages: nav.ok ? (nav.data.messages ?? 0) : 0,
|
||||
reports: nav.ok ? (nav.data.reports ?? 0) : 0,
|
||||
}}
|
||||
wsUrl={process.env.FORUM_WS_URL || "/api/v1/forum/ws"}
|
||||
/>
|
||||
<div className="forum-tools">
|
||||
<Link href="/forum/kereses" className="forum-theme forum-search" aria-label="Keresés a fórumban">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<circle cx="11" cy="11" r="6.5" />
|
||||
<path d="M16 16l4.5 4.5" />
|
||||
</svg>
|
||||
</Link>
|
||||
<ThemeToggle initial={theme} />
|
||||
</div>
|
||||
</div>
|
||||
<main className="forum-main">{children}</main>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
|
||||
export function ForumUnsubscribe({ token }: { token: string | null }) {
|
||||
const [state, setState] = useState<"idle" | "busy" | "done">("idle");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
if (!token)
|
||||
return <p className="msg msg-error">Hiányzik a leiratkozó link vége. Nyisd meg újra a levélben lévő linket.</p>;
|
||||
|
||||
async function unsubscribe() {
|
||||
setState("busy");
|
||||
setError(null);
|
||||
try {
|
||||
await api(`/forum/unsubscribe?token=${encodeURIComponent(token ?? "")}`, { method: "POST" });
|
||||
setState("done");
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
setState("idle");
|
||||
}
|
||||
}
|
||||
|
||||
if (state === "done") {
|
||||
return (
|
||||
<p className="fh-banner">
|
||||
<span>
|
||||
Kész, a fórum nem küld több levelet. Ha meggondolod magad, a{" "}
|
||||
<Link href="/forum/beallitasok">fórumprofilodnál</Link> újra bekapcsolhatod.
|
||||
</span>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<button type="button" className="btn btn-primary" disabled={state === "busy"} onClick={unsubscribe}>
|
||||
{state === "busy" ? "Leiratkozás…" : "Leiratkozom a fórum leveleiről"}
|
||||
</button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { ForumUnsubscribe } from "./ForumUnsubscribe";
|
||||
|
||||
export const metadata = { title: "Leiratkozás a fórum leveleiről", robots: { index: false } };
|
||||
|
||||
type Props = { searchParams: Promise<{ token?: string | string[] }> };
|
||||
|
||||
/** From the footer of a forum e-mail: every forum e-mail off, no login needed. */
|
||||
export default async function ForumUnsubscribePage({ searchParams }: Props) {
|
||||
const raw = (await searchParams).token;
|
||||
const token = Array.isArray(raw) ? raw[0] : raw;
|
||||
return (
|
||||
<div className="fh fprof">
|
||||
<h1 className="fpage-title">Leiratkozás</h1>
|
||||
<p className="muted">
|
||||
Nem kérsz több levelet a fórumról: se válaszértesítést, se napi összesítőt, se üzenetértesítést.
|
||||
</p>
|
||||
<ForumUnsubscribe token={token ?? null} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import { PostBody } from "@/components/forum/PostBody";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { REPORT_KINDS, type ReportEntry, ago, memberHref, threadHref } from "@/lib/forum";
|
||||
|
||||
const STATUS: Record<string, string> = { resolved: "Lezárva", dismissed: "Alaptalan" };
|
||||
|
||||
/** The reports: open ones first (a possible crisis on top), with what was reported and the actions. */
|
||||
export function ReportsList({ initial }: { initial: ReportEntry[] }) {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState<number | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const open = initial.filter((r) => r.status === "open");
|
||||
const handled = initial.filter((r) => r.status !== "open");
|
||||
|
||||
async function act(r: ReportEntry, work: () => Promise<unknown>) {
|
||||
setBusy(r.id);
|
||||
setError(null);
|
||||
try {
|
||||
await work();
|
||||
router.refresh();
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
|
||||
function removePost(r: ReportEntry) {
|
||||
if (r.target?.type !== "post") return;
|
||||
const reason = window.prompt("Miért távolítod el? Az indoklás a hozzászólás helyén látszik.");
|
||||
if (!reason) return;
|
||||
const id = r.target.id;
|
||||
void act(r, () => api(`/forum/posts/${id}`, { method: "DELETE", body: { reason } }));
|
||||
}
|
||||
|
||||
const card = (r: ReportEntry) => {
|
||||
const kind = REPORT_KINDS.find((k) => k.kind === r.kind)?.label ?? r.kind;
|
||||
const t = r.target;
|
||||
return (
|
||||
<article
|
||||
key={r.id}
|
||||
className={
|
||||
r.kind === "crisis" && r.status === "open" ? "fh-card fmod-report fmod-crisis" : "fh-card fmod-report"
|
||||
}
|
||||
>
|
||||
<div className="fmod-report-head">
|
||||
<strong>{kind}</strong>
|
||||
<span className="hint">
|
||||
{r.reporter} ·{" "}
|
||||
<time suppressHydrationWarning dateTime={r.created_at}>
|
||||
{ago(r.created_at)}
|
||||
</time>
|
||||
{r.open_reports_of_target > 1 && r.status === "open" && ` · ${r.open_reports_of_target} jelentés`}
|
||||
</span>
|
||||
</div>
|
||||
{r.note && <p className="fmod-note">„{r.note}”</p>}
|
||||
{r.kind === "crisis" && r.status === "open" && (
|
||||
<p className="hint warn">
|
||||
Lehet, hogy valaki bajban van. Ha a hozzászólás közvetlen veszélyre utal, ne csak moderálj: írj neki
|
||||
kedvesen, és mutasd meg a 116-123-as lelki elsősegély-számot.
|
||||
</p>
|
||||
)}
|
||||
{t?.type === "post" && (
|
||||
<div className="fmod-target">
|
||||
<span className="hint">
|
||||
Hozzászólás:{" "}
|
||||
{t.author ? <Link href={memberHref(t.author.nickname)}>{t.author.nickname}</Link> : "törölt tag"} ·{" "}
|
||||
<Link href={threadHref(t.thread, t.id)}>{t.thread.title}</Link>
|
||||
{t.deleted && " · már eltávolítva"}
|
||||
</span>
|
||||
<PostBody text={t.body} />
|
||||
</div>
|
||||
)}
|
||||
{t?.type === "message" && (
|
||||
<div className="fmod-target">
|
||||
<span className="hint">Privát üzenet, az előzményeivel (csak a jelentés miatt látod):</span>
|
||||
<ol className="fmod-chat">
|
||||
{t.messages.map((m) => (
|
||||
<li key={m.id} className={m.reported ? "fmod-chat-reported" : undefined}>
|
||||
<strong>{m.sender?.nickname ?? "Törölt tag"}:</strong> {m.body}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
)}
|
||||
{r.status === "open" ? (
|
||||
<div className="fmsg-actions">
|
||||
{t?.type === "post" && !t.deleted && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-danger"
|
||||
disabled={busy === r.id}
|
||||
onClick={() => removePost(r)}
|
||||
>
|
||||
Eltávolítás
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
disabled={busy === r.id}
|
||||
onClick={() => act(r, () => api(`/forum/mod/reports/${r.id}`, { body: { action: "resolve" } }))}
|
||||
>
|
||||
Kezeltem, lezárom
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-ghost"
|
||||
disabled={busy === r.id}
|
||||
onClick={() => act(r, () => api(`/forum/mod/reports/${r.id}`, { body: { action: "dismiss" } }))}
|
||||
>
|
||||
Alaptalan
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<p className="hint">
|
||||
{STATUS[r.status]}
|
||||
{r.handled_by && ` · ${r.handled_by}`}
|
||||
</p>
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<section className="fh-section" aria-labelledby="fmod-open">
|
||||
<h2 id="fmod-open" className="fmsg-h">
|
||||
Nyitott jelentések ({open.length})
|
||||
</h2>
|
||||
{open.length === 0 ? <p className="fh-card fh-empty">Nincs nyitott jelentés.</p> : open.map(card)}
|
||||
</section>
|
||||
{handled.length > 0 && (
|
||||
<section className="fh-section" aria-labelledby="fmod-done">
|
||||
<h2 id="fmod-done" className="fmsg-h">
|
||||
Az elmúlt 30 nap lezárt jelentései
|
||||
</h2>
|
||||
{handled.map(card)}
|
||||
</section>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import { Avatar } from "@/components/forum/Avatar";
|
||||
import { RankBadge } from "@/components/forum/Badges";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { type ForumTopic, type TopicRequest, ago } from "@/lib/forum";
|
||||
|
||||
const VISIBILITY: Record<string, string> = {
|
||||
public: "Nyilvános (a keresők is látják)",
|
||||
members: "Csak tagoknak",
|
||||
restricted: "Zárt (jóváhagyással)",
|
||||
};
|
||||
|
||||
/** Moderators: requests to join restricted topics. Admins also: opening and editing topics. */
|
||||
export function TopicsAdmin({
|
||||
requests,
|
||||
topics,
|
||||
admin,
|
||||
}: {
|
||||
requests: TopicRequest[];
|
||||
topics: ForumTopic[];
|
||||
admin: boolean;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [form, setForm] = useState({ name: "", description: "", visibility: "restricted", listening: false });
|
||||
|
||||
async function act(work: () => Promise<unknown>) {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await work();
|
||||
router.refresh();
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const decide = (r: TopicRequest, action: "approve" | "reject" | "remove") =>
|
||||
act(() =>
|
||||
api("/forum/mod/topic-requests", {
|
||||
body: { topic: r.topic.slug, nickname: r.member?.nickname ?? "", action },
|
||||
}),
|
||||
);
|
||||
|
||||
const pending = requests.filter((r) => r.status === "pending");
|
||||
const approved = requests.filter((r) => r.status === "approved");
|
||||
|
||||
return (
|
||||
<>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<section className="fh-section" aria-labelledby="ftop-pending">
|
||||
<h2 id="ftop-pending" className="fmsg-h">
|
||||
Jelentkezések zárt témákba ({pending.length})
|
||||
</h2>
|
||||
{pending.length === 0 ? (
|
||||
<p className="fh-card fh-empty">Nincs várakozó jelentkezés.</p>
|
||||
) : (
|
||||
pending.map((r) => (
|
||||
<article key={`${r.topic.slug}-${r.member?.nickname}`} className="fh-card fmod-report">
|
||||
<div className="fmod-report-head">
|
||||
<span className="fh-online-item">
|
||||
<Avatar avatar={r.member?.avatar} size={28} />
|
||||
<strong>{r.member?.nickname ?? "?"}</strong>
|
||||
{r.member && <RankBadge rank={r.member.rank} name={r.member.rank_name} />}
|
||||
</span>
|
||||
<span className="hint">
|
||||
{r.topic.name} ·{" "}
|
||||
<time suppressHydrationWarning dateTime={r.requested_at}>
|
||||
{ago(r.requested_at)}
|
||||
</time>
|
||||
</span>
|
||||
</div>
|
||||
{r.note && <p className="fmod-note">„{r.note}”</p>}
|
||||
<div className="fmsg-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-primary"
|
||||
disabled={busy}
|
||||
onClick={() => decide(r, "approve")}
|
||||
>
|
||||
Jóváhagyom
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-ghost"
|
||||
disabled={busy}
|
||||
onClick={() => decide(r, "reject")}
|
||||
>
|
||||
Elutasítom
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
))
|
||||
)}
|
||||
</section>
|
||||
|
||||
{approved.length > 0 && (
|
||||
<section className="fh-section" aria-labelledby="ftop-members">
|
||||
<h2 id="ftop-members" className="fmsg-h">
|
||||
Zárt témák tagjai
|
||||
</h2>
|
||||
<ul className="fh-card fh-flush fmodlog">
|
||||
{approved.map((r) => (
|
||||
<li key={`${r.topic.slug}-${r.member?.nickname}`} className="ftop-member">
|
||||
<span className="fh-online-item">
|
||||
<Avatar avatar={r.member?.avatar} size={24} />
|
||||
{r.member?.nickname ?? "?"}
|
||||
<span className="hint">· {r.topic.name}</span>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-ghost"
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
window.confirm(`Eltávolítod ${r.member?.nickname} tagot a(z) „${r.topic.name}” témából?`) &&
|
||||
decide(r, "remove")
|
||||
}
|
||||
>
|
||||
Eltávolítom
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{admin && (
|
||||
<section className="fh-section" aria-labelledby="ftop-admin">
|
||||
<h2 id="ftop-admin" className="fmsg-h">
|
||||
Témák (admin)
|
||||
</h2>
|
||||
<ul className="fh-card fh-flush fmodlog">
|
||||
{topics.map((t) => (
|
||||
<li key={t.slug} className="ftop-member">
|
||||
<span>
|
||||
<strong>{t.name}</strong> <span className="hint">· {VISIBILITY[t.visibility] ?? t.visibility}</span>
|
||||
{t.archived && <span className="hint"> · archivált</span>}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-ghost"
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
(t.archived ||
|
||||
window.confirm(
|
||||
`Archiválod a(z) „${t.name}” témát? A szálai olvashatók maradnak, de új szál és hozzászólás nem írható bele, és lekerül a főoldalról.`,
|
||||
)) &&
|
||||
act(() => api(`/forum/topics/${t.slug}`, { method: "PATCH", body: { archived: !t.archived } }))
|
||||
}
|
||||
>
|
||||
{t.archived ? "Visszaállítás" : "Archiválás"}
|
||||
</button>
|
||||
<select
|
||||
className="inp ftop-vis"
|
||||
aria-label={`${t.name} láthatósága`}
|
||||
value={t.visibility}
|
||||
disabled={busy}
|
||||
onChange={(e) =>
|
||||
act(() => api(`/forum/topics/${t.slug}`, { method: "PATCH", body: { visibility: e.target.value } }))
|
||||
}
|
||||
>
|
||||
{Object.entries(VISIBILITY).map(([value, label]) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<form
|
||||
className="fh-card fnew"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void act(async () => {
|
||||
await api("/forum/topics", { body: form });
|
||||
setForm({ name: "", description: "", visibility: "restricted", listening: false });
|
||||
});
|
||||
}}
|
||||
>
|
||||
<strong>Új téma</strong>
|
||||
<div className="field">
|
||||
<label htmlFor="ftop-name">Név</label>
|
||||
<input
|
||||
id="ftop-name"
|
||||
className="inp"
|
||||
value={form.name}
|
||||
maxLength={60}
|
||||
onChange={(e) => setForm({ ...form, name: e.target.value })}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="ftop-desc">Rövid leírás</label>
|
||||
<input
|
||||
id="ftop-desc"
|
||||
className="inp"
|
||||
value={form.description}
|
||||
maxLength={160}
|
||||
onChange={(e) => setForm({ ...form, description: e.target.value })}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="ftop-visibility">Láthatóság</label>
|
||||
<select
|
||||
id="ftop-visibility"
|
||||
className="inp"
|
||||
value={form.visibility}
|
||||
onChange={(e) => setForm({ ...form, visibility: e.target.value })}
|
||||
>
|
||||
{Object.entries(VISIBILITY).map(([value, label]) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<label className="fprof-check">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.listening}
|
||||
onChange={(e) => setForm({ ...form, listening: e.target.checked })}
|
||||
/>
|
||||
<span>
|
||||
<strong>Meghallgatós téma</strong>
|
||||
<span className="hint">Az új szálak alapból meghallgatást kérnek, nem tanácsot.</span>
|
||||
</span>
|
||||
</label>
|
||||
<button
|
||||
type="submit"
|
||||
className="btn btn-primary"
|
||||
disabled={busy || !form.name.trim() || !form.description.trim()}
|
||||
>
|
||||
Téma létrehozása
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import {
|
||||
type ForumTopic,
|
||||
type ModLogEntry,
|
||||
type ReportEntry,
|
||||
type TopicRequest,
|
||||
banText,
|
||||
memberHref,
|
||||
threadHref,
|
||||
} from "@/lib/forum";
|
||||
import { forumGet } from "@/lib/forumServer";
|
||||
import { getMe } from "@/lib/server";
|
||||
|
||||
import { ReportsList } from "./ReportsList";
|
||||
import { TopicsAdmin } from "./TopicsAdmin";
|
||||
|
||||
export const metadata = { title: "Moderálás", robots: { index: false } };
|
||||
|
||||
const ACTIONS: Record<string, string> = {
|
||||
delete_post: "hozzászólást távolított el",
|
||||
restore_post: "hozzászólást állított vissza",
|
||||
delete_thread: "szálat távolított el",
|
||||
restore_thread: "szálat állított vissza",
|
||||
ban: "eltiltotta",
|
||||
unban: "feloldotta az eltiltását",
|
||||
lock: "lezárta a szálat",
|
||||
unlock: "feloldotta a szálat",
|
||||
pin: "kitűzte a szálat",
|
||||
unpin: "levette a kitűzést",
|
||||
resolve_report: "lezárt egy jelentést",
|
||||
dismiss_report: "alaptalannak ítélt egy jelentést",
|
||||
approve_member: "felvette egy zárt témába",
|
||||
reject_member: "elutasította a jelentkezését",
|
||||
remove_member: "eltávolította egy zárt témából",
|
||||
reset_avatar: "eltávolította a saját képét",
|
||||
topic: "témát kezelt",
|
||||
};
|
||||
|
||||
type Props = { searchParams: Promise<{ nezet?: string }> };
|
||||
|
||||
/** Moderators: the open reports, and the log of every moderation step. */
|
||||
export default async function ModerationPage({ searchParams }: Props) {
|
||||
const view = (await searchParams).nezet;
|
||||
const log = view === "naplo";
|
||||
const topics = view === "temak";
|
||||
return (
|
||||
<div className="fh">
|
||||
<h1 className="fpage-title">Moderálás</h1>
|
||||
<nav className="fmod-tabs" aria-label="Moderálás">
|
||||
<Link href="/forum/moderalas" aria-current={log || topics ? undefined : "page"}>
|
||||
Jelentések
|
||||
</Link>
|
||||
<Link href="/forum/moderalas?nezet=temak" aria-current={topics ? "page" : undefined}>
|
||||
Témák
|
||||
</Link>
|
||||
<Link href="/forum/moderalas?nezet=naplo" aria-current={log ? "page" : undefined}>
|
||||
Napló
|
||||
</Link>
|
||||
</nav>
|
||||
{log ? <LogView /> : topics ? <TopicsView /> : <ReportsView />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
async function ReportsView() {
|
||||
const res = await forumGet<{ reports: ReportEntry[] }>("/v1/forum/mod/reports");
|
||||
if (!res.ok) notFound();
|
||||
return <ReportsList initial={res.data.reports} />;
|
||||
}
|
||||
|
||||
async function TopicsView() {
|
||||
const [requests, list, me] = await Promise.all([
|
||||
forumGet<{ requests: TopicRequest[] }>("/v1/forum/mod/topic-requests"),
|
||||
forumGet<{ topics: ForumTopic[] }>("/v1/forum/topics"),
|
||||
getMe(),
|
||||
]);
|
||||
if (!requests.ok) notFound();
|
||||
return (
|
||||
<TopicsAdmin
|
||||
requests={requests.data.requests}
|
||||
topics={list.ok ? list.data.topics : []}
|
||||
admin={me?.user.roles.includes("admin") ?? false}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
async function LogView() {
|
||||
const res = await forumGet<{ entries: ModLogEntry[] }>("/v1/forum/mod/log");
|
||||
if (!res.ok) notFound();
|
||||
if (res.data.entries.length === 0) return <p className="fh-card fh-empty">Még nem volt moderálás.</p>;
|
||||
return (
|
||||
<ul className="fh-card fh-flush fmodlog">
|
||||
{res.data.entries.map((e) => (
|
||||
<li key={e.id}>
|
||||
<span className="hint">
|
||||
{new Date(e.created_at).toLocaleString("hu-HU", { timeZone: "Europe/Budapest" })}
|
||||
{e.actor_kind === "ai" && " · AI"}
|
||||
</span>
|
||||
<span>
|
||||
<strong>{e.actor ?? "?"}</strong> {ACTIONS[e.action] ?? e.action}
|
||||
{e.target && (
|
||||
<>
|
||||
{" "}
|
||||
(<Link href={memberHref(e.target)}>{e.target}</Link>)
|
||||
</>
|
||||
)}
|
||||
{e.thread && (
|
||||
<>
|
||||
{": "}
|
||||
<Link href={threadHref({ id: e.thread.id, slug: "" }, e.post_id ?? undefined)}>
|
||||
{e.thread.title ?? `#${e.thread.id}`}
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
{e.until && ` · ${banText(e.until)}`}
|
||||
</span>
|
||||
{e.reason && <span className="hint">Ok: {e.reason}</span>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { Avatar } from "@/components/forum/Avatar";
|
||||
import { RankBadge } from "@/components/forum/Badges";
|
||||
import { JoinTopic } from "@/components/forum/JoinTopic";
|
||||
import { ThreadList, WaitingCard } from "@/components/forum/ThreadList";
|
||||
import { MoonPhaseIcon } from "@/components/MoonChip";
|
||||
import { MOON_PHASES, SIGNS } from "@/lib/astro";
|
||||
import { type ForumHome, ago, memberHref } from "@/lib/forum";
|
||||
import { forumGet } from "@/lib/forumServer";
|
||||
import { loadSky } from "@/lib/sky";
|
||||
import { MOON_IN_SIGN, SIGN_IN, withArticle } from "@/lib/skyText";
|
||||
import type { SkyNow } from "@/lib/types";
|
||||
|
||||
export const metadata = { title: { absolute: "Fórum · Sorsfonalak" } };
|
||||
|
||||
function TopicIcon({ slug }: { slug: string }) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" className="topic-icon">
|
||||
{slug === "ami-a-szivemen-van" && (
|
||||
<path d="M12 20s-7.5-4.6-7.5-10.2A4.2 4.2 0 0 1 12 7.3a4.2 4.2 0 0 1 7.5 2.5C19.5 15.4 12 20 12 20z" />
|
||||
)}
|
||||
{slug === "belso-utak" && (
|
||||
<>
|
||||
<path d="M12 12a1.2 1.2 0 1 0 1.2-1.2" />
|
||||
<path d="M13.2 10.8A3.4 3.4 0 1 0 15.4 14" />
|
||||
<path d="M15.4 14A5.6 5.6 0 1 1 12 6.4" />
|
||||
<path d="M12 6.4a7.8 7.8 0 1 1-7.6 9.4" />
|
||||
</>
|
||||
)}
|
||||
{slug === "egbolt-es-kepletek" && (
|
||||
<>
|
||||
<circle cx="12" cy="12" r="8.5" />
|
||||
<path d="M12 7.5l1.2 3.3 3.3 1.2-3.3 1.2L12 16.5l-1.2-3.3L7.5 12l3.3-1.2z" />
|
||||
</>
|
||||
)}
|
||||
{slug === "torzsasztal" && (
|
||||
<>
|
||||
<path d="M4.5 10h11v4.5a5 5 0 0 1-5 5h-1a5 5 0 0 1-5-5z" />
|
||||
<path d="M15.5 11.5h1.3a2.4 2.4 0 0 1 0 4.8h-1.6" />
|
||||
<path d="M8.5 3.5c0 1.4 1 1.6 1 3M12 3.5c0 1.4 1 1.6 1 3" />
|
||||
</>
|
||||
)}
|
||||
{!["ami-a-szivemen-van", "belso-utak", "egbolt-es-kepletek", "torzsasztal"].includes(slug) && (
|
||||
<circle cx="12" cy="12" r="8.5" />
|
||||
)}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/** "Mai égbolt": the Moon today, the same for everyone; never empty. */
|
||||
function SkyCard({ sky }: { sky: SkyNow }) {
|
||||
const moon = sky.moon;
|
||||
const sign = moon.position.sign;
|
||||
const date = new Date(sky.local_time.slice(0, 10) + "T12:00:00Z").toLocaleDateString("hu-HU", {
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
weekday: "long",
|
||||
timeZone: "UTC",
|
||||
});
|
||||
return (
|
||||
<section className="fh-card fh-sky" aria-labelledby="fh-sky-title">
|
||||
<div className="fh-card-head">
|
||||
<span className="eyebrow">Mai égbolt</span>
|
||||
<span className="hint">{date}</span>
|
||||
</div>
|
||||
<div className="fh-sky-body">
|
||||
<span className="fh-moon">
|
||||
<MoonPhaseIcon illumination={moon.illumination} waxing={moon.waxing} />
|
||||
</span>
|
||||
<div className="fh-sky-text">
|
||||
<h2 id="fh-sky-title">
|
||||
{MOON_PHASES[moon.phase] ?? moon.phase}, <span className="sym">{SIGNS[sign]?.glyph}</span> Hold{" "}
|
||||
{withArticle(SIGN_IN[sign] ?? sign)}
|
||||
</h2>
|
||||
<p>{MOON_IN_SIGN[sign]}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Link href="/holdnaptar" className="fh-link fh-link-foot">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<rect x="4" y="5.5" width="16" height="14.5" rx="2" />
|
||||
<path d="M4 10h16M8.5 3.5v4M15.5 3.5v4" />
|
||||
</svg>
|
||||
<span className="fh-link-text">
|
||||
Holdnaptár
|
||||
<span className="hint">A következő holdfázisok</span>
|
||||
</span>
|
||||
<span className="fh-link-arrow" aria-hidden="true">
|
||||
›
|
||||
</span>
|
||||
</Link>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export default async function ForumHomePage() {
|
||||
const [home, sky] = await Promise.all([forumGet<ForumHome>("/v1/forum/home"), loadSky()]);
|
||||
if (!home.ok) notFound();
|
||||
const { viewer, replies, waiting, topics, unanswered, hot } = home.data;
|
||||
|
||||
return (
|
||||
<div className="fh fh-home">
|
||||
<div className="fh-col fh-col-main">
|
||||
{!viewer.logged_in && (
|
||||
<section className="fh-card fh-intro o-1">
|
||||
<h1>Fórum</h1>
|
||||
<p>
|
||||
Beszélgetés a spiritualitásról, az égboltról, az álmokról és arról, ami a szívedet nyomja. Itt mindenki
|
||||
álnéven ír, a tempó nyugodt, és a meghallgatás fontosabb a vitánál.
|
||||
</p>
|
||||
<p className="hint">
|
||||
Olvasni belépés nélkül is lehet. Hozzászólni és az „Ami a szívemen van” témát olvasni belépve.
|
||||
</p>
|
||||
<Link href="/belepes?vissza=/forum" className="btn btn-primary">
|
||||
Belépés
|
||||
</Link>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{viewer.needs_nickname && (
|
||||
<Link href="/forum/beallitasok" className="fh-banner o-2">
|
||||
<span>
|
||||
<strong>Válassz álnevet</strong>, hogy hozzászólhass. A valódi neved soha nem jelenik meg a fórumon.
|
||||
</span>
|
||||
<span aria-hidden="true">›</span>
|
||||
</Link>
|
||||
)}
|
||||
|
||||
{viewer.member?.banned && (
|
||||
<p className="fh-banner fh-banner-warn o-2">
|
||||
Most nem írhatsz a fórumba. A részleteket a beállításaidnál látod.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{replies !== null && replies > 0 && (
|
||||
<Link href="/forum/valaszok" className="fh-banner o-2">
|
||||
<span>
|
||||
<strong>{replies === 1 ? "1 új válasz" : `${replies} új válasz`}</strong> érkezett neked
|
||||
</span>
|
||||
<span aria-hidden="true">›</span>
|
||||
</Link>
|
||||
)}
|
||||
|
||||
{unanswered.length > 0 && (
|
||||
<section className="fh-section o-4" id="varnak" aria-labelledby="fh-waiting">
|
||||
<div className="fh-section-head">
|
||||
<h2 id="fh-waiting">Várják a válaszod</h2>
|
||||
<span className="hint">még senki nem válaszolt</span>
|
||||
</div>
|
||||
<div className="fh-waiting-grid">
|
||||
{unanswered.map((t) => (
|
||||
<WaitingCard key={t.id} thread={t} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{hot.length > 0 && (
|
||||
<section className="fh-section o-5" aria-labelledby="fh-hot">
|
||||
<div className="fh-section-head">
|
||||
<h2 id="fh-hot">Élénk beszélgetések</h2>
|
||||
<span className="hint">ma sokan írtak bennük</span>
|
||||
</div>
|
||||
<div className="fh-card fh-flush">
|
||||
<ThreadList threads={hot} />
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
<section className="fh-section o-6" aria-labelledby="fh-topics">
|
||||
<div className="fh-section-head">
|
||||
<h2 id="fh-topics">Témák</h2>
|
||||
</div>
|
||||
<ul className="fh-card fh-flush fh-topics">
|
||||
{topics
|
||||
.filter((t) => !t.archived)
|
||||
.map((t) =>
|
||||
t.visibility === "restricted" && !t.readable ? (
|
||||
<li key={t.slug}>
|
||||
<div className="fh-topic fh-topic-closed">
|
||||
<span className="fh-topic-icon">
|
||||
<TopicIcon slug={t.slug} />
|
||||
</span>
|
||||
<span className="fh-topic-text">
|
||||
<span className="fh-topic-name">
|
||||
{t.name}
|
||||
<svg viewBox="0 0 24 24" className="fh-lock" role="img" aria-label="Zárt téma">
|
||||
<rect x="5" y="11" width="14" height="9" rx="2" />
|
||||
<path d="M8 11V8a4 4 0 0 1 8 0v3" />
|
||||
</svg>
|
||||
</span>
|
||||
<span className="fh-topic-desc">{t.description}</span>
|
||||
<span className="fh-topic-last">Zárt kör: jóváhagyás után olvasható</span>
|
||||
</span>
|
||||
{viewer.member && <JoinTopic slug={t.slug} pending={t.membership === "pending"} />}
|
||||
</div>
|
||||
</li>
|
||||
) : (
|
||||
<li key={t.slug}>
|
||||
<Link
|
||||
href={t.readable ? `/forum/${t.slug}` : `/belepes?vissza=/forum/${t.slug}`}
|
||||
className="fh-topic"
|
||||
>
|
||||
<span className="fh-topic-icon">
|
||||
<TopicIcon slug={t.slug} />
|
||||
</span>
|
||||
<span className="fh-topic-text">
|
||||
<span className="fh-topic-name">
|
||||
{t.name}
|
||||
{t.visibility !== "public" && (
|
||||
<svg viewBox="0 0 24 24" className="fh-lock" role="img" aria-label="Csak tagoknak">
|
||||
<rect x="5" y="11" width="14" height="9" rx="2" />
|
||||
<path d="M8 11V8a4 4 0 0 1 8 0v3" />
|
||||
</svg>
|
||||
)}
|
||||
</span>
|
||||
<span className="fh-topic-desc">{t.description}</span>
|
||||
{t.readable && t.last && (
|
||||
<span className="fh-topic-last">
|
||||
{t.last.author && (
|
||||
<Avatar avatar={t.last.author.avatar} size={18} online={t.last.author.online} />
|
||||
)}
|
||||
{t.last.author?.nickname ?? "Törölt tag"},{" "}
|
||||
<time suppressHydrationWarning dateTime={t.last.at}>
|
||||
{ago(t.last.at)}
|
||||
</time>
|
||||
</span>
|
||||
)}
|
||||
{!t.readable && <span className="fh-topic-last">Belépés után olvasható</span>}
|
||||
</span>
|
||||
{t.readable && (
|
||||
<span className="fh-topic-count">
|
||||
<strong>{t.thread_count ?? 0}</strong> szál
|
||||
</span>
|
||||
)}
|
||||
{t.readable && t.new_count ? (
|
||||
<span className="ft-new">{t.new_count > 99 ? "99+" : t.new_count} új</span>
|
||||
) : null}
|
||||
</Link>
|
||||
</li>
|
||||
),
|
||||
)}
|
||||
</ul>
|
||||
{topics.some((t) => t.archived) && (
|
||||
<details className="fh-archived">
|
||||
<summary>Archivált témák ({topics.filter((t) => t.archived).length})</summary>
|
||||
<ul className="fh-card fh-flush fh-links">
|
||||
{topics
|
||||
.filter((t) => t.archived && t.readable)
|
||||
.map((t) => (
|
||||
<li key={t.slug}>
|
||||
<Link href={`/forum/${t.slug}`} className="fh-link">
|
||||
<span className="fh-link-text">
|
||||
{t.name}
|
||||
<span className="hint">
|
||||
{t.description} · {t.thread_count ?? 0} szál
|
||||
</span>
|
||||
</span>
|
||||
<span className="fh-link-arrow" aria-hidden="true">
|
||||
›
|
||||
</span>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<aside className="fh-col fh-col-side" aria-label="Oldalsáv">
|
||||
{sky && (
|
||||
<div className="o-3">
|
||||
<SkyCard sky={sky} />
|
||||
</div>
|
||||
)}
|
||||
{home.data.online.length > 0 && (
|
||||
<section className="fh-card fh-online o-7" aria-labelledby="fh-online-title">
|
||||
<h2 id="fh-online-title" className="fh-online-title">
|
||||
Most itt vannak <span className="hint">({home.data.online.length})</span>
|
||||
</h2>
|
||||
<ul className="fh-online-list">
|
||||
{home.data.online.map((m) => (
|
||||
<li key={m.nickname}>
|
||||
<Link href={memberHref(m.nickname)} className="fh-online-item">
|
||||
<Avatar avatar={m.avatar} size={28} online />
|
||||
<span>{m.nickname}</span>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
{viewer.member && (
|
||||
<section className="fh-card fh-me o-7" aria-label="Saját">
|
||||
<div className="fh-me-head">
|
||||
<Avatar avatar={viewer.member.avatar} size={48} />
|
||||
<span className="fh-me-names">
|
||||
<Link href={memberHref(viewer.member.nickname)} className="fa-name">
|
||||
{viewer.member.nickname}
|
||||
</Link>
|
||||
<RankBadge rank={viewer.member.rank} name={viewer.member.rank_name} />
|
||||
</span>
|
||||
</div>
|
||||
{waiting !== null && waiting > 0 && (
|
||||
<Link href="#varnak" className="fh-link fh-link-boxed">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<circle cx="8" cy="6.5" r="2.5" />
|
||||
<circle cx="16" cy="6.5" r="2.5" />
|
||||
<path d="M3.5 20v-3.5a4.5 4.5 0 0 1 9 0V20" />
|
||||
<path d="M11.5 20v-3.5a4.5 4.5 0 0 1 9 0V20" />
|
||||
</svg>
|
||||
<span className="fh-link-text">
|
||||
{waiting === 1 ? "1 szál vár első válaszra" : `${waiting} szál vár első válaszra`}
|
||||
<span className="hint">Meghallgatást kérnek, még senki nem válaszolt</span>
|
||||
</span>
|
||||
<span className="fh-link-arrow" aria-hidden="true">
|
||||
›
|
||||
</span>
|
||||
</Link>
|
||||
)}
|
||||
<div className="fh-me-actions">
|
||||
<Link href="/forum/uj" className="btn btn-primary btn-sm">
|
||||
Új szál
|
||||
</Link>
|
||||
<Link href="/forum/beallitasok" className="btn btn-sm">
|
||||
Fórumprofil
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
<nav className="fh-card fh-flush fh-links o-8" aria-label="Továbbiak">
|
||||
<Link href="/aszf#forum" className="fh-link">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d="M5 4.5h9.5a3 3 0 0 1 3 3v12h-9.5a3 3 0 0 1-3-3z" />
|
||||
<path d="M8.5 9h5.5M8.5 12.5h5.5" />
|
||||
</svg>
|
||||
<span className="fh-link-text">
|
||||
Házirend
|
||||
<span className="hint">A fórum szabályai</span>
|
||||
</span>
|
||||
<span className="fh-link-arrow" aria-hidden="true">
|
||||
›
|
||||
</span>
|
||||
</Link>
|
||||
{viewer.moderator && (
|
||||
<Link href="/forum/moderalas" className="fh-link">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d="M12 3.5l7 2.5v5.5c0 4.5-3 7.5-7 9-4-1.5-7-4.5-7-9V6z" />
|
||||
<path d="M9 12l2.2 2.2L15.5 10" />
|
||||
</svg>
|
||||
<span className="fh-link-text">
|
||||
Moderálás
|
||||
<span className="hint">Jelentések, témák, napló</span>
|
||||
</span>
|
||||
<span className="fh-link-arrow" aria-hidden="true">
|
||||
›
|
||||
</span>
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
</aside>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound, permanentRedirect, redirect } from "next/navigation";
|
||||
|
||||
import { ThreadView } from "@/components/forum/ThreadView";
|
||||
import type { ThreadPage } from "@/lib/forum";
|
||||
import { forumGet } from "@/lib/forumServer";
|
||||
|
||||
type Props = { params: Promise<{ id: string }> };
|
||||
|
||||
/** `123-nem-tudom-elengedni` → 123; the words after the number are only for reading. */
|
||||
function threadId(param: string): number | null {
|
||||
const match = /^(\d{1,15})(?:-|$)/.exec(decodeURIComponent(param));
|
||||
return match ? Number(match[1]) : null;
|
||||
}
|
||||
|
||||
async function load(param: string) {
|
||||
const id = threadId(param);
|
||||
if (id === null) return null;
|
||||
return forumGet<ThreadPage>(`/v1/forum/threads/${id}`);
|
||||
}
|
||||
|
||||
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||
const res = await load((await params).id);
|
||||
if (!res?.ok) return { title: "Fórum", robots: { index: false } };
|
||||
const { thread, posts } = res.data;
|
||||
const open = thread.topic.visibility === "public" && !thread.deleted;
|
||||
const opening = posts.find((p) => p.is_opening)?.body ?? "";
|
||||
return {
|
||||
title: thread.title,
|
||||
description: open ? opening.slice(0, 160) : undefined,
|
||||
alternates: { canonical: `/forum/szal/${thread.id}-${thread.slug}` },
|
||||
// Members-only topics and removed threads stay out of search engines.
|
||||
robots: open ? undefined : { index: false, follow: false },
|
||||
};
|
||||
}
|
||||
|
||||
export default async function ThreadPageView({ params }: Props) {
|
||||
const param = (await params).id;
|
||||
const res = await load(param);
|
||||
if (!res) notFound();
|
||||
if (!res.ok) {
|
||||
if (res.status === 401) redirect(`/belepes?vissza=/forum/szal/${encodeURIComponent(param)}`);
|
||||
notFound();
|
||||
}
|
||||
const { thread } = res.data;
|
||||
const canonical = thread.slug ? `${thread.id}-${thread.slug}` : `${thread.id}`;
|
||||
if (decodeURIComponent(param) !== canonical) permanentRedirect(`/forum/szal/${canonical}`);
|
||||
return <ThreadView initial={res.data} />;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
|
||||
const DURATIONS: { hours: number | null; label: string }[] = [
|
||||
{ hours: 3, label: "3 óra" },
|
||||
{ hours: 24, label: "1 nap" },
|
||||
{ hours: 72, label: "3 nap" },
|
||||
{ hours: 168, label: "1 hét" },
|
||||
{ hours: 720, label: "30 nap" },
|
||||
{ hours: null, label: "Végleg" },
|
||||
];
|
||||
|
||||
/** Moderators: ban a member for a while or for good (they may still read), or lift it. */
|
||||
export function BanPanel({ nickname, banned, ownPicture }: { nickname: string; banned: boolean; ownPicture: boolean }) {
|
||||
const router = useRouter();
|
||||
const [hours, setHours] = useState<string>("24");
|
||||
const [reason, setReason] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const path = `/forum/members/${encodeURIComponent(nickname)}/ban`;
|
||||
|
||||
async function act(work: () => Promise<unknown>) {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await work();
|
||||
router.refresh();
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<details className="fban">
|
||||
<summary className="btn btn-sm btn-ghost">Moderálás</summary>
|
||||
<div className="fban-body">
|
||||
{ownPicture && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
window.confirm("Visszaállítod a kezdő avatart? A feltöltött kép törlődik.") &&
|
||||
act(() => api(`/forum/members/${encodeURIComponent(nickname)}/avatar-reset`, { method: "POST" }))
|
||||
}
|
||||
>
|
||||
Saját kép eltávolítása
|
||||
</button>
|
||||
)}
|
||||
{banned && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
disabled={busy}
|
||||
onClick={() => act(() => api(path, { method: "DELETE" }))}
|
||||
>
|
||||
Eltiltás feloldása
|
||||
</button>
|
||||
)}
|
||||
<div className="field">
|
||||
<label htmlFor="fban-hours">Eltiltás</label>
|
||||
<select id="fban-hours" className="inp" value={hours} onChange={(e) => setHours(e.target.value)}>
|
||||
{DURATIONS.map((d) => (
|
||||
<option key={d.label} value={d.hours ?? "forever"}>
|
||||
{d.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="fban-reason">Indoklás (a tag látja)</label>
|
||||
<input
|
||||
id="fban-reason"
|
||||
className="inp"
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
maxLength={300}
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-danger"
|
||||
disabled={busy || reason.trim().length < 3}
|
||||
onClick={() => act(() => api(path, { body: { hours: hours === "forever" ? null : Number(hours), reason } }))}
|
||||
>
|
||||
Eltiltom
|
||||
</button>
|
||||
</div>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
|
||||
/** The admin's switch for the "Alapító tag" badge (e.g. off for a test account; the place goes to the next newcomer). */
|
||||
export function FounderToggle({ nickname, founder }: { nickname: string; founder: boolean }) {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
return (
|
||||
<div className="fmute">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-ghost"
|
||||
disabled={busy}
|
||||
onClick={async () => {
|
||||
if (
|
||||
founder &&
|
||||
!window.confirm(`Elveszed ${nickname} Alapító tag jelvényét? A helyét a következő új tag kapja.`)
|
||||
)
|
||||
return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api(`/forum/members/${encodeURIComponent(nickname)}/founder`, {
|
||||
method: "PUT",
|
||||
body: { founder: !founder },
|
||||
});
|
||||
router.refresh();
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{founder ? "Alapító tag jelvény elvétele" : "Alapító tag jelvény megadása"}
|
||||
</button>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
|
||||
/** "Némítás" on a member's profile: their threads, posts and notices step out of the viewer's way. */
|
||||
export function MuteButton({ nickname, muted }: { nickname: string; muted: boolean }) {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
return (
|
||||
<div className="fmute">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-ghost"
|
||||
disabled={busy}
|
||||
onClick={async () => {
|
||||
if (
|
||||
!muted &&
|
||||
!window.confirm(
|
||||
`Elnémítod ${nickname} tagot? A szálai eltűnnek a listáidból, a hozzászólásai összecsukva látszanak, és nem kapsz értesítést tőle. Ő erről nem tud.`,
|
||||
)
|
||||
)
|
||||
return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api(`/forum/members/${encodeURIComponent(nickname)}/mute`, { method: muted ? "DELETE" : "PUT" });
|
||||
router.refresh();
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{muted ? "Némítás feloldása" : "Némítás"}
|
||||
</button>
|
||||
{muted && <span className="hint">Elnémítottad: a szálai és az értesítései nem jelennek meg nálad.</span>}
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { withEmoji } from "@/lib/emoticons";
|
||||
import type { MemberRelation } from "@/lib/forum";
|
||||
|
||||
const INTRO_MAX = 200;
|
||||
|
||||
/**
|
||||
* Starting a private conversation from a profile: a request with a short
|
||||
* introduction. Shows instead where things stand (sent, open, waiting for
|
||||
* the viewer's answer), or why the viewer cannot start one yet.
|
||||
*/
|
||||
export function RequestPanel({ nickname, relation }: { nickname: string; relation: MemberRelation }) {
|
||||
const router = useRouter();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [intro, setIntro] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const id = relation.conversation_id;
|
||||
|
||||
if (relation.state === "accepted" && id) {
|
||||
return (
|
||||
<Link href={`/forum/uzenetek/${id}`} className="btn btn-sm">
|
||||
Üzenetek
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
if (relation.state === "incoming" && id) {
|
||||
return (
|
||||
<Link href={`/forum/uzenetek/${id}`} className="btn btn-sm btn-primary">
|
||||
Beszélgetni szeretne veled: válaszolj
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
if (relation.state === "outgoing") return <p className="hint">Beszélgetési kérésed elküldve, válaszra vár.</p>;
|
||||
if (relation.state === "blocked_by_me")
|
||||
return <p className="hint">Letiltottad. A tiltást az üzeneteidnél oldhatod fel.</p>;
|
||||
if (!relation.eligible) {
|
||||
return <p className="hint">Beszélgetést a Kereső rangtól kezdeményezhetsz, ha már írtál a fórumba.</p>;
|
||||
}
|
||||
if (!relation.can_request) return null;
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await api<{ id: number }>("/forum/conversations", { body: { to: nickname, intro } });
|
||||
router.push(`/forum/uzenetek/${res.id}`);
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
setError(errorText(err));
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (!open) {
|
||||
return (
|
||||
<button type="button" className="btn btn-sm" onClick={() => setOpen(true)}>
|
||||
Beszélgetést kezdeményezek
|
||||
</button>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<form className="freq" onSubmit={submit}>
|
||||
<label htmlFor="freq-intro">Pár szó magadról és arról, miért írnál neki</label>
|
||||
<textarea
|
||||
id="freq-intro"
|
||||
className="fc-text"
|
||||
rows={3}
|
||||
maxLength={INTRO_MAX}
|
||||
value={intro}
|
||||
onChange={(e) => withEmoji(e, setIntro)}
|
||||
placeholder="Szia! Olvastam a hozzászólásodat a…"
|
||||
/>
|
||||
<span className="hint">
|
||||
{intro.length}/{INTRO_MAX} · link nélkül. Ha elfogadja, beszélgethettek; ha nem, erről nem kapsz értesítést.
|
||||
</span>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<div className="fc-actions">
|
||||
<button type="button" className="btn btn-ghost btn-sm" onClick={() => setOpen(false)}>
|
||||
Mégse
|
||||
</button>
|
||||
<button type="submit" className="btn btn-primary btn-sm" disabled={busy || intro.trim().length < 3}>
|
||||
{busy ? "Küldés…" : "Kérés küldése"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { Avatar } from "@/components/forum/Avatar";
|
||||
import { signsText } from "@/components/forum/AuthorLine";
|
||||
import { Badge, RankBadge } from "@/components/forum/Badges";
|
||||
import { PostBody } from "@/components/forum/PostBody";
|
||||
import { type MemberProfile, ago, banText, threadHref } from "@/lib/forum";
|
||||
import { forumGet } from "@/lib/forumServer";
|
||||
import { getMe } from "@/lib/server";
|
||||
|
||||
import { BanPanel } from "./BanPanel";
|
||||
import { FounderToggle } from "./FounderToggle";
|
||||
import { MuteButton } from "./MuteButton";
|
||||
import { RequestPanel } from "./RequestPanel";
|
||||
|
||||
type Props = { params: Promise<{ nev: string }> };
|
||||
|
||||
async function load(nev: string) {
|
||||
return forumGet<MemberProfile>(`/v1/forum/members/${encodeURIComponent(decodeURIComponent(nev))}`);
|
||||
}
|
||||
|
||||
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||
const res = await load((await params).nev);
|
||||
return res.ok ? { title: res.data.member.author.nickname, robots: { index: false } } : { title: "Fórum" };
|
||||
}
|
||||
|
||||
const LAST_SEEN: Record<string, string> = {
|
||||
online: "Most online",
|
||||
day: "Az elmúlt napban járt itt",
|
||||
week: "Ezen a héten járt itt",
|
||||
earlier: "Régebben járt itt",
|
||||
};
|
||||
|
||||
/** A member's profile: what they chose to show, and their recent posts. */
|
||||
export default async function MemberPage({ params }: Props) {
|
||||
const res = await load((await params).nev);
|
||||
if (!res.ok) notFound();
|
||||
const { member, recent, viewer } = res.data;
|
||||
const a = member.author;
|
||||
const admin = viewer.logged_in ? ((await getMe())?.user.roles.includes("admin") ?? false) : false;
|
||||
const signs = signsText(a.signs);
|
||||
const since = new Date(member.created_at).toLocaleDateString("hu-HU", { year: "numeric", month: "long" });
|
||||
return (
|
||||
<div className="fh fh-member">
|
||||
<section className="fh-card fmember">
|
||||
<div className="fmember-head">
|
||||
<Avatar avatar={a.avatar} size={72} online={a.online} />
|
||||
<div className="fmember-names">
|
||||
<h1>{a.nickname}</h1>
|
||||
<span className="fmember-badges">
|
||||
<RankBadge rank={a.rank} name={a.rank_name} />
|
||||
{a.moderator && <Badge kind="mod" />}
|
||||
{a.founder && <Badge kind="founder" />}
|
||||
{a.listener && <Badge kind="listener" />}
|
||||
{a.supporter && <Badge kind="supporter" />}
|
||||
</span>
|
||||
{member.last_seen && <span className="hint">{LAST_SEEN[member.last_seen]}</span>}
|
||||
</div>
|
||||
</div>
|
||||
{signs && <p className="sym fmember-signs">{signs}</p>}
|
||||
{member.bio && <PostBody text={member.bio} />}
|
||||
<p className="hint">
|
||||
Tag {since} óta · {member.post_count} hozzászólás · {member.thread_count} szál
|
||||
</p>
|
||||
{member.banned_until && (
|
||||
<p className="fh-banner fh-banner-warn">
|
||||
Eltiltva ({banText(member.banned_until)}).{member.ban_reason && ` Indok: ${member.ban_reason}`}
|
||||
</p>
|
||||
)}
|
||||
{res.data.relation && <RequestPanel nickname={a.nickname} relation={res.data.relation} />}
|
||||
{member.own && (
|
||||
<Link href="/forum/beallitasok" className="btn btn-sm">
|
||||
Profil szerkesztése
|
||||
</Link>
|
||||
)}
|
||||
{viewer.member && !member.own && <MuteButton nickname={a.nickname} muted={member.muted} />}
|
||||
{admin && <FounderToggle nickname={a.nickname} founder={a.founder ?? false} />}
|
||||
{viewer.moderator && !member.own && !a.moderator && (
|
||||
<BanPanel
|
||||
nickname={a.nickname}
|
||||
banned={member.banned_until !== null}
|
||||
ownPicture={a.avatar.startsWith("upload:")}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="fh-section" aria-labelledby="fmember-recent">
|
||||
<div className="fh-section-head">
|
||||
<h2 id="fmember-recent">Legutóbbi hozzászólások</h2>
|
||||
</div>
|
||||
{recent.length === 0 ? (
|
||||
<p className="fh-card fh-empty">
|
||||
Még nincs hozzászólása{viewer.logged_in ? "." : ", vagy csak belépve látható."}
|
||||
</p>
|
||||
) : (
|
||||
<ul className="fh-card fh-flush ft-list">
|
||||
{recent.map((r) => (
|
||||
<li key={r.id}>
|
||||
<Link href={threadHref({ id: r.thread_id, slug: r.thread_slug }, r.id)} className="ft-row">
|
||||
<span className="ft-main">
|
||||
<span className="ft-title">{r.thread_title}</span>
|
||||
<span className="ft-excerpt">{r.excerpt}</span>
|
||||
<span className="ft-meta">
|
||||
{r.is_opening ? "Szálat indított" : "Hozzászólt"} · {r.topic.name} ·{" "}
|
||||
<time suppressHydrationWarning dateTime={r.created_at}>
|
||||
{ago(r.created_at)}
|
||||
</time>
|
||||
</span>
|
||||
</span>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { convertEmoticons, withEmoji } from "@/lib/emoticons";
|
||||
import { ShareCard } from "@/components/forum/ShareCard";
|
||||
import { type ForumTopic, type ShareCardData, threadHref } from "@/lib/forum";
|
||||
|
||||
type Intent = "listen" | "advice" | "";
|
||||
|
||||
export function NewThreadForm({
|
||||
topics,
|
||||
initialTopic,
|
||||
share: initialShare,
|
||||
}: {
|
||||
topics: ForumTopic[];
|
||||
initialTopic: string;
|
||||
/** A chart, forecast or synastry shared for the question (from its page). */
|
||||
share?: { slug: string; card: ShareCardData } | null;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [share, setShare] = useState(initialShare ?? null);
|
||||
const [topic, setTopic] = useState(initialTopic);
|
||||
const listening = topics.find((t) => t.slug === topic)?.listening ?? false;
|
||||
const [intent, setIntent] = useState<Intent>(listening ? "listen" : "");
|
||||
const [title, setTitle] = useState("");
|
||||
const [body, setBody] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
function pickTopic(slug: string) {
|
||||
setTopic(slug);
|
||||
const t = topics.find((x) => x.slug === slug);
|
||||
if (t?.listening) setIntent("listen");
|
||||
}
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const created = await api<{ id: number; slug: string }>("/forum/threads", {
|
||||
body: {
|
||||
topic,
|
||||
title: convertEmoticons(title, title.length, true).text,
|
||||
body: convertEmoticons(body, body.length, true).text,
|
||||
intent: intent || null,
|
||||
share: share?.slug ?? null,
|
||||
},
|
||||
});
|
||||
router.push(threadHref(created));
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
setError(errorText(err));
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="fnew" onSubmit={submit}>
|
||||
{share && (
|
||||
<div className="fnew-share">
|
||||
<ShareCard share={share.card} onRemove={() => setShare(null)} />
|
||||
<span className="hint">
|
||||
A belépett tagok látják a hozzászólásod alatt. Írd le, mire vagy kíváncsi: minél konkrétabb a kérdés, annál
|
||||
jobb válaszokat kapsz.
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<fieldset className="fnew-set">
|
||||
<legend>Téma</legend>
|
||||
<div className="fnew-topics">
|
||||
{topics.map((t) => (
|
||||
<label key={t.slug} className="fnew-topic">
|
||||
<input
|
||||
type="radio"
|
||||
name="topic"
|
||||
value={t.slug}
|
||||
checked={topic === t.slug}
|
||||
onChange={() => pickTopic(t.slug)}
|
||||
/>
|
||||
<span>
|
||||
<strong>{t.name}</strong>
|
||||
<span className="hint">{t.description}</span>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset className="fnew-set">
|
||||
<legend>Mit szeretnél?</legend>
|
||||
<div className="fnew-intents">
|
||||
<label className="fnew-intent">
|
||||
<input type="radio" name="intent" checked={intent === "listen"} onChange={() => setIntent("listen")} />
|
||||
<span>
|
||||
<strong>Csak meghallgatást kérek</strong>
|
||||
<span className="hint">Nem kérek tanácsot, jólesne, ha valaki meghallgatna.</span>
|
||||
</span>
|
||||
</label>
|
||||
<label className="fnew-intent">
|
||||
<input type="radio" name="intent" checked={intent === "advice"} onChange={() => setIntent("advice")} />
|
||||
<span>
|
||||
<strong>Tanácsot, véleményt kérek</strong>
|
||||
<span className="hint">Kíváncsi vagyok, ti mit gondoltok, mit tennétek.</span>
|
||||
</span>
|
||||
</label>
|
||||
{!listening && (
|
||||
<label className="fnew-intent">
|
||||
<input type="radio" name="intent" checked={intent === ""} onChange={() => setIntent("")} />
|
||||
<span>
|
||||
<strong>Csak beszélgetnék</strong>
|
||||
<span className="hint">Egy téma, egy gondolat, egy élmény.</span>
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<div className="field">
|
||||
<label htmlFor="fnew-title">Cím</label>
|
||||
<input
|
||||
id="fnew-title"
|
||||
className="inp"
|
||||
value={title}
|
||||
onChange={(e) => withEmoji(e, setTitle)}
|
||||
maxLength={120}
|
||||
required
|
||||
placeholder="Miről szeretnél beszélgetni?"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="field">
|
||||
<label htmlFor="fnew-body">Az első hozzászólás</label>
|
||||
<textarea
|
||||
id="fnew-body"
|
||||
className="fc-text"
|
||||
rows={8}
|
||||
value={body}
|
||||
onChange={(e) => withEmoji(e, setBody)}
|
||||
maxLength={10000}
|
||||
required
|
||||
placeholder={intent === "listen" ? "Írd le, ami benned van…" : "Írd le a gondolataidat…"}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p className="hint">
|
||||
Írás előtt érdemes elolvasni a <Link href="/aszf#forum">fórum házirendjét</Link>: tisztelettel, kéretlen tanács
|
||||
és hirdetés nélkül.
|
||||
</p>
|
||||
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<button type="submit" className="btn btn-primary" disabled={busy || !title.trim() || !body.trim() || !topic}>
|
||||
{busy ? "Küldés…" : "Szál indítása"}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import type { ForumTopic, ForumViewer, ShareCardData } from "@/lib/forum";
|
||||
import { forumGet } from "@/lib/forumServer";
|
||||
|
||||
import { NewThreadForm } from "./NewThreadForm";
|
||||
|
||||
export const metadata = { title: "Új szál", robots: { index: false } };
|
||||
|
||||
type Props = { searchParams: Promise<{ tema?: string; kepletkartya?: string }> };
|
||||
|
||||
/** Starting a thread: a nickname first, then topic, wish, title and text. */
|
||||
export default async function NewThreadPage({ searchParams }: Props) {
|
||||
const { tema, kepletkartya } = await searchParams;
|
||||
const query = new URLSearchParams();
|
||||
if (tema) query.set("tema", tema);
|
||||
if (kepletkartya) query.set("kepletkartya", kepletkartya);
|
||||
const back = `/forum/uj${query.size ? `?${query}` : ""}`;
|
||||
const res = await forumGet<{ topics: ForumTopic[] }>("/v1/forum/topics");
|
||||
const nav = await forumGet<{ viewer: ForumViewer }>("/v1/forum/nav");
|
||||
const viewer = nav.ok ? nav.data.viewer : null;
|
||||
if (!viewer?.logged_in) redirect(`/belepes?vissza=${encodeURIComponent(back)}`);
|
||||
if (viewer.needs_nickname) redirect(`/forum/beallitasok?vissza=${encodeURIComponent(back)}`);
|
||||
const topics = res.ok ? res.data.topics.filter((t) => t.readable && !t.archived) : [];
|
||||
const initial = topics.find((t) => t.slug === tema)?.slug ?? topics[0]?.slug ?? "";
|
||||
// A question about one's chart: the share made for it on the chart page.
|
||||
const card = kepletkartya
|
||||
? await forumGet<ShareCardData>(`/v1/forum/share-card/${encodeURIComponent(kepletkartya)}`).catch(() => null)
|
||||
: null;
|
||||
return (
|
||||
<div className="fh">
|
||||
<h1 className="fpage-title">Új szál</h1>
|
||||
{viewer.member?.banned ? (
|
||||
<p className="fh-banner fh-banner-warn">Most nem írhatsz a fórumba.</p>
|
||||
) : (
|
||||
<NewThreadForm
|
||||
topics={topics}
|
||||
initialTopic={initial}
|
||||
share={card?.ok && kepletkartya ? { slug: kepletkartya, card: card.data } : null}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { AuthorLine } from "@/components/forum/AuthorLine";
|
||||
import { Avatar } from "@/components/forum/Avatar";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { type ConversationItem, ago } from "@/lib/forum";
|
||||
|
||||
export function Conversations({ initial }: { initial: ConversationItem[] }) {
|
||||
const router = useRouter();
|
||||
const [items, setItems] = useState(initial);
|
||||
// New messages and requests show up while the list is open.
|
||||
useEffect(() => setItems(initial), [initial]);
|
||||
useEffect(() => {
|
||||
const live = () => router.refresh();
|
||||
window.addEventListener("forum:live", live);
|
||||
return () => window.removeEventListener("forum:live", live);
|
||||
}, [router]);
|
||||
const [busy, setBusy] = useState<number | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function answer(c: ConversationItem, action: "accept" | "decline" | "block" | "unblock") {
|
||||
setBusy(c.id);
|
||||
setError(null);
|
||||
try {
|
||||
await api(`/forum/conversations/${c.id}/${action === "unblock" ? "block" : action}`, {
|
||||
method: action === "unblock" ? "DELETE" : "POST",
|
||||
});
|
||||
if (action === "accept") {
|
||||
router.push(`/forum/uzenetek/${c.id}`);
|
||||
router.refresh();
|
||||
return;
|
||||
}
|
||||
setItems((list) => list.filter((x) => x.id !== c.id));
|
||||
router.refresh();
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
|
||||
const incoming = items.filter((c) => c.state === "incoming");
|
||||
const open = items.filter((c) => c.state === "accepted");
|
||||
const sent = items.filter((c) => c.state === "outgoing" || c.state === "expired");
|
||||
const blocked = items.filter((c) => c.state === "blocked_by_me");
|
||||
|
||||
return (
|
||||
<>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{incoming.length > 0 && (
|
||||
<section className="fh-section" aria-labelledby="fmsg-in">
|
||||
<h2 id="fmsg-in" className="fmsg-h">
|
||||
Kérések
|
||||
</h2>
|
||||
{incoming.map((c) => (
|
||||
<article key={c.id} className="fh-card fmsg-request">
|
||||
<AuthorLine author={c.other} time={c.created_at} />
|
||||
<p className="fmsg-intro">„{c.intro}”</p>
|
||||
<div className="fmsg-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-sm"
|
||||
disabled={busy === c.id}
|
||||
onClick={() => answer(c, "accept")}
|
||||
>
|
||||
Elfogadom
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
disabled={busy === c.id}
|
||||
onClick={() => answer(c, "decline")}
|
||||
>
|
||||
Nem most
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost btn-sm"
|
||||
disabled={busy === c.id}
|
||||
onClick={() => window.confirm("Letiltod? Nem küldhet neked több kérést.") && answer(c, "block")}
|
||||
>
|
||||
Letiltom
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
|
||||
<section className="fh-section" aria-labelledby="fmsg-open">
|
||||
<h2 id="fmsg-open" className="fmsg-h">
|
||||
Beszélgetések
|
||||
</h2>
|
||||
{open.length === 0 ? (
|
||||
<p className="fh-card fh-empty">
|
||||
Még nincs beszélgetésed. Egy tag profilján kezdeményezhetsz egyet, ha már elérted a Kereső rangot.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="fh-card fh-flush ft-list">
|
||||
{open.map((c) => (
|
||||
<li key={c.id}>
|
||||
<Link href={`/forum/uzenetek/${c.id}`} className="ft-row fmsg-row">
|
||||
<Avatar avatar={c.other?.avatar} size={40} online={c.other?.online} />
|
||||
<span className="ft-main">
|
||||
<span className="ft-title">{c.other?.nickname ?? "Törölt tag"}</span>
|
||||
<span className="ft-excerpt">
|
||||
{c.last_message
|
||||
? `${c.last_message.mine ? "Te: " : ""}${c.last_message.excerpt}`
|
||||
: "Még nincs üzenet."}
|
||||
</span>
|
||||
</span>
|
||||
<span className="fmsg-when">
|
||||
{c.last_message_at && (
|
||||
<time suppressHydrationWarning dateTime={c.last_message_at}>
|
||||
{ago(c.last_message_at)}
|
||||
</time>
|
||||
)}
|
||||
{c.unread > 0 && <span className="ft-new">{c.unread} új</span>}
|
||||
</span>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{sent.length > 0 && (
|
||||
<section className="fh-section" aria-labelledby="fmsg-sent">
|
||||
<h2 id="fmsg-sent" className="fmsg-h">
|
||||
Elküldött kérések
|
||||
</h2>
|
||||
<ul className="fh-card fh-flush ft-list">
|
||||
{sent.map((c) => (
|
||||
<li key={c.id} className="ft-row fmsg-row">
|
||||
<Avatar avatar={c.other?.avatar} size={32} />
|
||||
<span className="ft-main">
|
||||
<span className="ft-title">{c.other?.nickname ?? "Törölt tag"}</span>
|
||||
<span className="ft-excerpt">„{c.intro}”</span>
|
||||
</span>
|
||||
<span className="hint">{c.state === "expired" ? "Lejárt" : "Válaszra vár"}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{blocked.length > 0 && (
|
||||
<section className="fh-section" aria-labelledby="fmsg-blocked">
|
||||
<h2 id="fmsg-blocked" className="fmsg-h">
|
||||
Letiltottak
|
||||
</h2>
|
||||
<ul className="fh-card fh-flush ft-list">
|
||||
{blocked.map((c) => (
|
||||
<li key={c.id} className="ft-row fmsg-row">
|
||||
<Avatar avatar={c.other?.avatar} size={32} />
|
||||
<span className="ft-main">
|
||||
<span className="ft-title">{c.other?.nickname ?? "Törölt tag"}</span>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
disabled={busy === c.id}
|
||||
onClick={() => answer(c, "unblock")}
|
||||
>
|
||||
Tiltás feloldása
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { Avatar } from "@/components/forum/Avatar";
|
||||
import { RankBadge } from "@/components/forum/Badges";
|
||||
import { Composer } from "@/components/forum/Composer";
|
||||
import { PostBody } from "@/components/forum/PostBody";
|
||||
import type { LiveNotice } from "@/components/forum/ForumNav";
|
||||
import { ReportButton } from "@/components/forum/ReportButton";
|
||||
import { TypingLine, useTypingSender, useTypingWatch } from "@/components/forum/typing";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { type ChatMessage, type ConversationPage, memberHref } from "@/lib/forum";
|
||||
|
||||
/** A safety net: how often an open conversation looks for new messages anyway. */
|
||||
const POLL_MS = 30_000;
|
||||
|
||||
function when(iso: string) {
|
||||
return new Date(iso).toLocaleString("hu-HU", {
|
||||
timeZone: "Europe/Budapest",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
}
|
||||
|
||||
/** One private conversation: the request (to answer, or waiting), then the messages. */
|
||||
export function Chat({ initial }: { initial: ConversationPage }) {
|
||||
const router = useRouter();
|
||||
const [page, setPage] = useState(initial);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const bottom = useRef<HTMLDivElement>(null);
|
||||
const { conversation: c, messages } = page;
|
||||
const base = `/forum/conversations/${c.id}`;
|
||||
const lastId = messages.length ? messages[messages.length - 1].id : 0;
|
||||
const other = c.other?.nickname ?? "Törölt tag";
|
||||
const typingNow = useTypingWatch("conversation", initial.conversation.id);
|
||||
const imTyping = useTypingSender("conversation", initial.conversation.id);
|
||||
|
||||
useEffect(() => {
|
||||
if (lastId) api(`${base}/read`, { body: { message_id: lastId } }).catch(() => {});
|
||||
bottom.current?.scrollIntoView({ block: "end" });
|
||||
}, [base, lastId]);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
setPage(await api<ConversationPage>(base));
|
||||
} catch {
|
||||
/* retried on the next round */
|
||||
}
|
||||
}, [base]);
|
||||
|
||||
useEffect(() => {
|
||||
// The live connection rings for this conversation (a message, or the request answered).
|
||||
const live = (e: Event) => {
|
||||
const notice = (e as CustomEvent<LiveNotice>).detail;
|
||||
if (notice.t === "conversation" && notice.id === c.id) void refresh();
|
||||
};
|
||||
window.addEventListener("forum:live", live);
|
||||
const timer =
|
||||
c.state === "accepted"
|
||||
? window.setInterval(() => {
|
||||
if (document.visibilityState === "visible") void refresh();
|
||||
}, POLL_MS)
|
||||
: undefined;
|
||||
return () => {
|
||||
window.removeEventListener("forum:live", live);
|
||||
window.clearInterval(timer);
|
||||
};
|
||||
}, [c.id, c.state, refresh]);
|
||||
|
||||
async function run(work: () => Promise<unknown>) {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await work();
|
||||
return true;
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
return false;
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function send(text: string) {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const msg = await api<ChatMessage>(`${base}/messages`, { body: { body: text } });
|
||||
setPage((p) => ({ ...p, messages: [...p.messages, msg] }));
|
||||
return true;
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
return false;
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function answer(action: "accept" | "decline" | "block" | "unblock") {
|
||||
const ok = await run(() =>
|
||||
api(`${base}/${action === "unblock" ? "block" : action}`, { method: action === "unblock" ? "DELETE" : "POST" }),
|
||||
);
|
||||
if (!ok) return;
|
||||
if (action === "decline") {
|
||||
router.push("/forum/uzenetek");
|
||||
router.refresh();
|
||||
return;
|
||||
}
|
||||
await refresh();
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fchat">
|
||||
<nav className="forum-crumbs" aria-label="Morzsamenü">
|
||||
<Link href="/forum/uzenetek">Üzenetek</Link>
|
||||
</nav>
|
||||
<header className="fchat-head">
|
||||
<Avatar avatar={c.other?.avatar} size={44} online={c.other?.online} />
|
||||
<div className="fchat-who">
|
||||
{c.other ? (
|
||||
<Link href={memberHref(c.other.nickname)} className="fa-name">
|
||||
{other}
|
||||
</Link>
|
||||
) : (
|
||||
<span className="fa-name muted">{other}</span>
|
||||
)}
|
||||
{c.other && <RankBadge rank={c.other.rank} name={c.other.rank_name} />}
|
||||
</div>
|
||||
{c.state === "accepted" && (
|
||||
<details className="ftv-mod">
|
||||
<summary className="btn btn-sm btn-ghost">Továbbiak</summary>
|
||||
<div className="ftv-mod-menu">
|
||||
<button
|
||||
type="button"
|
||||
className="danger"
|
||||
onClick={() => window.confirm(`Letiltod ${other} tagot? Nem írhat neked többet.`) && answer("block")}
|
||||
>
|
||||
Letiltás
|
||||
</button>
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
</header>
|
||||
|
||||
<p className="fchat-intro">
|
||||
<span className="hint">{c.requested_by_me ? "A kérésed" : `${other} kérése`}:</span> „{c.intro}”
|
||||
</p>
|
||||
|
||||
{c.state === "incoming" && (
|
||||
<div className="fh-card fmsg-request">
|
||||
<p>{other} szeretne beszélgetni veled.</p>
|
||||
<div className="fmsg-actions">
|
||||
<button type="button" className="btn btn-primary btn-sm" disabled={busy} onClick={() => answer("accept")}>
|
||||
Elfogadom
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm" disabled={busy} onClick={() => answer("decline")}>
|
||||
Nem most
|
||||
</button>
|
||||
<button type="button" className="btn btn-ghost btn-sm" disabled={busy} onClick={() => answer("block")}>
|
||||
Letiltom
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{(c.state === "outgoing" || c.state === "expired") && (
|
||||
<p className="fh-card fh-empty">
|
||||
{c.state === "expired"
|
||||
? "A kérésedre nem jött válasz, és lejárt."
|
||||
: `A kérésedet elküldtük. Ha ${other} elfogadja, itt tudtok beszélgetni.`}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{messages.length > 0 && (
|
||||
<ol className="fchat-list">
|
||||
{messages.map((m) => (
|
||||
<li key={m.id} className={m.mine ? "fchat-msg fchat-mine" : "fchat-msg"}>
|
||||
<div className="fchat-bubble">
|
||||
<PostBody text={m.body} />
|
||||
</div>
|
||||
<span className="fchat-meta">
|
||||
<time suppressHydrationWarning dateTime={m.created_at}>
|
||||
{when(m.created_at)}
|
||||
</time>
|
||||
{!m.mine && <ReportButton path={`/forum/messages/${m.id}/report`} className="fchat-report" />}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
)}
|
||||
{c.state === "accepted" && <TypingLine text={typingNow} />}
|
||||
<div ref={bottom} />
|
||||
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{c.state === "accepted" && (
|
||||
<div className="fchat-compose">
|
||||
<Composer
|
||||
onTyping={imTyping}
|
||||
id="uzenet"
|
||||
label="Üzeneted"
|
||||
placeholder="Írj üzenetet…"
|
||||
rows={2}
|
||||
busy={busy}
|
||||
onSubmit={send}
|
||||
/>
|
||||
<p className="hint">
|
||||
Csak szöveg és emoji. A linkek nem kattinthatók. A moderátorok csak jelentett üzenetet látnak.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{c.state === "blocked_by_me" && (
|
||||
<div className="fh-card">
|
||||
<p>Letiltottad. Nem írhat neked, és te sem neki.</p>
|
||||
<button type="button" className="btn btn-sm" disabled={busy} onClick={() => answer("unblock")}>
|
||||
Tiltás feloldása
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
|
||||
import type { ConversationPage } from "@/lib/forum";
|
||||
import { forumGet } from "@/lib/forumServer";
|
||||
|
||||
import { Chat } from "./Chat";
|
||||
|
||||
export const metadata = { title: "Beszélgetés", robots: { index: false } };
|
||||
|
||||
type Props = { params: Promise<{ id: string }> };
|
||||
|
||||
export default async function ConversationView({ params }: Props) {
|
||||
const { id } = await params;
|
||||
if (!/^\d{1,15}$/.test(id)) notFound();
|
||||
const res = await forumGet<ConversationPage>(`/v1/forum/conversations/${id}`);
|
||||
if (!res.ok) {
|
||||
if (res.status === 401) redirect(`/belepes?vissza=/forum/uzenetek/${id}`);
|
||||
notFound();
|
||||
}
|
||||
return <Chat initial={res.data} />;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import type { ConversationItem } from "@/lib/forum";
|
||||
import { forumGet } from "@/lib/forumServer";
|
||||
|
||||
import { Conversations } from "./Conversations";
|
||||
|
||||
export const metadata = { title: "Üzenetek", robots: { index: false } };
|
||||
|
||||
/** Private messages: requests to answer, conversations, requests sent. */
|
||||
export default async function MessagesPage() {
|
||||
const res = await forumGet<{ conversations: ConversationItem[] }>("/v1/forum/conversations");
|
||||
if (!res.ok) redirect("/belepes?vissza=/forum/uzenetek");
|
||||
return (
|
||||
<div className="fh fmsg-page">
|
||||
<h1 className="fpage-title">Üzenetek</h1>
|
||||
<p className="muted">
|
||||
Privát beszélgetés csak kéréssel indulhat. A kérést elfogadhatod, csendben elutasíthatod (a küldő ezt nem
|
||||
látja), vagy letilthatod a küldőt.
|
||||
</p>
|
||||
<Conversations initial={res.data.conversations} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import { api } from "@/lib/api";
|
||||
|
||||
/** "Mind olvasott": the answers stay in the list, the count on the tab goes. */
|
||||
export function ReadAll() {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost btn-sm"
|
||||
disabled={busy}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await api("/forum/replies/read", { method: "POST" });
|
||||
window.dispatchEvent(new Event("forum:nav"));
|
||||
router.refresh();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Mind olvasott
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { Avatar } from "@/components/forum/Avatar";
|
||||
import { RepliesTabs } from "@/components/forum/RepliesTabs";
|
||||
import { type ReplyEntry, ago, threadHref } from "@/lib/forum";
|
||||
import { forumGet } from "@/lib/forumServer";
|
||||
|
||||
import { ReadAll } from "./ReadAll";
|
||||
|
||||
export const metadata = { title: "Válaszok", robots: { index: false } };
|
||||
|
||||
const KIND: Record<ReplyEntry["kind"], string> = {
|
||||
reply: "válaszolt neked",
|
||||
thread: "válaszolt a száladban",
|
||||
mention: "megemlített",
|
||||
};
|
||||
|
||||
/** The answers to the member, newest first; the unread ones stand out. */
|
||||
export default async function RepliesPage({ searchParams }: { searchParams: Promise<{ oldal?: string }> }) {
|
||||
const page = Math.max(1, Number((await searchParams).oldal) || 1);
|
||||
const res = await forumGet<{ replies: ReplyEntry[]; unread: number; more: boolean }>(
|
||||
`/v1/forum/replies?page=${page}`,
|
||||
);
|
||||
if (!res.ok) redirect("/belepes?vissza=/forum/valaszok");
|
||||
const { replies, unread, more } = res.data;
|
||||
return (
|
||||
<div className="fh">
|
||||
<h1 className="fpage-title">Válaszok</h1>
|
||||
<div className="frep-head">
|
||||
<RepliesTabs current="replies" />
|
||||
{unread > 0 && <ReadAll />}
|
||||
</div>
|
||||
<p className="muted">
|
||||
Ha valaki a hozzászólásodra vagy a száladban válaszol, vagy megemlít. A menüben csak ezek száma látszik.
|
||||
</p>
|
||||
{replies.length === 0 ? (
|
||||
<p className="fh-card fh-empty">Még nem válaszolt neked senki. Ha valaki ír neked, itt látod.</p>
|
||||
) : (
|
||||
<ul className="fh-card fh-flush fanswers">
|
||||
{replies.map((r) => (
|
||||
<li key={r.id}>
|
||||
<Link href={threadHref(r.thread, r.id)} className={r.unread ? "fanswer fanswer-new" : "fanswer"}>
|
||||
<Avatar avatar={r.author?.avatar} size={36} online={r.author?.online} />
|
||||
<span className="fanswer-text">
|
||||
<span className="fanswer-who">
|
||||
<strong>{r.author?.nickname ?? "Törölt tag"}</strong> {KIND[r.kind]}
|
||||
{r.unread && <span className="fa-badge fa-badge-new">új</span>}
|
||||
</span>
|
||||
<span className="fanswer-thread">{r.thread.title}</span>
|
||||
<span className="fanswer-excerpt">{r.excerpt}</span>
|
||||
</span>
|
||||
<time className="fanswer-time" suppressHydrationWarning dateTime={r.created_at}>
|
||||
{ago(r.created_at)}
|
||||
</time>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{(page > 1 || more) && (
|
||||
<nav className="forum-pager" aria-label="Lapozás">
|
||||
{page > 1 ? <Link href={`/forum/valaszok?oldal=${page - 1}`}>‹ Újabbak</Link> : <span />}
|
||||
<span className="hint">{page}. oldal</span>
|
||||
{more ? <Link href={`/forum/valaszok?oldal=${page + 1}`}>Régebbiek ›</Link> : <span />}
|
||||
</nav>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -834,6 +834,9 @@ a.pair-row:hover strong { color: var(--gold); }
|
||||
.qdock-fab-label { display: none; }
|
||||
.qdock-dot { left: 42px; }
|
||||
.qdock-panel { inset: 0; width: 100%; height: 100dvh; border: 0; border-radius: 0; }
|
||||
/* While typing: only the part of the screen above the keyboard (KeyboardSafe). */
|
||||
.kb-open .qdock-panel { top: var(--vv-top, 0px); bottom: auto; height: var(--vv-height, 100dvh); }
|
||||
.kb-open .qdock-fab { display: none; }
|
||||
body.qdock-open { overflow: hidden; }
|
||||
}
|
||||
@media (max-width: 480px) {
|
||||
@@ -1349,6 +1352,15 @@ span.tarot-fan-card { cursor: default; }
|
||||
.lp-free-card:hover { border-color: var(--gold); color: var(--ink); }
|
||||
.lp-free-card strong { font-family: var(--font-display); font-size: 24px; font-weight: 600; }
|
||||
.lp-free-go { color: var(--gold); font-weight: 500; margin-top: auto; }
|
||||
/* The forum, first and across the whole row. */
|
||||
.lp-free-featured { grid-column: 1 / -1; border-color: var(--gold); background: rgba(217, 180, 106, 0.07); gap: 10px; }
|
||||
.lp-free-featured strong { font-size: 30px; }
|
||||
.lp-free-featured-label {
|
||||
align-self: flex-start; font-size: 12px; font-weight: 600; letter-spacing: 1.2px; text-transform: uppercase;
|
||||
color: var(--gold-ink); background: var(--gold); border-radius: 999px; padding: 2px 10px;
|
||||
}
|
||||
.lp-free-featured-text { max-width: 760px; font-size: 17px; color: var(--ink-2); }
|
||||
.lp-free-featured-quiet { max-width: 760px; color: var(--muted); font-style: italic; }
|
||||
.calc-result-head { margin-top: 32px; }
|
||||
.calc-links ul { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }
|
||||
.calc-links li { font-size: 15px; }
|
||||
@@ -1784,3 +1796,10 @@ span.tarot-fan-card { cursor: default; }
|
||||
.lp-gift-text { align-items: center; }
|
||||
.lp-gift-card { width: 160px; }
|
||||
}
|
||||
|
||||
/* "Kérdezek róla a fórumon" (chart, forecast and comparison pages). */
|
||||
.ask-forum { display: inline-flex; align-items: center; gap: 8px; }
|
||||
.ask-forum svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.ask-forum-card { display: flex; flex-direction: column; align-items: flex-start; gap: 10px; }
|
||||
.ask-forum-body { display: flex; flex-direction: column; gap: 12px; }
|
||||
.ask-forum-actions { display: flex; justify-content: flex-end; gap: 8px; flex-wrap: wrap; margin-top: 4px; }
|
||||
|
||||
@@ -2,11 +2,13 @@ import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { AskOnForum } from "@/components/AskOnForum";
|
||||
import { ChartWheel } from "@/components/ChartWheel";
|
||||
import { DetailedAnalysis } from "@/components/DetailedAnalysis";
|
||||
import { ForecastKeys, ForecastTimeline, ForecastTransits, longDay } from "@/components/ForecastViews";
|
||||
import { Tabs } from "@/components/Tabs";
|
||||
import { payMethod } from "@/lib/payments";
|
||||
import { forumEnabled } from "@/lib/forumServer";
|
||||
import { backendGet, requireMe } from "@/lib/server";
|
||||
import type { Analysis, Chart, ForecastDetail, ForecastList, PublicConfig } from "@/lib/types";
|
||||
|
||||
@@ -94,6 +96,12 @@ export default async function ForecastPage({
|
||||
)}
|
||||
<div className="field chart-side">
|
||||
<ForecastKeys forecast={fc} solarReturn={sr} />
|
||||
{forumEnabled() && (
|
||||
<div className="card ask-forum-card">
|
||||
<p className="muted">Kérdésed van az évedről? Kérdezd meg a fórum tagjait.</p>
|
||||
<AskOnForum kind="forecast" targetId={forecast.id} />
|
||||
</div>
|
||||
)}
|
||||
{(list.years.length > 0 || others.length > 0) && (
|
||||
<details className="card">
|
||||
<summary>Másik év vagy helyszín</summary>
|
||||
|
||||
@@ -3,6 +3,7 @@ import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { AspectGrid, AspectList, BigThree, PositionTables } from "@/components/ChartTables";
|
||||
import { AskOnForum } from "@/components/AskOnForum";
|
||||
import { ChartSummary } from "@/components/ChartSummary";
|
||||
import { ChartSwitcher } from "@/components/ChartSwitcher";
|
||||
import { DetailedAnalysis } from "@/components/DetailedAnalysis";
|
||||
@@ -12,6 +13,7 @@ import { SkyToday } from "@/components/SkyToday";
|
||||
import { Tabs } from "@/components/Tabs";
|
||||
import { ASPECTS, ELEMENTS, MODALITIES, MOON_PHASES, countryName, formatBirthDate, pointName } from "@/lib/astro";
|
||||
import { payMethod } from "@/lib/payments";
|
||||
import { forumEnabled } from "@/lib/forumServer";
|
||||
import { backendGet, requireMe } from "@/lib/server";
|
||||
import { loadSky } from "@/lib/sky";
|
||||
import type { Analysis, Chart, ChartListItem, PublicConfig } from "@/lib/types";
|
||||
@@ -86,6 +88,12 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
|
||||
referralsLeft={me.referral_rewards.limit - me.referral_rewards.earned}
|
||||
/>
|
||||
<BigThree chart={chart} />
|
||||
{forumEnabled() && (
|
||||
<div className="card ask-forum-card">
|
||||
<p className="muted">Kérdésed van a képletről? Kérdezd meg a fórum tagjait.</p>
|
||||
<AskOnForum kind="chart" targetId={chart.id} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import type { Metadata } from "next";
|
||||
import type { Metadata, Viewport } from "next";
|
||||
import { Cormorant_Garamond, Inter } from "next/font/google";
|
||||
import { Suspense } from "react";
|
||||
|
||||
import { KeyboardSafe } from "@/components/KeyboardSafe";
|
||||
import { NightSky } from "@/components/NightSky";
|
||||
import { NpsBanner } from "@/components/NpsBanner";
|
||||
import { PaymentReturn } from "@/components/PaymentReturn";
|
||||
@@ -30,6 +31,10 @@ export async function generateMetadata(): Promise<Metadata> {
|
||||
};
|
||||
}
|
||||
|
||||
// On Android the opening keyboard shrinks the page instead of covering it
|
||||
// (iOS ignores this; KeyboardSafe handles both).
|
||||
export const viewport: Viewport = { width: "device-width", initialScale: 1, interactiveWidget: "resizes-content" };
|
||||
|
||||
export default async function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
const me = await getMe();
|
||||
// The Moon today in the header (cached for five minutes).
|
||||
@@ -38,6 +43,7 @@ export default async function RootLayout({ children }: { children: React.ReactNo
|
||||
<html lang="hu" className={`${cormorant.variable} ${inter.variable}`}>
|
||||
<body>
|
||||
<NightSky />
|
||||
<KeyboardSafe />
|
||||
<ValidationMessages />
|
||||
{me && <SiteHeader me={me} sky={sky} />}
|
||||
{children}
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { AskOnForum } from "@/components/AskOnForum";
|
||||
import { SignTrio } from "@/components/ChartCard";
|
||||
import { DetailedAnalysis } from "@/components/DetailedAnalysis";
|
||||
import { CompositeTables, CrossGrid, HouseOverlays, InterAspectList, NatureBar } from "@/components/SynastryTables";
|
||||
@@ -9,6 +10,7 @@ import { SynastryLegend, SynastryWheel } from "@/components/SynastryWheel";
|
||||
import { Tabs } from "@/components/Tabs";
|
||||
import { ASPECTS, formatBirthDate } from "@/lib/astro";
|
||||
import { payMethod } from "@/lib/payments";
|
||||
import { forumEnabled } from "@/lib/forumServer";
|
||||
import { backendGet, requireMe } from "@/lib/server";
|
||||
import { sideName, sideTimeKnown } from "@/lib/synastry";
|
||||
import type { Analysis, ChartListItem, PublicConfig, Synastry, SynastrySide } from "@/lib/types";
|
||||
@@ -112,6 +114,12 @@ export default async function ComparisonPage({ params }: { params: Promise<{ id:
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{forumEnabled() && (
|
||||
<div className="card ask-forum-card">
|
||||
<p className="muted">Kérdésed van kettőtök képletéről? Kérdezd meg a fórum tagjait.</p>
|
||||
<AskOnForum kind="synastry" targetId={synastry.id} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
@@ -84,6 +84,41 @@ const DATA: [string, string, string][] = [
|
||||
"Fixing bugs, answering questions",
|
||||
"Legitimate interest (Art. 6(1)(f))",
|
||||
],
|
||||
[
|
||||
"Your forum profile: your nickname (earlier ones for 90 days, so nobody else can take them), your avatar or the picture you uploaded (made smaller, without its hidden data such as the location), introduction, the signs of your chart you share, whether you are a volunteer companion (Kísérő), the Támogató (supporter) badge (if you switch it on, others see that you bought something), whether you were among the first fifteen members (Alapító tag – founder), the invisible mode and your e-mail notification settings",
|
||||
"Taking part in the forum; sharing the signs and the badges is your choice",
|
||||
"Performance of the contract",
|
||||
],
|
||||
[
|
||||
"Your forum threads and posts, your reactions and “Ez segített” (it helped) marks, your points and rank; whom you mentioned (@nickname); what you have read, the threads you follow, and the members you muted",
|
||||
"Running the forum, the ranks, showing what is new",
|
||||
"Performance of the contract",
|
||||
],
|
||||
[
|
||||
"The share link of a chart, yearly forecast or comparison you attach to a forum question",
|
||||
"So that members see what you are asking about; attaching it is your choice",
|
||||
"Performance of the contract",
|
||||
],
|
||||
[
|
||||
"Your requests to join restricted topics (with the few words you add) and your memberships",
|
||||
"Restricted topics: the moderators decide who joins",
|
||||
"Performance of the contract",
|
||||
],
|
||||
[
|
||||
"When you were last on the forum",
|
||||
"The online indicator (green dot); you can turn it off with the invisible mode",
|
||||
"Performance of the contract",
|
||||
],
|
||||
[
|
||||
"Your private conversations: the introductions of requests, accepting, declining or blocking, and the messages",
|
||||
"Private conversations with other members",
|
||||
"Performance of the contract",
|
||||
],
|
||||
[
|
||||
"Reports (who reported what, and why), the moderation log (who decided what, when and why), the length and reason of bans",
|
||||
"Enforcing the house rules, handling reports, keeping decisions traceable",
|
||||
"Legal obligation (Regulation (EU) 2022/2065, the DSA; Art. 6(1)(c)); legitimate interest (Art. 6(1)(f))",
|
||||
],
|
||||
[
|
||||
"IP address, browser details, request times (server logs)",
|
||||
"Security, troubleshooting, preventing abuse",
|
||||
@@ -157,6 +192,24 @@ export default async function PrivacyPolicyPage() {
|
||||
the latest short summary. It shows no name or birth data, search engines do not list it, and you can revoke
|
||||
the link at any time.
|
||||
</p>
|
||||
<p>
|
||||
<strong>Forum:</strong> what you write in the public topics can be seen by anyone, including search engines;
|
||||
the members-only topics are seen only by logged-in users, and the restricted ones only by their approved
|
||||
members. Next to your posts we show your nickname, avatar, rank, the signs you chose to share and the badges
|
||||
you switched on (Kísérő – companion, Támogató – supporter); never your real name, e-mail address or birth data, and never the
|
||||
degrees of your chart. Your private messages are seen only by the two people in the conversation; moderators
|
||||
see a message only when someone reports it, and then only that message and the few before it. Moderators
|
||||
(members appointed by the operator) do not see your real name or e-mail address. If you attach your chart,
|
||||
yearly forecast or a comparison to a question, only logged-in members see it: the drawing with degrees and
|
||||
houses, the short summary or the forecast text, without names, birth date, time or place. A practised
|
||||
astrologer can roughly work out the birth date and time from the degrees, and a forecast's first day is the
|
||||
birthday. You can take it off at any time, and deleting the question ends the link. If a post has a YouTube
|
||||
link, our server fetches the video's title and picture and we show them from our own server: reading the
|
||||
forum sends YouTube nothing about you. If you play the video on the forum, the player loads from YouTube's
|
||||
(Google's) servers (youtube-nocookie.com), which see your IP address and what you play; on a phone, opening
|
||||
it takes you to the YouTube app. The forum rules are in
|
||||
point 8 of the <Link href="/aszf#forum">terms (ÁSZF, in Hungarian)</Link>.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
@@ -173,7 +226,9 @@ export default async function PrivacyPolicyPage() {
|
||||
</ul>
|
||||
<p>
|
||||
<strong>How we use it:</strong> to create your account and recognise you when you sign in; your e-mail address
|
||||
for service e-mails (for example when a reading is ready or an invitation was accepted); your name for display;
|
||||
for service e-mails (for example when a reading is ready, an invitation was accepted, or someone replied on the
|
||||
forum, when someone mentions you there, or the forum's weekly summary, if you asked for these); your name for
|
||||
display;
|
||||
your language for the language of the site and your readings.
|
||||
</p>
|
||||
<p>
|
||||
@@ -222,6 +277,10 @@ export default async function PrivacyPolicyPage() {
|
||||
your questions either. The readings are for entertainment and self-reflection and are not medical,
|
||||
financial, legal or other professional advice.
|
||||
</p>
|
||||
<p>
|
||||
Forum posts and private messages are not sent to artificial intelligence. Should we introduce this later (for
|
||||
example to filter out unsolicited advertising), we will say so here first.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
@@ -287,14 +346,27 @@ export default async function PrivacyPolicyPage() {
|
||||
after that as statistics, without your name and comment.
|
||||
</li>
|
||||
<li>Data needed for invoicing: for the period required by accounting law (8 years).</li>
|
||||
<li>
|
||||
Your forum profile (with your own picture), private conversations, reactions, followed threads and
|
||||
restricted topic memberships: until you delete your account; a declined request is deleted at once.
|
||||
When you delete it, your private conversations are deleted for the other person too. Your threads and
|
||||
posts stay, shown as “Törölt tag” (deleted member), so that the conversations remain readable; to have them
|
||||
deleted as well, write to the e-mail address above.
|
||||
</li>
|
||||
<li>
|
||||
The text of a post removed by a moderator: 1 year, for a possible objection; after that only its place and
|
||||
the reason stay. Closed reports and the reason of expired bans: 1 year; the moderation log: 2 years.
|
||||
</li>
|
||||
<li>Conversation requests never accepted: deleted after 90 days. Your earlier nicknames are reserved for 90 days.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>8. Cookies</h2>
|
||||
<p>
|
||||
We use a single cookie that is strictly necessary for the service (<code>sf_session</code>), which keeps you
|
||||
signed in. We use no advertising or tracking cookies and no analytics.
|
||||
We use a cookie that is strictly necessary for the service (<code>sf_session</code>), which keeps you signed
|
||||
in. If you choose the light or dark theme on the forum, a second cookie (<code>sf_forum_theme</code>) keeps
|
||||
your choice for a year; it stores nothing else. We use no advertising or tracking cookies and no analytics.
|
||||
</p>
|
||||
<p>
|
||||
On the public birth chart page (no account needed), the birth data you enter are sent only for the
|
||||
@@ -310,14 +382,16 @@ export default async function PrivacyPolicyPage() {
|
||||
<h2>9. Your rights</h2>
|
||||
<ul>
|
||||
<li>
|
||||
<strong>Access and portability:</strong> download all your data with one click on the{" "}
|
||||
<Link href="/profil#adataim">Profile</Link> page.
|
||||
<strong>Access and portability:</strong> download all your data, including what you wrote and set on the
|
||||
forum, with one click on the <Link href="/profil#adataim">Profile</Link> page.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Rectification:</strong> change your name and birth data on the Profile page.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Erasure:</strong> delete your account and all your data on the Profile page.
|
||||
<strong>Erasure:</strong> delete your account and all your data on the Profile page. You can delete your
|
||||
own forum posts one by one too; to have the ones kept as “Törölt tag” deleted after your account is gone,
|
||||
write to us.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Restriction and objection:</strong> ask us at the e-mail address above.
|
||||
|
||||
@@ -54,7 +54,24 @@ const AI_SEARCH = [
|
||||
];
|
||||
|
||||
// Logged-in pages redirect anyway; shared links carry noindex.
|
||||
const PRIVATE = ["/api/", "/admin", "/profil", "/kepletek", "/osszevetesek", "/szemelyek", "/szamlak"];
|
||||
const PRIVATE = [
|
||||
"/api/",
|
||||
"/admin",
|
||||
"/profil",
|
||||
"/kepletek",
|
||||
"/osszevetesek",
|
||||
"/szemelyek",
|
||||
"/szamlak",
|
||||
// The forum's own pages (the topics and threads are open).
|
||||
"/forum/beallitasok",
|
||||
"/forum/uzenetek",
|
||||
"/forum/valaszok",
|
||||
"/forum/kovetett",
|
||||
"/forum/moderalas",
|
||||
"/forum/uj",
|
||||
"/forum/kereses",
|
||||
"/forum/leiratkozas",
|
||||
];
|
||||
|
||||
export default async function robots(): Promise<MetadataRoute.Robots> {
|
||||
return {
|
||||
|
||||
@@ -2,13 +2,18 @@ import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { AnalysisView } from "@/components/AnalysisView";
|
||||
import { ChartWheel, WheelLegend } from "@/components/ChartWheel";
|
||||
import { ForecastKeys, ForecastTimeline, ForecastTransits, longDay } from "@/components/ForecastViews";
|
||||
import { InterAspectList, NatureBar } from "@/components/SynastryTables";
|
||||
import { SynastryLegend, SynastryWheel } from "@/components/SynastryWheel";
|
||||
import { Rich } from "@/components/Rich";
|
||||
import { ShareVisit } from "@/components/ShareVisit";
|
||||
import { PublicHeader } from "@/components/SiteHeader";
|
||||
import { SIGNS, signName } from "@/lib/astro";
|
||||
import { getMe } from "@/lib/server";
|
||||
import { bigThree, imageVersion, loadShare, plain, shorten, siteUrl } from "@/lib/share";
|
||||
import { type PublicShare, bigThree, imageVersion, loadShare, plain, shorten, siteUrl } from "@/lib/share";
|
||||
import type { Synastry } from "@/lib/types";
|
||||
|
||||
type Props = { params: Promise<{ slug: string }> };
|
||||
|
||||
@@ -16,6 +21,13 @@ type Props = { params: Promise<{ slug: string }> };
|
||||
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||
const { slug } = await params;
|
||||
const share = await loadShare(slug);
|
||||
if (share?.kind === "synastry" && share.synastry) {
|
||||
return { title: "Megosztott összevetés", robots: { index: false, follow: false } };
|
||||
}
|
||||
if (share?.kind === "forecast" && share.forecast) {
|
||||
const y = share.forecast.year;
|
||||
return { title: `Megosztott éves előrejelzés · ${y}–${y + 1}`, robots: { index: false, follow: false } };
|
||||
}
|
||||
if (!share?.chart) return { title: "A link nem érhető el", robots: { index: false } };
|
||||
const base = await siteUrl();
|
||||
const title = share.summary?.title ?? "Születési képlet";
|
||||
@@ -39,6 +51,12 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||
export default async function SharedChartPage({ params }: Props) {
|
||||
const { slug } = await params;
|
||||
const [share, me] = await Promise.all([loadShare(slug), getMe()]);
|
||||
if (share?.kind === "synastry" && share.synastry) {
|
||||
return <SharedSynastry slug={slug} share={share} loggedIn={me !== null} />;
|
||||
}
|
||||
if (share?.kind === "forecast" && share.forecast) {
|
||||
return <SharedForecast slug={slug} share={share} loggedIn={me !== null} />;
|
||||
}
|
||||
const chart = share?.chart?.chart;
|
||||
if (!share || !chart) notFound();
|
||||
const summary = share.summary;
|
||||
@@ -106,3 +124,109 @@ export default async function SharedChartPage({ params }: Props) {
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** A shared comparison: the two charts on one wheel and the aspects between them, without names. */
|
||||
function SharedSynastry({ slug, share, loggedIn }: { slug: string; share: PublicShare; loggedIn: boolean }) {
|
||||
const s = share.synastry!;
|
||||
const name1 = s.chart1.label ?? "Első képlet";
|
||||
const name2 = s.chart2.label ?? "Második képlet";
|
||||
const time1 = s.chart1.chart.time_known;
|
||||
const time2 = s.chart2.chart.time_known;
|
||||
// The tables read only the result.
|
||||
const synastry = { synastry: s.synastry } as unknown as Synastry;
|
||||
return (
|
||||
<>
|
||||
<ShareVisit slug={slug} />
|
||||
{!loggedIn && <PublicHeader />}
|
||||
<main className="page" style={{ maxWidth: 1180 }}>
|
||||
<div className="page-head">
|
||||
<span className="eyebrow">Megosztott összevetés</span>
|
||||
<h1>Két képlet egymásra vetítve</h1>
|
||||
</div>
|
||||
<section className="chart-layout" aria-label="Kettős képletrajz">
|
||||
<div className="card chart-wheel-card">
|
||||
<SynastryWheel
|
||||
chart1={s.chart1.chart}
|
||||
chart2={s.chart2.chart}
|
||||
time1={time1}
|
||||
time2={time2}
|
||||
aspects={s.synastry.aspects}
|
||||
name1={name1}
|
||||
name2={name2}
|
||||
/>
|
||||
<SynastryLegend name1={name1} name2={name2} time1={time1} />
|
||||
</div>
|
||||
<div className="field chart-side">
|
||||
<div className="card summary-card">
|
||||
<span className="eyebrow">Számokban</span>
|
||||
<h2 className="summary-title">{s.synastry.summary.aspect_count} fényszög a két képlet között</h2>
|
||||
<NatureBar summary={s.synastry.summary} />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section className="card" aria-label="Fényszögek">
|
||||
<h2>Fényszögek</h2>
|
||||
<InterAspectList synastry={synastry} name1={name1} name2={name2} />
|
||||
</section>
|
||||
<p className="hint">Ezt az összevetést a tulajdonosa osztotta meg, nevek és születési adatok nélkül.</p>
|
||||
</main>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** A shared yearly forecast: the year's keys, timeline and transits, and the detailed text if it was written. */
|
||||
function SharedForecast({ slug, share, loggedIn }: { slug: string; share: PublicShare; loggedIn: boolean }) {
|
||||
const f = share.forecast!;
|
||||
const fc = f.forecast;
|
||||
const sr = f.solar_return;
|
||||
const text = share.analysis?.content ?? null;
|
||||
return (
|
||||
<>
|
||||
<ShareVisit slug={slug} />
|
||||
{!loggedIn && <PublicHeader />}
|
||||
<main className="page" style={{ maxWidth: 1180 }}>
|
||||
<div className="page-head">
|
||||
<span className="eyebrow">Megosztott éves előrejelzés</span>
|
||||
<h1>
|
||||
{f.year}–{f.year + 1}
|
||||
</h1>
|
||||
<p className="muted">
|
||||
{longDay(fc.start)} – {longDay(fc.end)}
|
||||
</p>
|
||||
</div>
|
||||
<section className="chart-layout" aria-label="Szolár képlet">
|
||||
{sr ? (
|
||||
<div className="card chart-wheel-card">
|
||||
<ChartWheel chart={sr} timeKnown title="Szolár képlet" />
|
||||
<p className="hint">Szolár képlet: a Nap ekkor ér vissza pontosan a születéskori helyére.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="card">
|
||||
<p className="muted">Szolár képlet nincs, mert a születési idő ismeretlen.</p>
|
||||
</div>
|
||||
)}
|
||||
<div className="field chart-side">
|
||||
<ForecastKeys forecast={fc} solarReturn={sr} />
|
||||
</div>
|
||||
</section>
|
||||
{text && (
|
||||
<section className="card" aria-label="Előrejelzés">
|
||||
<AnalysisView content={text} kind="forecast" language={share.analysis?.language} />
|
||||
</section>
|
||||
)}
|
||||
<section className="card" aria-label="Idővonal">
|
||||
<h2>Idővonal</h2>
|
||||
<ForecastTimeline forecast={fc} />
|
||||
</section>
|
||||
<section className="card" aria-label="Tranzitok">
|
||||
<h2>Tranzitok</h2>
|
||||
<ForecastTransits forecast={fc} />
|
||||
</section>
|
||||
<p className="hint">
|
||||
Ezt az előrejelzést a tulajdonosa osztotta meg, név, születési adatok és helyszín nélkül.
|
||||
{text && " A szöveget mesterséges intelligencia írta a képlet alapján."}
|
||||
</p>
|
||||
</main>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { MetadataRoute } from "next";
|
||||
|
||||
import { ZODIAC } from "@/content/zodiac";
|
||||
import { loadCelebrities } from "@/lib/celebrities";
|
||||
import { forumEnabled, forumSitemap } from "@/lib/forumServer";
|
||||
import { currentYear } from "@/lib/sky";
|
||||
import { siteUrl } from "@/lib/share";
|
||||
|
||||
@@ -10,7 +11,7 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
|
||||
const base = await siteUrl();
|
||||
const privacy = { languages: { hu: `${base}/adatvedelem`, en: `${base}/privacy` } };
|
||||
// The sitemap still works when the backend does not answer.
|
||||
const people = await loadCelebrities().catch(() => []);
|
||||
const [people, forum] = await Promise.all([loadCelebrities().catch(() => []), forumSitemap()]);
|
||||
const next = currentYear() + 1;
|
||||
return [
|
||||
{ url: `${base}/`, changeFrequency: "weekly", priority: 1 },
|
||||
@@ -30,6 +31,20 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
|
||||
changeFrequency: "monthly" as const,
|
||||
priority: 0.6,
|
||||
})),
|
||||
// The forum's public topics and threads (the members-only ones are not listed).
|
||||
...(forumEnabled() ? [{ url: `${base}/forum`, changeFrequency: "hourly" as const, priority: 0.8 }] : []),
|
||||
...forum.topics.map((t) => ({
|
||||
url: `${base}/forum/${t.slug}`,
|
||||
lastModified: t.updated ?? undefined,
|
||||
changeFrequency: "daily" as const,
|
||||
priority: 0.6,
|
||||
})),
|
||||
...forum.threads.map((t) => ({
|
||||
url: `${base}/forum/szal/${t.id}-${t.slug}`,
|
||||
lastModified: t.updated,
|
||||
changeFrequency: "weekly" as const,
|
||||
priority: 0.5,
|
||||
})),
|
||||
{ url: `${base}/aszf`, changeFrequency: "yearly", priority: 0.2 },
|
||||
|
||||
{ url: `${base}/kapcsolat`, changeFrequency: "yearly", priority: 0.2 },
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
|
||||
import { Modal } from "./Modal";
|
||||
|
||||
type Kind = "chart" | "synastry" | "forecast";
|
||||
|
||||
const WHAT: Record<Kind, { button: string; shown: string; extra?: string }> = {
|
||||
chart: {
|
||||
button: "Kérdezek róla a fórumon",
|
||||
shown: "a képleted rajzát a bolygók fokaival és házaival, és a rövid összefoglalót, ha már van",
|
||||
},
|
||||
synastry: {
|
||||
button: "Kérdezek róla a fórumon",
|
||||
shown: "a két képlet közös rajzát, a köztük lévő fényszögeket és házakat",
|
||||
extra: "A másik fél nevét és születési adatait sem mutatjuk, de az ő képlete is látszik.",
|
||||
},
|
||||
forecast: {
|
||||
button: "Kérdezek róla a fórumon",
|
||||
shown: "az év kulcsait, az idővonalat, a tranzitokat és a részletes előrejelzést, ha már elkészült",
|
||||
extra: "Az előrejelzés éve a születésnapodon kezdődik, ezért abból a születésnapod kiderül.",
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* "Kérdezek róla a fórumon": a link made for the forum (no birth data, no
|
||||
* names), then a new thread in "Égbolt és képletek" with it attached.
|
||||
*/
|
||||
export function AskOnForum({ kind, targetId }: { kind: Kind; targetId: string }) {
|
||||
const router = useRouter();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const what = WHAT[kind];
|
||||
|
||||
async function go() {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const share = await api<{ slug: string }>("/shares", { body: { kind, target_id: targetId, for_forum: true } });
|
||||
router.push(`/forum/uj?tema=egbolt-es-kepletek&kepletkartya=${encodeURIComponent(share.slug)}`);
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<button type="button" className="btn btn-sm ask-forum" onClick={() => setOpen(true)}>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d="M4 5h12a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H9l-4 3v-3H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2z" />
|
||||
<path d="M20 9h1a1 1 0 0 1 1 1v8l-3-2h-6" />
|
||||
</svg>
|
||||
{what.button}
|
||||
</button>
|
||||
{open && (
|
||||
<Modal title="Kérdés a fórumon" onClose={() => setOpen(false)}>
|
||||
<div className="ask-forum-body">
|
||||
<p>
|
||||
A kérdésed mellé csatoljuk {what.shown}. A fórum belépett tagjai látják, a látogatók és a keresők nem.
|
||||
</p>
|
||||
<p className="hint">
|
||||
Neved, születési dátumod, időd és helyed nem kerül ki.
|
||||
{what.extra && ` ${what.extra}`} A fokokból egy jártas asztrológus nagyjából kiszámolhatja a születési
|
||||
napot és időt. A csatolt képletet bármikor leveheted a kérdésedről, és ha törlöd a kérdést, a link is
|
||||
megszűnik.
|
||||
</p>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<div className="ask-forum-actions">
|
||||
<button type="button" className="btn btn-ghost" onClick={() => setOpen(false)}>
|
||||
Mégse
|
||||
</button>
|
||||
<button type="button" className="btn btn-primary" disabled={busy} onClick={go}>
|
||||
{busy ? "Egy pillanat…" : "Tovább a kérdéshez"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
|
||||
const NOT_TYPED = new Set([
|
||||
"checkbox",
|
||||
"radio",
|
||||
"button",
|
||||
"submit",
|
||||
"reset",
|
||||
"range",
|
||||
"file",
|
||||
"color",
|
||||
"image",
|
||||
"hidden",
|
||||
]);
|
||||
|
||||
function typedInto(el: Element | null): el is HTMLElement {
|
||||
if (el instanceof HTMLTextAreaElement) return true;
|
||||
if (el instanceof HTMLInputElement) return !NOT_TYPED.has(el.type);
|
||||
return el instanceof HTMLElement && el.isContentEditable;
|
||||
}
|
||||
|
||||
/**
|
||||
* On phones the on-screen keyboard must not cover the box being typed in.
|
||||
* While a text field has the focus: `kb-open` on <html> (the forum's bottom
|
||||
* menu and other fixed bars step aside), `--vv-top` and `--vv-height` give
|
||||
* the part of the screen the keyboard leaves free (for full-screen panels),
|
||||
* and the field, with its send button when the form is small, is scrolled
|
||||
* into that part.
|
||||
*/
|
||||
export function KeyboardSafe() {
|
||||
useEffect(() => {
|
||||
if (!window.matchMedia("(pointer: coarse)").matches) return;
|
||||
const root = document.documentElement;
|
||||
const vv = window.visualViewport;
|
||||
let timer: number | undefined;
|
||||
let closing: number | undefined;
|
||||
|
||||
const measure = () => {
|
||||
root.style.setProperty("--vv-top", `${vv ? vv.offsetTop : 0}px`);
|
||||
root.style.setProperty("--vv-height", `${vv ? vv.height : window.innerHeight}px`);
|
||||
};
|
||||
|
||||
const reveal = () => {
|
||||
const el = document.activeElement;
|
||||
if (!typedInto(el)) return;
|
||||
measure();
|
||||
const top = vv ? vv.offsetTop : 0;
|
||||
const height = vv ? vv.height : window.innerHeight;
|
||||
const form = el.closest("form");
|
||||
const target = form && form.getBoundingClientRect().height < height * 0.6 ? form : el;
|
||||
const rect = target.getBoundingClientRect();
|
||||
const free = { top: top + 12, bottom: top + height - 12 };
|
||||
if (rect.bottom > free.bottom) {
|
||||
window.scrollBy({ top: Math.min(rect.bottom - free.bottom, rect.top - free.top), behavior: "smooth" });
|
||||
} else if (rect.top < free.top) {
|
||||
window.scrollBy({ top: rect.top - free.top, behavior: "smooth" });
|
||||
}
|
||||
};
|
||||
|
||||
// After the keyboard has slid up, and again whenever the free part changes.
|
||||
const later = (ms: number) => {
|
||||
window.clearTimeout(timer);
|
||||
timer = window.setTimeout(reveal, ms);
|
||||
};
|
||||
|
||||
const onFocusIn = (e: FocusEvent) => {
|
||||
if (!typedInto(e.target as Element)) return;
|
||||
window.clearTimeout(closing);
|
||||
root.classList.add("kb-open");
|
||||
measure();
|
||||
later(350);
|
||||
};
|
||||
const onFocusOut = () => {
|
||||
// Moving to another field keeps it open.
|
||||
window.clearTimeout(closing);
|
||||
closing = window.setTimeout(() => {
|
||||
if (!typedInto(document.activeElement)) root.classList.remove("kb-open");
|
||||
}, 150);
|
||||
};
|
||||
const onViewport = () => {
|
||||
if (!root.classList.contains("kb-open")) return;
|
||||
measure();
|
||||
later(120);
|
||||
};
|
||||
|
||||
document.addEventListener("focusin", onFocusIn);
|
||||
document.addEventListener("focusout", onFocusOut);
|
||||
vv?.addEventListener("resize", onViewport);
|
||||
vv?.addEventListener("scroll", measure);
|
||||
return () => {
|
||||
window.clearTimeout(timer);
|
||||
window.clearTimeout(closing);
|
||||
document.removeEventListener("focusin", onFocusIn);
|
||||
document.removeEventListener("focusout", onFocusOut);
|
||||
vv?.removeEventListener("resize", onViewport);
|
||||
vv?.removeEventListener("scroll", measure);
|
||||
root.classList.remove("kb-open");
|
||||
};
|
||||
}, []);
|
||||
return null;
|
||||
}
|
||||
@@ -12,6 +12,7 @@ export type NavIconName =
|
||||
| "moon"
|
||||
| "retro"
|
||||
| "packages"
|
||||
| "forum"
|
||||
| "admin";
|
||||
|
||||
const GLYPHS: Partial<Record<NavIconName, string>> = {
|
||||
@@ -62,6 +63,12 @@ export function NavIcon({ name }: { name: NavIconName }) {
|
||||
<path d="M3.5 7.2L12 12l8.5-4.8M12 12v9.5" />
|
||||
</>
|
||||
)}
|
||||
{name === "forum" && (
|
||||
<>
|
||||
<path d="M4 5h12a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H9l-4 3v-3H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2z" />
|
||||
<path d="M20 9h1a1 1 0 0 1 1 1v8l-3-2h-6" />
|
||||
</>
|
||||
)}
|
||||
{name === "admin" && (
|
||||
<>
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { forumEnabled } from "@/lib/forumServer";
|
||||
import type { Me, SkyNow } from "@/lib/types";
|
||||
|
||||
import { MobileMenu } from "./MobileMenu";
|
||||
@@ -42,10 +43,11 @@ export function PublicHeader({
|
||||
current,
|
||||
}: {
|
||||
onHome?: boolean;
|
||||
current?: "pelda" | "horoszkop" | "csillagjegyek" | "hires" | "holdnaptar" | "retrograd";
|
||||
current?: "pelda" | "horoszkop" | "csillagjegyek" | "hires" | "holdnaptar" | "retrograd" | "forum";
|
||||
}) {
|
||||
const home = onHome ? "" : "/";
|
||||
const here = (page: typeof current) => (current === page ? "page" : undefined);
|
||||
const forum = forumEnabled();
|
||||
return (
|
||||
<header className="site-header lp-header">
|
||||
<Logo />
|
||||
@@ -56,6 +58,11 @@ export function PublicHeader({
|
||||
<Link href="/pelda" aria-current={here("pelda")}>
|
||||
Példa
|
||||
</Link>
|
||||
{forum && (
|
||||
<Link href="/forum" aria-current={here("forum")}>
|
||||
Fórum
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
<nav className="lp-free" aria-label="Ingyenes, belépés nélkül">
|
||||
<span className="lp-free-label">Ingyenes</span>
|
||||
@@ -81,6 +88,7 @@ export function PublicHeader({
|
||||
{ href: `${home}#elorejelzes`, label: "Előrejelzés" },
|
||||
{ href: `${home}#osszevetes`, label: "Összevetés" },
|
||||
{ href: "/pelda", label: "Példa" },
|
||||
...(forum ? [{ href: "/forum", label: "Fórum" }] : []),
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -148,6 +156,7 @@ export function SiteHeader({ me, sky }: { me: Me; sky?: SkyNow | null }) {
|
||||
{ href: "/szemelyek", label: "Személyek", icon: "persons" },
|
||||
{ href: "/osszevetesek", label: "Összevetések", icon: "compare" },
|
||||
{ href: "/kartyajoslas", label: "Kártyajóslás", icon: "tarot" },
|
||||
...(forumEnabled() ? [{ href: "/forum", label: "Fórum", icon: "forum" as const }] : []),
|
||||
];
|
||||
const packages: NavItem = { href: "/csomagok", label: "Csomagok", icon: "packages" };
|
||||
const team: NavItem[] = me.user.roles.includes("admin")
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { POINTS, SIGNS } from "@/lib/astro";
|
||||
import { type ForumAuthor, ago, memberHref } from "@/lib/forum";
|
||||
|
||||
import { Avatar } from "./Avatar";
|
||||
import { Badge, RankBadge } from "./Badges";
|
||||
|
||||
/** "☉ Halak · ☽ Rák · Asz Szűz": the signs a member chose to share. */
|
||||
export function signsText(signs: Record<string, string> | null | undefined): string | null {
|
||||
if (!signs) return null;
|
||||
const parts = Object.entries(signs)
|
||||
.sort(([a], [b]) => order(a) - order(b))
|
||||
.map(([point, sign]) => {
|
||||
const name = SIGNS[sign]?.hu ?? sign;
|
||||
return point === "ascendant" ? `Asz ${name}` : `${POINTS[point]?.glyph ?? point} ${name}`;
|
||||
});
|
||||
return parts.length ? parts.join(" · ") : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The short form next to a post: Sun, Moon and Ascendant as glyphs
|
||||
* ("☉♓ ☽♋ ↑♍"), with the names in `title`. Every planet only on the profile.
|
||||
*/
|
||||
export function signGlyphs(signs: Record<string, string> | null | undefined): { text: string; title: string } | null {
|
||||
if (!signs) return null;
|
||||
const parts: string[] = [];
|
||||
const names: string[] = [];
|
||||
for (const [point, label] of [
|
||||
["sun", "Nap"],
|
||||
["moon", "Hold"],
|
||||
["ascendant", "Aszcendens"],
|
||||
] as const) {
|
||||
const sign = signs[point];
|
||||
if (!sign) continue;
|
||||
const mark = point === "ascendant" ? "↑" : (POINTS[point]?.glyph ?? "");
|
||||
parts.push(`${mark}${SIGNS[sign]?.glyph ?? ""}`);
|
||||
names.push(`${label}: ${SIGNS[sign]?.hu ?? sign}`);
|
||||
}
|
||||
return parts.length ? { text: parts.join(" "), title: names.join(", ") } : null;
|
||||
}
|
||||
|
||||
const ORDER = [
|
||||
"sun",
|
||||
"moon",
|
||||
"ascendant",
|
||||
"mercury",
|
||||
"venus",
|
||||
"mars",
|
||||
"jupiter",
|
||||
"saturn",
|
||||
"uranus",
|
||||
"neptune",
|
||||
"pluto",
|
||||
];
|
||||
function order(point: string) {
|
||||
const i = ORDER.indexOf(point);
|
||||
return i < 0 ? 99 : i;
|
||||
}
|
||||
|
||||
/**
|
||||
* Who wrote it: avatar with the online dot, nickname, rank, badges, the
|
||||
* shared signs and the time. A deleted account shows as "Törölt tag".
|
||||
*/
|
||||
export function AuthorLine({
|
||||
author,
|
||||
size = 40,
|
||||
time,
|
||||
edited = false,
|
||||
badges,
|
||||
signs = true,
|
||||
}: {
|
||||
author: ForumAuthor | null;
|
||||
size?: number;
|
||||
time?: string;
|
||||
edited?: boolean;
|
||||
badges?: React.ReactNode;
|
||||
signs?: boolean;
|
||||
}) {
|
||||
if (!author) {
|
||||
return (
|
||||
<div className="fa-line">
|
||||
<Avatar avatar={null} size={size} />
|
||||
<span className="fa-meta">
|
||||
<span className="fa-name muted">Törölt tag</span>
|
||||
{time && <span className="fa-sub">{ago(time)}</span>}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const glyphs = signs ? signGlyphs(author.signs) : null;
|
||||
const shown = glyphs?.text ?? null;
|
||||
return (
|
||||
<div className="fa-line">
|
||||
<Link href={memberHref(author.nickname)} className="fa-avatar" tabIndex={-1} aria-hidden="true">
|
||||
<Avatar avatar={author.avatar} size={size} online={author.online} />
|
||||
</Link>
|
||||
<span className="fa-meta">
|
||||
<span className="fa-names">
|
||||
<Link href={memberHref(author.nickname)} className="fa-name">
|
||||
{author.nickname}
|
||||
</Link>
|
||||
{author.online && <span className="sr-only">(online)</span>}
|
||||
<RankBadge rank={author.rank} name={author.rank_name} />
|
||||
{author.moderator && <Badge kind="mod" />}
|
||||
{author.founder && <Badge kind="founder" />}
|
||||
{author.listener && <Badge kind="listener" />}
|
||||
{author.supporter && <Badge kind="supporter" />}
|
||||
{badges}
|
||||
</span>
|
||||
{(shown || time) && (
|
||||
<span className="fa-sub">
|
||||
{shown && (
|
||||
<span className="sym" title={glyphs?.title}>
|
||||
{shown}
|
||||
</span>
|
||||
)}
|
||||
{shown && time && " · "}
|
||||
{time && (
|
||||
<time
|
||||
suppressHydrationWarning
|
||||
dateTime={time}
|
||||
title={new Date(time).toLocaleString("hu-HU", { timeZone: "Europe/Budapest" })}
|
||||
>
|
||||
{ago(time)}
|
||||
</time>
|
||||
)}
|
||||
{edited && " · szerkesztve"}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
// The starter avatars, `<glyph>-<colour>` (the forum service checks the same
|
||||
// lists): a gold glyph on a night colour in the dark theme, a darker glyph on
|
||||
// a pale tint in the light one (forum.css: .av-<colour>). With `online`, the
|
||||
// green dot.
|
||||
|
||||
import { uploadedAvatar } from "@/lib/forum";
|
||||
|
||||
export const AVATAR_GLYPHS = ["hold", "csillag", "nap", "hullam", "level", "lotusz", "kristaly", "toll"] as const;
|
||||
export const AVATAR_COLOURS = ["ejkek", "lila", "tenger", "borostyan", "rozsa", "erdo"] as const;
|
||||
|
||||
export const GLYPH_NAMES: Record<string, string> = {
|
||||
hold: "Hold",
|
||||
csillag: "Csillag",
|
||||
nap: "Nap",
|
||||
hullam: "Hullám",
|
||||
level: "Levél",
|
||||
lotusz: "Lótusz",
|
||||
kristaly: "Kristály",
|
||||
toll: "Toll",
|
||||
};
|
||||
|
||||
function Glyph({ name }: { name: string }) {
|
||||
switch (name) {
|
||||
case "hold":
|
||||
return <path d="M23 10A10 10 0 1 0 23 30A8 8 0 1 1 23 10Z" className="av-fill" />;
|
||||
case "csillag":
|
||||
return <path d="M20 9 L22.5 17.5 L31 20 L22.5 22.5 L20 31 L17.5 22.5 L9 20 L17.5 17.5 Z" className="av-fill" />;
|
||||
case "nap":
|
||||
return (
|
||||
<>
|
||||
<circle cx="20" cy="20" r="5" className="av-fill" />
|
||||
<path d="M20 8v4M20 28v4M8 20h4M28 20h4M11.5 11.5l2.8 2.8M25.7 25.7l2.8 2.8M28.5 11.5l-2.8 2.8M14.3 25.7l-2.8 2.8" />
|
||||
</>
|
||||
);
|
||||
case "hullam":
|
||||
return (
|
||||
<>
|
||||
<path d="M9 18 q5.5-6 11 0 t11 0" />
|
||||
<path d="M12 25 q4-4 8 0 t8 0" opacity="0.6" />
|
||||
</>
|
||||
);
|
||||
case "level":
|
||||
return (
|
||||
<>
|
||||
<path d="M12 28 C12 16 20 11 29 11 C29 20 24 28 12 28 Z" />
|
||||
<path d="M12 28 L22 18" />
|
||||
</>
|
||||
);
|
||||
case "lotusz":
|
||||
return (
|
||||
<>
|
||||
<path d="M20 11c3 4 3 9 0 14c-3-5-3-10 0-14z" />
|
||||
<path d="M20 25c-4-1-8-4-9-9c4 0 7 3 9 9zM20 25c4-1 8-4 9-9c-4 0-7 3-9 9z" />
|
||||
<path d="M12 29h16" />
|
||||
</>
|
||||
);
|
||||
case "kristaly":
|
||||
return (
|
||||
<>
|
||||
<path d="M20 9l7 9-7 13-7-13z" />
|
||||
<path d="M13 18h14" />
|
||||
</>
|
||||
);
|
||||
default:
|
||||
return (
|
||||
<>
|
||||
<path d="M28 10c-8 1-13 7-15 18l3-1c1-6 5-11 12-17z" />
|
||||
<path d="M13 29l9-11" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function Avatar({
|
||||
avatar,
|
||||
size = 40,
|
||||
online = false,
|
||||
}: {
|
||||
avatar: string | null | undefined;
|
||||
size?: number;
|
||||
online?: boolean;
|
||||
}) {
|
||||
const picture = uploadedAvatar(avatar);
|
||||
if (picture) {
|
||||
return (
|
||||
<span className="av av-picture" style={{ width: size, height: size }}>
|
||||
{/* A member's own picture, served by the forum (already small and square). */}
|
||||
<img src={picture} alt="" width={size} height={size} loading="lazy" />
|
||||
{online && <span className="av-online" title="Most online" />}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
const [glyph, colour] = (avatar ?? "hold-ejkek").split("-");
|
||||
const known = (AVATAR_COLOURS as readonly string[]).includes(colour) ? colour : "ejkek";
|
||||
return (
|
||||
<span className={`av av-${known}`} style={{ width: size, height: size }}>
|
||||
<svg viewBox="0 0 40 40" width={size} height={size} aria-hidden="true">
|
||||
<circle cx="20" cy="20" r="20" className="av-bg" />
|
||||
<g className="av-glyph">
|
||||
<Glyph name={glyph} />
|
||||
</g>
|
||||
</svg>
|
||||
{online && <span className="av-online" title="Most online" />}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
// The small labels next to a nickname, each with its own line icon: the rank
|
||||
// (from Vándor to Sorsfonó, a thread being spun), and the badges.
|
||||
|
||||
import type { Rank } from "@/lib/forum";
|
||||
|
||||
const RANK_ICONS: Record<Rank, React.ReactNode> = {
|
||||
// Vándor: on the way (a path from a starting point).
|
||||
vandor: (
|
||||
<>
|
||||
<circle cx="5.5" cy="18.5" r="1.8" />
|
||||
<path d="M8 17.5c3-1 2.5-4.5 6-5.5s3.5-3.5 5-6" strokeDasharray="2.2 2.6" />
|
||||
</>
|
||||
),
|
||||
// Kereső: a compass.
|
||||
kereso: (
|
||||
<>
|
||||
<circle cx="12" cy="12" r="8.5" />
|
||||
<path d="M14.8 9.2l-1.6 4-4 1.6 1.6-4z" />
|
||||
</>
|
||||
),
|
||||
// Fonó: a spool with thread.
|
||||
fono: (
|
||||
<>
|
||||
<path d="M6.5 4.5h11M6.5 19.5h11" />
|
||||
<path d="M8.5 4.5v15M15.5 4.5v15" />
|
||||
<path d="M8.5 8.5l7 2.5M8.5 13l7 2.5" />
|
||||
</>
|
||||
),
|
||||
// Csillagfonó: a star with a thread from it.
|
||||
csillagfono: (
|
||||
<>
|
||||
<path d="M10 3.5l1.5 4 4 1.5-4 1.5-1.5 4-1.5-4-4-1.5 4-1.5z" />
|
||||
<path d="M14 15c2.5 0 3.5 1.5 3.5 3s-1.5 2.5-3 2" />
|
||||
</>
|
||||
),
|
||||
// Sorsfonó: the thread of fate around the circle (the site's mark).
|
||||
sorsfono: (
|
||||
<>
|
||||
<circle cx="12" cy="12" r="7" />
|
||||
<path d="M4.5 16.5c4.5-.5 6-7 11-8.5" />
|
||||
<circle cx="18.5" cy="6" r="1.4" />
|
||||
</>
|
||||
),
|
||||
};
|
||||
|
||||
export type BadgeKind = "mod" | "founder" | "listener" | "supporter" | "starter" | "sky";
|
||||
|
||||
const BADGES: Record<BadgeKind, { label: string; title: string; icon: React.ReactNode }> = {
|
||||
// A shield with a tick.
|
||||
mod: {
|
||||
label: "Moderátor",
|
||||
title: "A fórum moderátora",
|
||||
icon: (
|
||||
<>
|
||||
<path d="M12 3.5l7 2.5v5.5c0 4.5-3 7.5-7 9-4-1.5-7-4.5-7-9V6z" />
|
||||
<path d="M9 12l2.2 2.2L15.5 10" />
|
||||
</>
|
||||
),
|
||||
},
|
||||
// A sprout: there from the beginning.
|
||||
founder: {
|
||||
label: "Alapító tag",
|
||||
title: "A fórum első tizenöt tagja közül való",
|
||||
icon: (
|
||||
<>
|
||||
<path d="M12 20.5V11" />
|
||||
<path d="M12 12.5c0-4 2.8-6.5 7-6.5 0 4-2.8 6.5-7 6.5z" />
|
||||
<path d="M12 14.5c0-3.2-2.4-5.5-6-5.5 0 3.2 2.4 5.5 6 5.5z" />
|
||||
<path d="M8 20.5h8" />
|
||||
</>
|
||||
),
|
||||
},
|
||||
// Two walking side by side.
|
||||
listener: {
|
||||
label: "Kísérő",
|
||||
title: "Önkéntes kísérő: szívesen válaszol annak, aki meghallgatást kér",
|
||||
icon: (
|
||||
<>
|
||||
<circle cx="8" cy="6.5" r="2.5" />
|
||||
<circle cx="16" cy="6.5" r="2.5" />
|
||||
<path d="M3.5 20v-3.5a4.5 4.5 0 0 1 9 0V20" />
|
||||
<path d="M11.5 20v-3.5a4.5 4.5 0 0 1 9 0V20" />
|
||||
</>
|
||||
),
|
||||
},
|
||||
// A gem.
|
||||
supporter: {
|
||||
label: "Támogató",
|
||||
title: "Vásárlásával támogatja a Sorsfonalakat",
|
||||
icon: (
|
||||
<>
|
||||
<path d="M7.5 5h9l3.5 4.5L12 19.5 4 9.5z" />
|
||||
<path d="M4 9.5h16M10 5l-1.5 4.5L12 19.5l3.5-10L14 5" />
|
||||
</>
|
||||
),
|
||||
},
|
||||
// A quill.
|
||||
starter: {
|
||||
label: "Szálindító",
|
||||
title: "Ő indította a szálat",
|
||||
icon: (
|
||||
<>
|
||||
<path d="M19.5 4.5c-6 .5-10.5 4.5-11.5 11l-1.5 4" />
|
||||
<path d="M8.3 13.5c4.5 0 8.5-3 11.2-9" />
|
||||
</>
|
||||
),
|
||||
},
|
||||
// A crescent Moon.
|
||||
sky: {
|
||||
label: "napi égbolt",
|
||||
title: "A Sorsfonalak napi szála az égboltról",
|
||||
icon: <path d="M19 14.5A7.5 7.5 0 0 1 9.5 5a7.5 7.5 0 1 0 9.5 9.5z" />,
|
||||
},
|
||||
};
|
||||
|
||||
function Icon({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<svg className="fa-icon" viewBox="0 0 24 24" aria-hidden="true">
|
||||
{children}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/** The member's rank, with its icon. */
|
||||
export function RankBadge({ rank, name }: { rank: Rank; name: string }) {
|
||||
return (
|
||||
<span className={`fa-rank fa-rank-${rank}`} title={`Rang: ${name}`}>
|
||||
<Icon>{RANK_ICONS[rank] ?? RANK_ICONS.vandor}</Icon>
|
||||
{name}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** A badge (Moderátor, Alapító tag, Kísérő, Támogató, Szálindító, napi égbolt), with its icon. */
|
||||
export function Badge({ kind }: { kind: BadgeKind }) {
|
||||
const b = BADGES[kind];
|
||||
return (
|
||||
<span className={`fa-badge fa-badge-${kind === "sky" ? "starter" : kind}`} title={b.title}>
|
||||
<Icon>{b.icon}</Icon>
|
||||
{b.label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
import { api } from "@/lib/api";
|
||||
import { convertEmoticons, withEmoji } from "@/lib/emoticons";
|
||||
import type { ForumAuthor } from "@/lib/forum";
|
||||
|
||||
import { Avatar } from "./Avatar";
|
||||
|
||||
/** "@Ho" right before the caret: what was typed after the "@", and where it starts. */
|
||||
function mentionAt(text: string, caret: number): { query: string; start: number } | null {
|
||||
const before = text.slice(0, caret);
|
||||
const match = /(?:^|\s)@([^\s@]{1,24})$/.exec(before);
|
||||
if (!match) return null;
|
||||
return { query: match[1], start: caret - match[1].length - 1 };
|
||||
}
|
||||
|
||||
/**
|
||||
* The text box and the send button. Character smileys (`:)`, `<3`) turn into
|
||||
* emoji as they are typed; phones bring their own emoji keyboard.
|
||||
* `onTyping`: called on every keystroke (the "… gépel" notice).
|
||||
* `mentions`: typing "@Ho" offers the members whose nickname starts so.
|
||||
* `onChange`: the text as it is typed (to keep a draft when the box moves).
|
||||
*/
|
||||
export function Composer({
|
||||
id,
|
||||
label,
|
||||
placeholder,
|
||||
initial = "",
|
||||
submitLabel = "Küldés",
|
||||
busy,
|
||||
onSubmit,
|
||||
onCancel,
|
||||
onTyping,
|
||||
onChange,
|
||||
mentions = false,
|
||||
rows = 3,
|
||||
autoFocus = false,
|
||||
}: {
|
||||
id: string;
|
||||
label: string;
|
||||
placeholder?: string;
|
||||
initial?: string;
|
||||
submitLabel?: string;
|
||||
busy: boolean;
|
||||
onSubmit: (text: string) => Promise<boolean>;
|
||||
onCancel?: () => void;
|
||||
onTyping?: () => void;
|
||||
onChange?: (text: string) => void;
|
||||
mentions?: boolean;
|
||||
rows?: number;
|
||||
autoFocus?: boolean;
|
||||
}) {
|
||||
const [text, setText] = useState(initial);
|
||||
const [suggest, setSuggest] = useState<{ query: string; start: number; members: ForumAuthor[] } | null>(null);
|
||||
const area = useRef<HTMLTextAreaElement>(null);
|
||||
const timer = useRef<number | undefined>(undefined);
|
||||
|
||||
useEffect(() => () => window.clearTimeout(timer.current), []);
|
||||
useEffect(() => {
|
||||
onChange?.(text);
|
||||
}, [text, onChange]);
|
||||
|
||||
function lookUp(value: string, caret: number) {
|
||||
window.clearTimeout(timer.current);
|
||||
const at = mentions ? mentionAt(value, caret) : null;
|
||||
if (!at) {
|
||||
setSuggest(null);
|
||||
return;
|
||||
}
|
||||
timer.current = window.setTimeout(() => {
|
||||
api<{ members: ForumAuthor[] }>(`/forum/members/search?q=${encodeURIComponent(at.query)}`)
|
||||
.then((res) => setSuggest(res.members.length ? { ...at, members: res.members } : null))
|
||||
.catch(() => setSuggest(null));
|
||||
}, 200);
|
||||
}
|
||||
|
||||
function pick(nickname: string) {
|
||||
if (!suggest) return;
|
||||
const el = area.current;
|
||||
const caret = el?.selectionStart ?? text.length;
|
||||
const inserted = `@${nickname} `;
|
||||
const next = text.slice(0, suggest.start) + inserted + text.slice(caret);
|
||||
setText(next);
|
||||
setSuggest(null);
|
||||
requestAnimationFrame(() => {
|
||||
el?.focus();
|
||||
const at = suggest.start + inserted.length;
|
||||
el?.setSelectionRange(at, at);
|
||||
});
|
||||
}
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!text.trim() || busy) return;
|
||||
const final = convertEmoticons(text, text.length, true).text;
|
||||
if (await onSubmit(final)) {
|
||||
setText("");
|
||||
setSuggest(null);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="fc" onSubmit={submit}>
|
||||
<label htmlFor={id} className="sr-only">
|
||||
{label}
|
||||
</label>
|
||||
<textarea
|
||||
id={id}
|
||||
ref={area}
|
||||
className="fc-text"
|
||||
rows={rows}
|
||||
placeholder={placeholder}
|
||||
value={text}
|
||||
onChange={(e) => {
|
||||
withEmoji(e, setText);
|
||||
lookUp(e.target.value, e.target.selectionStart ?? e.target.value.length);
|
||||
onTyping?.();
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Escape") setSuggest(null);
|
||||
}}
|
||||
maxLength={10000}
|
||||
autoFocus={autoFocus}
|
||||
aria-autocomplete={mentions ? "list" : undefined}
|
||||
/>
|
||||
{suggest && (
|
||||
<div className="fc-suggest" role="listbox" aria-label="Tagok">
|
||||
{suggest.members.map((m) => (
|
||||
<button
|
||||
key={m.nickname}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected="false"
|
||||
className="fc-suggest-item"
|
||||
onClick={() => pick(m.nickname)}
|
||||
>
|
||||
<Avatar avatar={m.avatar} size={24} online={m.online} />
|
||||
{m.nickname}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="fc-actions">
|
||||
<span className="fc-spacer" />
|
||||
{onCancel && (
|
||||
<button type="button" className="btn btn-ghost btn-sm" onClick={onCancel}>
|
||||
Mégse
|
||||
</button>
|
||||
)}
|
||||
<button type="submit" className="btn btn-primary btn-sm" disabled={busy || !text.trim()}>
|
||||
{busy ? "Küldés…" : submitLabel}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { api } from "@/lib/api";
|
||||
import type { ForumNavData } from "@/lib/forum";
|
||||
|
||||
/** The menu's counts. */
|
||||
export interface NavCounts {
|
||||
/** Unread answers to the member: the only count on the "Válaszok" tab. */
|
||||
replies: number;
|
||||
messages: number;
|
||||
reports: number;
|
||||
}
|
||||
|
||||
/** The live notice a page listens to (`window` event `forum:live`). */
|
||||
export interface LiveNotice {
|
||||
t: "thread" | "conversation" | "nav" | "typing";
|
||||
id?: number;
|
||||
/** For `typing`: where (`thread` or `conversation`) and who. */
|
||||
kind?: string;
|
||||
who?: string;
|
||||
}
|
||||
|
||||
/** How often the counts are asked for while there is no live connection (also the online dot). */
|
||||
const POLL_MS = 30_000;
|
||||
|
||||
function counts(data: ForumNavData): NavCounts {
|
||||
return { replies: data.replies ?? 0, messages: data.messages ?? 0, reports: data.reports ?? 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* The live connection (a member's): the server rings when something changed,
|
||||
* the menu fetches its counts, and an open thread or conversation is told
|
||||
* (`forum:live` events). Without a connection, the counts are polled.
|
||||
*/
|
||||
function useLive(member: boolean, wsUrl: string, refresh: () => void) {
|
||||
const open = useRef(false);
|
||||
useEffect(() => {
|
||||
if (!member) return;
|
||||
let socket: WebSocket | null = null;
|
||||
let retry = 1000;
|
||||
let timer: number | undefined;
|
||||
let stopped = false;
|
||||
const url = new URL(wsUrl, window.location.href);
|
||||
url.protocol = url.protocol === "https:" ? "wss:" : url.protocol === "http:" ? "ws:" : url.protocol;
|
||||
const connect = () => {
|
||||
if (stopped) return;
|
||||
socket = new WebSocket(url);
|
||||
socket.onopen = () => {
|
||||
open.current = true;
|
||||
retry = 1000;
|
||||
refresh();
|
||||
};
|
||||
socket.onmessage = (e) => {
|
||||
let notice: LiveNotice;
|
||||
try {
|
||||
notice = JSON.parse(String(e.data)) as LiveNotice;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (notice.t === "nav") refresh();
|
||||
window.dispatchEvent(new CustomEvent<LiveNotice>("forum:live", { detail: notice }));
|
||||
};
|
||||
socket.onclose = () => {
|
||||
open.current = false;
|
||||
if (stopped) return;
|
||||
timer = window.setTimeout(connect, retry);
|
||||
retry = Math.min(retry * 2, 60_000);
|
||||
};
|
||||
};
|
||||
connect();
|
||||
// The page says its member is typing somewhere: passed on while connected.
|
||||
const typing = (e: Event) => {
|
||||
const out = (e as CustomEvent<{ kind: string; id: number }>).detail;
|
||||
if (open.current && socket?.readyState === WebSocket.OPEN) {
|
||||
socket.send(JSON.stringify({ typing: out.kind, id: out.id }));
|
||||
}
|
||||
};
|
||||
window.addEventListener("forum:typing-out", typing);
|
||||
// Polling while there is no connection; and when the page comes back to the front.
|
||||
const poll = window.setInterval(() => {
|
||||
if (!open.current && document.visibilityState === "visible") refresh();
|
||||
}, POLL_MS);
|
||||
const visible = () => {
|
||||
if (document.visibilityState === "visible") refresh();
|
||||
};
|
||||
document.addEventListener("visibilitychange", visible);
|
||||
return () => {
|
||||
stopped = true;
|
||||
window.clearTimeout(timer);
|
||||
window.clearInterval(poll);
|
||||
document.removeEventListener("visibilitychange", visible);
|
||||
window.removeEventListener("forum:typing-out", typing);
|
||||
socket?.close();
|
||||
};
|
||||
}, [member, wsUrl, refresh]);
|
||||
}
|
||||
|
||||
function Icon({ name }: { name: "forum" | "replies" | "new" | "messages" | "profile" }) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" className="fn-icon">
|
||||
{name === "forum" && (
|
||||
<>
|
||||
<path d="M4 5h12a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H9l-4 3v-3H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2z" />
|
||||
<path d="M20 9h1a1 1 0 0 1 1 1v8l-3-2h-6" />
|
||||
</>
|
||||
)}
|
||||
{name === "replies" && (
|
||||
<>
|
||||
<path d="M10 8L5 12.5l5 4.5" />
|
||||
<path d="M5 12.5h9a5 5 0 0 1 5 5V19" />
|
||||
<path d="M14 4.5h5.5" />
|
||||
</>
|
||||
)}
|
||||
{name === "new" && (
|
||||
<>
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
<path d="M12 8v8M8 12h8" />
|
||||
</>
|
||||
)}
|
||||
{name === "messages" && (
|
||||
<>
|
||||
<rect x="3" y="5.5" width="18" height="13" rx="2" />
|
||||
<path d="M3.5 7l8.5 6 8.5-6" />
|
||||
</>
|
||||
)}
|
||||
{name === "profile" && (
|
||||
<>
|
||||
<circle cx="12" cy="8" r="4" />
|
||||
<path d="M4.5 20.5c0-3.8 3.4-6 7.5-6s7.5 2.2 7.5 6" />
|
||||
</>
|
||||
)}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The forum's own menu: a bar at the bottom of the screen on phones, tabs
|
||||
* above the content on wider screens. The "Válaszok" tab counts the unread
|
||||
* answers to the member (a reply to them, in their thread, or naming them).
|
||||
*/
|
||||
export function ForumNav({
|
||||
member,
|
||||
loggedIn,
|
||||
initial,
|
||||
wsUrl,
|
||||
}: {
|
||||
member: string | null;
|
||||
loggedIn: boolean;
|
||||
initial: NavCounts;
|
||||
wsUrl: string;
|
||||
}) {
|
||||
const path = usePathname();
|
||||
const [{ replies, messages, reports }, setCounts] = useState(initial);
|
||||
const refresh = useCallback(() => {
|
||||
api<ForumNavData>("/forum/nav")
|
||||
.then((data) => setCounts(counts(data)))
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
useLive(member !== null, wsUrl, refresh);
|
||||
// A page that changed what counts (read a thread, "Mind olvasott") asks for fresh counts.
|
||||
useEffect(() => {
|
||||
window.addEventListener("forum:nav", refresh);
|
||||
return () => window.removeEventListener("forum:nav", refresh);
|
||||
}, [refresh]);
|
||||
// The menu stays on screen between pages: fresh counts on every page.
|
||||
const first = useRef(true);
|
||||
useEffect(() => {
|
||||
if (first.current) {
|
||||
first.current = false;
|
||||
return;
|
||||
}
|
||||
if (loggedIn) refresh();
|
||||
}, [path, loggedIn, refresh]);
|
||||
const items = [
|
||||
{
|
||||
href: "/forum",
|
||||
label: "Fórum",
|
||||
icon: "forum" as const,
|
||||
current: path === "/forum" || path.startsWith("/forum/szal"),
|
||||
},
|
||||
{
|
||||
href: loggedIn ? "/forum/valaszok" : "/belepes?vissza=/forum/valaszok",
|
||||
label: "Válaszok",
|
||||
icon: "replies" as const,
|
||||
current: path.startsWith("/forum/valaszok") || path.startsWith("/forum/kovetett"),
|
||||
badge: replies,
|
||||
},
|
||||
{
|
||||
href: loggedIn ? "/forum/uj" : "/belepes?vissza=/forum/uj",
|
||||
label: "Új szál",
|
||||
icon: "new" as const,
|
||||
current: path.startsWith("/forum/uj"),
|
||||
},
|
||||
{
|
||||
href: member
|
||||
? "/forum/uzenetek"
|
||||
: loggedIn
|
||||
? "/forum/beallitasok?vissza=/forum/uzenetek"
|
||||
: "/belepes?vissza=/forum/uzenetek",
|
||||
label: "Üzenetek",
|
||||
icon: "messages" as const,
|
||||
current: path.startsWith("/forum/uzenetek"),
|
||||
badge: messages,
|
||||
},
|
||||
{
|
||||
href: member
|
||||
? `/forum/tag/${encodeURIComponent(member)}`
|
||||
: loggedIn
|
||||
? "/forum/beallitasok"
|
||||
: "/belepes?vissza=/forum",
|
||||
label: member ? "Profilom" : loggedIn ? "Álnév" : "Belépés",
|
||||
icon: "profile" as const,
|
||||
current: path.startsWith("/forum/tag/") || path.startsWith("/forum/beallitasok"),
|
||||
},
|
||||
];
|
||||
return (
|
||||
<>
|
||||
{reports > 0 && (
|
||||
<Link href="/forum/moderalas" className="forum-modchip">
|
||||
Moderálás: {reports}
|
||||
</Link>
|
||||
)}
|
||||
<nav className="forum-nav" aria-label="Fórum menü">
|
||||
{items.map((item) => (
|
||||
<Link key={item.label} href={item.href} aria-current={item.current ? "page" : undefined} className="fn-item">
|
||||
<span className="fn-icon-wrap">
|
||||
<Icon name={item.icon} />
|
||||
{item.badge ? (
|
||||
<span className="fn-badge" aria-label={`${item.badge} új`}>
|
||||
{item.badge > 99 ? "99+" : item.badge}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
<span className="fn-label">{item.label}</span>
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
|
||||
/** A restricted topic: asking to join it (a moderator decides), or the request waiting. */
|
||||
export function JoinTopic({ slug, pending }: { slug: string; pending: boolean }) {
|
||||
const router = useRouter();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [note, setNote] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [sent, setSent] = useState(pending);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
if (sent) return <span className="hint">Jelentkezésed elküldve, egy moderátor dönt róla.</span>;
|
||||
|
||||
async function send(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api(`/forum/topics/${slug}/join`, { body: { note } });
|
||||
setSent(true);
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
setError(errorText(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (!open) {
|
||||
return (
|
||||
<button type="button" className="btn btn-sm" onClick={() => setOpen(true)}>
|
||||
Csatlakozás kérése
|
||||
</button>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<form className="fjoin" onSubmit={send}>
|
||||
<label htmlFor={`join-${slug}`} className="hint">
|
||||
Pár szó, miért szeretnél csatlakozni (nem kötelező)
|
||||
</label>
|
||||
<textarea
|
||||
id={`join-${slug}`}
|
||||
className="fc-text"
|
||||
rows={2}
|
||||
maxLength={300}
|
||||
value={note}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
/>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<div className="fc-actions">
|
||||
<span className="fc-spacer" />
|
||||
<button type="button" className="btn btn-ghost btn-sm" onClick={() => setOpen(false)}>
|
||||
Mégse
|
||||
</button>
|
||||
<button type="submit" className="btn btn-primary btn-sm" disabled={busy}>
|
||||
Jelentkezem
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import type { LinkPreview } from "@/lib/forum";
|
||||
|
||||
type Device = "android" | "ios" | "desktop";
|
||||
|
||||
function detect(): Device {
|
||||
const ua = navigator.userAgent;
|
||||
if (/Android/i.test(ua)) return "android";
|
||||
// iPadOS reports itself as a Mac with touch.
|
||||
if (/iPhone|iPad|iPod/i.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1)) return "ios";
|
||||
return "desktop";
|
||||
}
|
||||
|
||||
/**
|
||||
* A YouTube link under a post: our own copy of the thumbnail (nothing is
|
||||
* loaded from YouTube until someone plays it). On a computer a click plays
|
||||
* it here; on a phone it opens the YouTube app (Android: an intent with the
|
||||
* web page as fallback; iOS: the link, which the app takes over), and
|
||||
* "Lejátszás itt" plays it here.
|
||||
*/
|
||||
function YouTubeCard({ link }: { link: LinkPreview }) {
|
||||
const [playing, setPlaying] = useState(false);
|
||||
const [device, setDevice] = useState<Device>("desktop");
|
||||
useEffect(() => setDevice(detect()), []);
|
||||
const at = link.start ? `&t=${link.start}s` : "";
|
||||
const watch = `https://www.youtube.com/watch?v=${link.id}${at}`;
|
||||
const app =
|
||||
device === "android"
|
||||
? `intent://www.youtube.com/watch?v=${link.id}${at}#Intent;scheme=https;package=com.google.android.youtube;` +
|
||||
`S.browser_fallback_url=${encodeURIComponent(watch)};end`
|
||||
: watch;
|
||||
const mobile = device !== "desktop";
|
||||
|
||||
if (playing) {
|
||||
const start = link.start ? `&start=${link.start}` : "";
|
||||
return (
|
||||
<div className="flink flink-playing">
|
||||
<div className="flink-frame">
|
||||
<iframe
|
||||
src={`https://www.youtube-nocookie.com/embed/${link.id}?autoplay=1&rel=0&playsinline=1${start}`}
|
||||
title={link.title}
|
||||
allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
|
||||
allowFullScreen
|
||||
referrerPolicy="strict-origin-when-cross-origin"
|
||||
/>
|
||||
</div>
|
||||
<div className="flink-meta">
|
||||
<span className="flink-title">{link.title}</span>
|
||||
<a href={watch} target="_blank" rel="noopener noreferrer" className="fp-link">
|
||||
Megnyitás a YouTube-on
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="flink">
|
||||
<a
|
||||
className="flink-thumb"
|
||||
href={mobile ? app : watch}
|
||||
onClick={(e) => {
|
||||
if (!mobile) {
|
||||
e.preventDefault();
|
||||
setPlaying(true);
|
||||
}
|
||||
}}
|
||||
aria-label={mobile ? `Megnyitás a YouTube alkalmazásban: ${link.title}` : `Lejátszás: ${link.title}`}
|
||||
>
|
||||
{link.thumbnail ? (
|
||||
// Our own copy of the thumbnail (already small).
|
||||
<img src={link.thumbnail} alt="" width={480} height={270} loading="lazy" />
|
||||
) : (
|
||||
<span className="flink-noimg" />
|
||||
)}
|
||||
<span className="flink-play" aria-hidden="true">
|
||||
<svg viewBox="0 0 24 24">
|
||||
<path d="M8 5.5v13l11-6.5z" />
|
||||
</svg>
|
||||
</span>
|
||||
</a>
|
||||
<div className="flink-meta">
|
||||
<span className="flink-title">{link.title}</span>
|
||||
<span className="hint">
|
||||
YouTube{link.author ? ` · ${link.author}` : ""}
|
||||
{link.start ? ` · ${Math.floor(link.start / 60)}:${String(link.start % 60).padStart(2, "0")}-tól` : ""}
|
||||
</span>
|
||||
{mobile ? (
|
||||
<button type="button" className="fp-link flink-here" onClick={() => setPlaying(true)}>
|
||||
Lejátszás itt
|
||||
</button>
|
||||
) : (
|
||||
<a href={watch} target="_blank" rel="noopener noreferrer" className="fp-link flink-here">
|
||||
Megnyitás a YouTube-on
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The previews of the links in a post (the link module: YouTube for now). */
|
||||
export function LinkPreviews({ links }: { links: LinkPreview[] }) {
|
||||
return (
|
||||
<div className="flinks">
|
||||
{links.map((link) => (link.provider === "youtube" ? <YouTubeCard key={link.id} link={link} /> : null))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { memberHref } from "@/lib/forum";
|
||||
|
||||
/** "@Holdfény" as a link to the profile, for the nicknames the post names. */
|
||||
function withMentions(line: string, mentions: string[]): React.ReactNode[] {
|
||||
if (mentions.length === 0) return [line];
|
||||
const escaped = [...mentions]
|
||||
.sort((a, b) => b.length - a.length)
|
||||
.map((n) => n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
|
||||
const pattern = new RegExp(`@(${escaped.join("|")})`, "gi");
|
||||
const out: React.ReactNode[] = [];
|
||||
let last = 0;
|
||||
for (const match of line.matchAll(pattern)) {
|
||||
const at = match.index ?? 0;
|
||||
if (at > last) out.push(line.slice(last, at));
|
||||
const nickname = mentions.find((n) => n.toLowerCase() === match[1].toLowerCase()) ?? match[1];
|
||||
out.push(
|
||||
<Link key={at} href={memberHref(nickname)} className="fp-mention">
|
||||
@{match[1]}
|
||||
</Link>,
|
||||
);
|
||||
last = at + match[0].length;
|
||||
}
|
||||
if (last < line.length) out.push(line.slice(last));
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* A post's text: paragraphs and line breaks as typed; links stay plain text;
|
||||
* mentions link to profiles. `hide`: links shown as a preview below, left
|
||||
* out where they stand on a line of their own.
|
||||
*/
|
||||
export function PostBody({ text, mentions = [], hide = [] }: { text: string; mentions?: string[]; hide?: string[] }) {
|
||||
const shown = hide.length
|
||||
? text
|
||||
.split("\n")
|
||||
.filter((line) => !hide.includes(line.trim()))
|
||||
.join("\n")
|
||||
.trim()
|
||||
: text;
|
||||
return (
|
||||
<div className="fp-body">
|
||||
{shown
|
||||
.split(/\n{2,}/)
|
||||
.filter((para) => para.trim() !== "")
|
||||
.map((para, i) => (
|
||||
<p key={i}>
|
||||
{para.split("\n").map((line, j) => (
|
||||
<span key={j}>
|
||||
{j > 0 && <br />}
|
||||
{withMentions(line, mentions)}
|
||||
</span>
|
||||
))}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// The forum's own reaction marks (no emoji): a heart, a lotus, two circles
|
||||
// meeting, a star. Each has its colour (forum.css: .ri-<kind>); the viewer's
|
||||
// own reaction is drawn filled.
|
||||
import type { ReactionKind } from "@/lib/forum";
|
||||
|
||||
export function ReactionIcon({
|
||||
kind,
|
||||
size = 16,
|
||||
filled = false,
|
||||
}: {
|
||||
kind: ReactionKind;
|
||||
size?: number;
|
||||
filled?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
width={size}
|
||||
height={size}
|
||||
aria-hidden="true"
|
||||
className={filled ? `ri ri-${kind} ri-filled` : `ri ri-${kind}`}
|
||||
>
|
||||
{kind === "with_you" && (
|
||||
<path d="M12 20s-7.5-4.6-7.5-10.2A4.2 4.2 0 0 1 12 7.3a4.2 4.2 0 0 1 7.5 2.5C19.5 15.4 12 20 12 20z" />
|
||||
)}
|
||||
{kind === "thanks" && (
|
||||
<>
|
||||
<path d="M12 4.5c2.3 2.7 2.3 6.6 0 9.3c-2.3-2.7-2.3-6.6 0-9.3z" />
|
||||
<path d="M12 13.8c-3.2-.5-5.9-2.6-6.8-6.1c3.2.2 5.6 2.4 6.8 6.1z" />
|
||||
<path d="M12 13.8c3.2-.5 5.9-2.6 6.8-6.1c-3.2.2-5.6 2.4-6.8 6.1z" />
|
||||
<path d="M5.5 17.5h13" className="ri-line" />
|
||||
<path d="M8.5 20.2h7" className="ri-line" />
|
||||
</>
|
||||
)}
|
||||
{kind === "me_too" && (
|
||||
<>
|
||||
<circle cx="9.3" cy="12" r="5.3" />
|
||||
<circle cx="14.7" cy="12" r="5.3" />
|
||||
</>
|
||||
)}
|
||||
{kind === "insight" && (
|
||||
<>
|
||||
<path d="M11 4l1.7 5.1 5.1 1.7-5.1 1.7L11 17.6l-1.7-5.1-5.1-1.7 5.1-1.7z" />
|
||||
<path d="M18 15.5l.6 1.6 1.6.6-1.6.6-.6 1.6-.6-1.6-1.6-.6 1.6-.6z" />
|
||||
</>
|
||||
)}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import Link from "next/link";
|
||||
|
||||
/** The two views of the "Válaszok" tab: answers to me, and the threads I follow. */
|
||||
export function RepliesTabs({ current }: { current: "replies" | "followed" }) {
|
||||
return (
|
||||
<nav className="fmod-tabs" aria-label="Válaszok">
|
||||
<Link href="/forum/valaszok" aria-current={current === "replies" ? "page" : undefined}>
|
||||
Nekem
|
||||
</Link>
|
||||
<Link href="/forum/kovetett" aria-current={current === "followed" ? "page" : undefined}>
|
||||
Követett szálak
|
||||
</Link>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { REPORT_KINDS, type ReportKind } from "@/lib/forum";
|
||||
|
||||
/** What to do when someone may be in danger: shown right after a crisis report. */
|
||||
export function CrisisHelp() {
|
||||
return (
|
||||
<p className="frep-crisis" role="note">
|
||||
Ha azonnali veszélyt látsz, hívd a <strong>112</strong>-t. A lelki elsősegély-szolgálat ingyenes, éjjel-nappal
|
||||
hívható száma: <strong>116-123</strong>.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The report form: what the problem is, an optional note, and a thank-you
|
||||
* (with the helpline for a crisis report). `onClose`: the form was cancelled.
|
||||
*/
|
||||
export function ReportForm({ path, onClose }: { path: string; onClose: () => void }) {
|
||||
const [kind, setKind] = useState<ReportKind | "">("");
|
||||
const [note, setNote] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [done, setDone] = useState<{ crisis: boolean } | null>(null);
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!kind) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await api<{ crisis: boolean }>(path, { body: { kind, note } });
|
||||
setDone(res);
|
||||
} catch (err) {
|
||||
setError(errorText(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (done) {
|
||||
return (
|
||||
<div className="frep" role="status">
|
||||
<p>Köszönjük, a moderátorok megnézik. A döntésről e-mailben értesítünk.</p>
|
||||
{done.crisis && <CrisisHelp />}
|
||||
<button type="button" className="btn btn-ghost btn-sm frep-close" onClick={onClose}>
|
||||
Bezárás
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<form className="frep" onSubmit={submit}>
|
||||
<fieldset className="fnew-set">
|
||||
<legend>Mi a gond?</legend>
|
||||
{REPORT_KINDS.map((k) => (
|
||||
<label key={k.kind} className="frep-kind">
|
||||
<input type="radio" name={`${path}-kind`} checked={kind === k.kind} onChange={() => setKind(k.kind)} />
|
||||
<span>{k.label}</span>
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
{kind === "crisis" && <CrisisHelp />}
|
||||
<label className="sr-only" htmlFor={`${path}-note`}>
|
||||
Megjegyzés
|
||||
</label>
|
||||
<textarea
|
||||
id={`${path}-note`}
|
||||
className="fc-text"
|
||||
rows={2}
|
||||
maxLength={500}
|
||||
value={note}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
placeholder={kind === "other" ? "Írd le röviden, mi a gond." : "Megjegyzés (nem kötelező)"}
|
||||
/>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<div className="fc-actions">
|
||||
<span className="fc-spacer" />
|
||||
<button type="button" className="btn btn-ghost btn-sm" onClick={onClose}>
|
||||
Mégse
|
||||
</button>
|
||||
<button type="submit" className="btn btn-primary btn-sm" disabled={busy || !kind}>
|
||||
{busy ? "Küldés…" : "Jelentés küldése"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
/** "Jelentés" as a small button that opens the form in place (private messages). */
|
||||
export function ReportButton({ path, className = "fp-reply" }: { path: string; className?: string }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
if (open) return <ReportForm path={path} onClose={() => setOpen(false)} />;
|
||||
return (
|
||||
<button type="button" className={className} onClick={() => setOpen(true)}>
|
||||
Jelentés
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { POINTS, SIGNS, signName } from "@/lib/astro";
|
||||
import type { ShareCardData } from "@/lib/forum";
|
||||
|
||||
const EYEBROW: Record<ShareCardData["kind"], string> = {
|
||||
chart: "Csatolt képlet",
|
||||
synastry: "Csatolt összevetés",
|
||||
forecast: "Csatolt előrejelzés",
|
||||
};
|
||||
|
||||
const POINT_LABEL: Record<string, string> = { sun: "Nap", moon: "Hold", ascendant: "Aszcendens" };
|
||||
|
||||
/**
|
||||
* The chart, forecast or synastry a question came with: the big three with
|
||||
* degrees and houses, the summary's title, and the shared page. Members only;
|
||||
* a visitor sees that there is one.
|
||||
*/
|
||||
export function ShareCard({ share, onRemove }: { share: ShareCardData; onRemove?: () => void }) {
|
||||
if (share.locked) {
|
||||
return (
|
||||
<div className="fshare fshare-quiet">
|
||||
<span className="eyebrow">{EYEBROW[share.kind]}</span>
|
||||
<span className="hint">
|
||||
A kérdéshez csatolt képlet <Link href="/belepes">belépés</Link> után látható.
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (share.revoked) {
|
||||
return (
|
||||
<div className="fshare fshare-quiet">
|
||||
<span className="eyebrow">{EYEBROW[share.kind]}</span>
|
||||
<span className="hint">A szerző levette a csatolt képletet.</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const points = share.points ?? [];
|
||||
return (
|
||||
<div className="fshare">
|
||||
<div className="fshare-head">
|
||||
<span className="eyebrow">{EYEBROW[share.kind]}</span>
|
||||
{onRemove && (
|
||||
<button type="button" className="fp-link" onClick={onRemove} aria-label="Képlet levétele">
|
||||
×
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<strong className="fshare-title">{share.title}</strong>
|
||||
{share.summary && <span className="fshare-summary">„{share.summary}”</span>}
|
||||
{points.length > 0 && (
|
||||
<ul className="fshare-points">
|
||||
{points.map((p) => (
|
||||
<li key={p.id}>
|
||||
<span className="sym" aria-hidden="true">
|
||||
{POINTS[p.id]?.glyph ?? ""}
|
||||
</span>{" "}
|
||||
{POINT_LABEL[p.id] ?? p.id}{" "}
|
||||
<span className="sym" aria-hidden="true">
|
||||
{SIGNS[p.sign]?.glyph ?? ""}
|
||||
</span>{" "}
|
||||
{signName(p.sign)}
|
||||
{p.degree !== null && ` ${p.degree}°`}
|
||||
{p.house !== null && <span className="hint"> · {p.house}. ház</span>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{share.kind !== "synastry" && share.time_known === false && (
|
||||
<span className="hint">A születési idő ismeretlen, ezért házak és Aszcendens nincsenek.</span>
|
||||
)}
|
||||
{share.slug && (
|
||||
<Link href={`/s/${share.slug}`} className="btn btn-sm fshare-open" target="_blank" rel="noopener">
|
||||
Megnyitom ›
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
import { FORUM_THEME_COOKIE, type ForumTheme } from "@/lib/forum";
|
||||
|
||||
/**
|
||||
* Light (the forum's default) or dark. Remembered in a cookie, so the server
|
||||
* renders the chosen one and nothing flashes on load.
|
||||
*/
|
||||
export function ThemeToggle({ initial }: { initial: ForumTheme }) {
|
||||
const [theme, setTheme] = useState<ForumTheme>(initial);
|
||||
const next: ForumTheme = theme === "light" ? "dark" : "light";
|
||||
|
||||
function toggle() {
|
||||
document.cookie = `${FORUM_THEME_COOKIE}=${next}; path=/; max-age=${60 * 60 * 24 * 365}; samesite=lax`;
|
||||
document.querySelector<HTMLElement>(".forum")?.setAttribute("data-theme", next);
|
||||
setTheme(next);
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="forum-theme"
|
||||
onClick={toggle}
|
||||
aria-label={next === "dark" ? "Sötét téma" : "Világos téma"}
|
||||
title={next === "dark" ? "Sötét téma" : "Világos téma"}
|
||||
>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
{next === "dark" ? (
|
||||
<path d="M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z" />
|
||||
) : (
|
||||
<>
|
||||
<circle cx="12" cy="12" r="4" />
|
||||
<path d="M12 2.5v2M12 19.5v2M2.5 12h2M19.5 12h2M5.3 5.3l1.4 1.4M17.3 17.3l1.4 1.4M5.3 18.7l1.4-1.4M17.3 6.7l1.4-1.4" />
|
||||
</>
|
||||
)}
|
||||
</svg>
|
||||
<span className="forum-theme-label">{next === "dark" ? "Sötét" : "Világos"}</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { INTENTS, type ThreadCard, ago, threadHref } from "@/lib/forum";
|
||||
|
||||
import { Avatar } from "./Avatar";
|
||||
|
||||
export function IntentTag({ intent, long = false }: { intent: ThreadCard["intent"]; long?: boolean }) {
|
||||
if (!intent) return null;
|
||||
const text = long ? INTENTS[intent].label : INTENTS[intent].short;
|
||||
return <span className={`ft-intent ft-intent-${intent}`}>{text}</span>;
|
||||
}
|
||||
|
||||
function UnreadPill({ n }: { n: number | null }) {
|
||||
if (n === null) return null;
|
||||
if (n === 0) return <span className="ft-read">olvasva</span>;
|
||||
return <span className="ft-new">{n > 99 ? "99+" : n} új</span>;
|
||||
}
|
||||
|
||||
/** Threads in a list: title, topic, replies, the starter, what is new. */
|
||||
export function ThreadList({ threads, showTopic = true }: { threads: ThreadCard[]; showTopic?: boolean }) {
|
||||
return (
|
||||
<ul className="ft-list">
|
||||
{threads.map((t) => (
|
||||
<li key={t.id}>
|
||||
<Link href={threadHref(t)} className="ft-row">
|
||||
<span className="ft-main">
|
||||
<span className="ft-title">
|
||||
{t.pinned && <span className="ft-pin">Kitűzve</span>}
|
||||
{t.locked && <span className="ft-pin">Lezárva</span>}
|
||||
{t.title}
|
||||
</span>
|
||||
<span className="ft-meta">
|
||||
{t.author && <Avatar avatar={t.author.avatar} size={20} online={t.author.online} />}
|
||||
<span>
|
||||
{t.system ? "Sorsfonalak" : (t.author?.nickname ?? "Törölt tag")}
|
||||
{showTopic && ` · ${t.topic.name}`}
|
||||
<span className="ft-m-narrow">
|
||||
{" "}
|
||||
· {t.reply_count} válasz ·{" "}
|
||||
<time suppressHydrationWarning dateTime={t.last_post_at}>
|
||||
{ago(t.last_post_at)}
|
||||
</time>
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
<span className="ft-col ft-col-replies">
|
||||
<strong>{t.reply_count}</strong> válasz
|
||||
{t.participants > 1 && <span className="hint">{t.participants} résztvevő</span>}
|
||||
</span>
|
||||
<span className="ft-col ft-col-last">
|
||||
<time suppressHydrationWarning dateTime={t.last_post_at}>
|
||||
{ago(t.last_post_at)}
|
||||
</time>
|
||||
</span>
|
||||
<UnreadPill n={t.unread} />
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
/** "Várják a válaszod": a thread without replies, with the starter's wish and a reply button. */
|
||||
export function WaitingCard({ thread }: { thread: ThreadCard }) {
|
||||
return (
|
||||
<article className="ft-waiting">
|
||||
<IntentTag intent={thread.intent} long />
|
||||
<Link href={threadHref(thread)} className="ft-waiting-title">
|
||||
{thread.title}
|
||||
</Link>
|
||||
<span className="ft-meta">
|
||||
{thread.author && <Avatar avatar={thread.author.avatar} size={24} online={thread.author.online} />}
|
||||
<span>
|
||||
{thread.author?.nickname ?? "Törölt tag"} · {thread.topic.name} ·{" "}
|
||||
<time suppressHydrationWarning dateTime={thread.created_at}>
|
||||
{ago(thread.created_at)}
|
||||
</time>
|
||||
</span>
|
||||
</span>
|
||||
<Link href={`${threadHref(thread)}#valasz`} className="btn btn-sm ft-answer">
|
||||
Válaszolok
|
||||
</Link>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,816 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { type ForumPost, INTENTS, REACTIONS, type ReactionKind, type ThreadPage, ago, memberHref } from "@/lib/forum";
|
||||
|
||||
import { signGlyphs } from "./AuthorLine";
|
||||
import { Avatar } from "./Avatar";
|
||||
import { Composer } from "./Composer";
|
||||
import { PostBody } from "./PostBody";
|
||||
import type { LiveNotice } from "./ForumNav";
|
||||
import { ReactionIcon } from "./ReactionIcon";
|
||||
import { ReportForm } from "./ReportButton";
|
||||
import { LinkPreviews } from "./LinkPreviews";
|
||||
import { ShareCard } from "./ShareCard";
|
||||
import { TypingLine, useTypingSender, useTypingWatch } from "./typing";
|
||||
import { Badge, RankBadge } from "./Badges";
|
||||
|
||||
/** How often the open thread looks for new replies (while the page is in front). */
|
||||
const POLL_MS = 30_000;
|
||||
|
||||
type Actions = {
|
||||
busy: boolean;
|
||||
react: (post: ForumPost, kind: ReactionKind | "down") => void;
|
||||
replyTo: (post: ForumPost) => void;
|
||||
edit: (post: ForumPost, body: string) => Promise<boolean>;
|
||||
remove: (post: ForumPost) => void;
|
||||
restore: (post: ForumPost) => void;
|
||||
helped: (post: ForumPost) => void;
|
||||
/** The author takes the shared chart off their question. */
|
||||
detachShare: (post: ForumPost) => void;
|
||||
/** Mute or unmute the post's author. */
|
||||
mute: (post: ForumPost) => void;
|
||||
};
|
||||
|
||||
function ReactionRow({
|
||||
post,
|
||||
enabled,
|
||||
canDownvote,
|
||||
onReact,
|
||||
}: {
|
||||
post: ForumPost;
|
||||
enabled: boolean;
|
||||
canDownvote: boolean;
|
||||
onReact: Actions["react"];
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const given = REACTIONS.filter((r) => post.reactions[r.kind] > 0 || post.mine === r.kind);
|
||||
return (
|
||||
<div className="fr-row" role="group" aria-label="Reakciók">
|
||||
{given.map((r) => (
|
||||
<button
|
||||
key={r.kind}
|
||||
type="button"
|
||||
className="fr-chip"
|
||||
aria-pressed={post.mine === r.kind}
|
||||
aria-label={`${r.label}, ${post.reactions[r.kind]}${post.mine === r.kind ? ", a tiéd" : ""}`}
|
||||
title={r.label}
|
||||
disabled={!enabled}
|
||||
onClick={() => onReact(post, r.kind)}
|
||||
>
|
||||
<ReactionIcon kind={r.kind} filled={post.mine === r.kind} />
|
||||
{post.reactions[r.kind]}
|
||||
</button>
|
||||
))}
|
||||
{enabled && (
|
||||
<Popover
|
||||
open={open}
|
||||
onClose={() => setOpen(false)}
|
||||
button={
|
||||
<button
|
||||
type="button"
|
||||
className="fr-chip fr-add"
|
||||
aria-label="Reakció hozzáadása"
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d="M12 6v12M6 12h12" />
|
||||
</svg>
|
||||
</button>
|
||||
}
|
||||
>
|
||||
{REACTIONS.map((r) => (
|
||||
<button
|
||||
key={r.kind}
|
||||
type="button"
|
||||
role="menuitem"
|
||||
className="fpop-item"
|
||||
aria-pressed={post.mine === r.kind}
|
||||
onClick={() => {
|
||||
setOpen(false);
|
||||
onReact(post, r.kind);
|
||||
}}
|
||||
>
|
||||
<ReactionIcon kind={r.kind} size={18} filled={post.mine === r.kind} />
|
||||
{r.label}
|
||||
</button>
|
||||
))}
|
||||
</Popover>
|
||||
)}
|
||||
{canDownvote && enabled && (
|
||||
<button
|
||||
type="button"
|
||||
className="fr-chip fr-down"
|
||||
aria-pressed={post.mine === "down"}
|
||||
aria-label="Nem visz előre"
|
||||
title="Nem visz előre"
|
||||
onClick={() => onReact(post, "down")}
|
||||
>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d="M7 10l5 5 5-5" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** A small menu under a button (closes on a click elsewhere or Escape). */
|
||||
function Popover({
|
||||
open,
|
||||
onClose,
|
||||
button,
|
||||
children,
|
||||
align = "left",
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
button: React.ReactNode;
|
||||
children: React.ReactNode;
|
||||
align?: "left" | "right";
|
||||
}) {
|
||||
const box = useRef<HTMLSpanElement>(null);
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const outside = (e: MouseEvent) => {
|
||||
if (box.current && !box.current.contains(e.target as Node)) onClose();
|
||||
};
|
||||
const escape = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") onClose();
|
||||
};
|
||||
document.addEventListener("mousedown", outside);
|
||||
document.addEventListener("keydown", escape);
|
||||
return () => {
|
||||
document.removeEventListener("mousedown", outside);
|
||||
document.removeEventListener("keydown", escape);
|
||||
};
|
||||
}, [open, onClose]);
|
||||
return (
|
||||
<span className="fpop-wrap" ref={box}>
|
||||
{button}
|
||||
{open && (
|
||||
<span className={align === "right" ? "fpop fpop-right" : "fpop"} role="menu">
|
||||
{children}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** The site's own mark as an avatar (the daily sky thread). */
|
||||
function SiteMark({ size }: { size: number }) {
|
||||
return (
|
||||
<span className="av av-site" style={{ width: size, height: size }}>
|
||||
<svg viewBox="0 0 64 64" width={size} height={size} aria-hidden="true">
|
||||
<circle cx="32" cy="32" r="32" className="av-bg" />
|
||||
<g fill="none" strokeWidth="4.5" strokeLinecap="round" className="av-site-mark">
|
||||
<circle cx="32" cy="32" r="18" />
|
||||
<path d="M15 43 C 26 42, 30 25, 42 21" />
|
||||
</g>
|
||||
</svg>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function PostCard({
|
||||
post,
|
||||
page,
|
||||
actions,
|
||||
isNew,
|
||||
nested = false,
|
||||
}: {
|
||||
post: ForumPost;
|
||||
page: ThreadPage;
|
||||
actions: Actions;
|
||||
isNew: boolean;
|
||||
nested?: boolean;
|
||||
}) {
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [reporting, setReporting] = useState(false);
|
||||
const [menu, setMenu] = useState(false);
|
||||
const [showCollapsed, setShowCollapsed] = useState(false);
|
||||
const [showMuted, setShowMuted] = useState(false);
|
||||
const { viewer, thread, access } = page;
|
||||
const writer = viewer.member !== null && !viewer.member.banned;
|
||||
const starter = post.author !== null && post.author.nickname === thread.author?.nickname;
|
||||
const canReact = writer && !post.own && !post.deleted && !thread.locked;
|
||||
const author = post.author;
|
||||
const glyphs = signGlyphs(author?.signs);
|
||||
const size = post.is_opening ? 40 : nested ? 26 : 32;
|
||||
|
||||
if (post.deleted && !viewer.moderator) {
|
||||
return (
|
||||
<article className="fp fp-removed" id={`h${post.id}`}>
|
||||
<span>
|
||||
{post.deleted.by_moderator
|
||||
? "A moderátor eltávolította ezt a hozzászólást."
|
||||
: "A szerző törölte ezt a hozzászólást."}
|
||||
</span>
|
||||
{post.deleted.reason && <span className="hint">Ok: {post.deleted.reason}</span>}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
// A muted member's post folds up; one click shows it.
|
||||
if (post.muted && !showMuted) {
|
||||
return (
|
||||
<article className={nested ? "fp fp-muted fp-nested" : "fp fp-muted"} id={`h${post.id}`}>
|
||||
<button type="button" className="fp-collapsed" onClick={() => setShowMuted(true)}>
|
||||
{author?.nickname ?? "Egy tag"} hozzászólása · elnémítottad · Megjelenítés
|
||||
</button>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
const menuItems: { label: string; run: () => void; danger?: boolean }[] = [];
|
||||
if (!post.deleted) {
|
||||
if (access?.is_thread_author && !post.is_opening && !post.own && writer) {
|
||||
menuItems.push({ label: post.helped ? "Mégsem segített" : "Ez segített", run: () => actions.helped(post) });
|
||||
}
|
||||
if (post.own && writer && !thread.locked) menuItems.push({ label: "Szerkesztés", run: () => setEditing(true) });
|
||||
if (post.own && post.share && !post.share.revoked)
|
||||
menuItems.push({ label: "Képlet levétele", run: () => actions.detachShare(post) });
|
||||
if (post.own) menuItems.push({ label: "Törlés", run: () => actions.remove(post), danger: true });
|
||||
if (viewer.logged_in && !post.own) menuItems.push({ label: "Jelentés", run: () => setReporting(true) });
|
||||
if (viewer.member && !post.own && author && !post.system)
|
||||
menuItems.push({
|
||||
label: post.muted ? `${author.nickname} némításának feloldása` : `${author.nickname} némítása`,
|
||||
run: () => actions.mute(post),
|
||||
});
|
||||
if (viewer.moderator && !post.own)
|
||||
menuItems.push({ label: "Eltávolítás", run: () => actions.remove(post), danger: true });
|
||||
} else if (viewer.moderator) {
|
||||
menuItems.push({ label: "Visszaállítás (admin)", run: () => actions.restore(post) });
|
||||
}
|
||||
|
||||
const classes = ["fp", post.is_opening && "fp-opening", nested && "fp-nested"].filter(Boolean).join(" ");
|
||||
return (
|
||||
<article className={classes} id={`h${post.id}`}>
|
||||
<span className="fp-av">
|
||||
{post.system ? (
|
||||
<SiteMark size={size} />
|
||||
) : author ? (
|
||||
<Link href={memberHref(author.nickname)} tabIndex={-1} aria-hidden="true">
|
||||
<Avatar avatar={author.avatar} size={size} online={author.online} />
|
||||
</Link>
|
||||
) : (
|
||||
<Avatar avatar={null} size={size} />
|
||||
)}
|
||||
</span>
|
||||
<div className="fp-head">
|
||||
<span className="fp-names">
|
||||
{post.system ? (
|
||||
<span className="fa-name">Sorsfonalak</span>
|
||||
) : author ? (
|
||||
<Link href={memberHref(author.nickname)} className="fa-name">
|
||||
{author.nickname}
|
||||
</Link>
|
||||
) : (
|
||||
<span className="fa-name muted">Törölt tag</span>
|
||||
)}
|
||||
{post.reply_to?.nickname && nested && (
|
||||
<span className="fp-replyto" title={`Válasz neki: ${post.reply_to.nickname}`}>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d="M9 14L4 9l5-5" />
|
||||
<path d="M4 9h10a6 6 0 0 1 6 6v4" />
|
||||
</svg>
|
||||
<span className="sr-only">válasz neki:</span>
|
||||
{post.reply_to.nickname}
|
||||
</span>
|
||||
)}
|
||||
{author?.online && <span className="sr-only">(online)</span>}
|
||||
{author && <RankBadge rank={author.rank} name={author.rank_name} />}
|
||||
{post.system && <Badge kind="sky" />}
|
||||
{author?.moderator && <Badge kind="mod" />}
|
||||
{author?.founder && !nested && <Badge kind="founder" />}
|
||||
{author?.listener && <Badge kind="listener" />}
|
||||
{author?.supporter && <Badge kind="supporter" />}
|
||||
{starter && !post.is_opening && <Badge kind="starter" />}
|
||||
{isNew && <span className="fa-badge fa-badge-new">új</span>}
|
||||
{glyphs && !nested && (
|
||||
<span className="fp-signs sym" title={glyphs.title}>
|
||||
{glyphs.text}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<time
|
||||
className="fp-time"
|
||||
suppressHydrationWarning
|
||||
dateTime={post.created_at}
|
||||
title={new Date(post.created_at).toLocaleString("hu-HU", { timeZone: "Europe/Budapest" })}
|
||||
>
|
||||
{ago(post.created_at)}
|
||||
{post.edited_at && " · szerkesztve"}
|
||||
</time>
|
||||
</div>
|
||||
<div className="fp-content">
|
||||
{post.deleted && (
|
||||
<p className="fp-mod-note">
|
||||
Eltávolítva{post.deleted.reason ? ` (ok: ${post.deleted.reason})` : " a szerző által"}. Csak a moderátorok
|
||||
látják.
|
||||
</p>
|
||||
)}
|
||||
{post.collapsed && !showCollapsed ? (
|
||||
<button type="button" className="fp-collapsed" onClick={() => setShowCollapsed(true)}>
|
||||
Sokan jelezték, hogy ez nem visz előre. Megjelenítés
|
||||
</button>
|
||||
) : editing ? (
|
||||
<Composer
|
||||
mentions
|
||||
id={`szerk-${post.id}`}
|
||||
label="Hozzászólás szerkesztése"
|
||||
initial={post.body ?? ""}
|
||||
submitLabel="Mentés"
|
||||
busy={actions.busy}
|
||||
autoFocus
|
||||
onCancel={() => setEditing(false)}
|
||||
onSubmit={async (text) => {
|
||||
const ok = await actions.edit(post, text);
|
||||
if (ok) setEditing(false);
|
||||
return ok;
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
post.body !== null && (
|
||||
<>
|
||||
<PostBody text={post.body} mentions={post.mentions} hide={post.links?.map((l) => l.url) ?? []} />
|
||||
{post.links && post.links.length > 0 && <LinkPreviews links={post.links} />}
|
||||
{post.share && <ShareCard share={post.share} />}
|
||||
</>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
{!editing && (!post.deleted || menuItems.length > 0) && (
|
||||
<div className="fp-actions">
|
||||
{post.helped && (
|
||||
<span className="fp-helped" title={`${thread.author?.nickname ?? "A szál indítója"} szerint ez segített`}>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d="M5 12.5l4.5 4.5L19 7.5" />
|
||||
</svg>
|
||||
Segített
|
||||
</span>
|
||||
)}
|
||||
{!post.deleted && (
|
||||
<ReactionRow
|
||||
post={post}
|
||||
enabled={canReact}
|
||||
canDownvote={access?.can_downvote ?? false}
|
||||
onReact={actions.react}
|
||||
/>
|
||||
)}
|
||||
<span className="fp-spacer" />
|
||||
{viewer.moderator && typeof post.down === "number" && post.down > 0 && (
|
||||
<span className="hint" title="Nem visz előre jelzések (csak moderátoroknak)">
|
||||
⌄ {post.down}
|
||||
</span>
|
||||
)}
|
||||
{!post.deleted && access?.can_reply && writer && !post.is_opening && (
|
||||
<button type="button" className="fp-reply" onClick={() => actions.replyTo(post)}>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d="M9 14L4 9l5-5" />
|
||||
<path d="M4 9h10a6 6 0 0 1 6 6v4" />
|
||||
</svg>
|
||||
Válasz
|
||||
</button>
|
||||
)}
|
||||
{menuItems.length > 0 && (
|
||||
<Popover
|
||||
open={menu}
|
||||
onClose={() => setMenu(false)}
|
||||
align="right"
|
||||
button={
|
||||
<button
|
||||
type="button"
|
||||
className="fp-more"
|
||||
aria-label="Továbbiak"
|
||||
aria-expanded={menu}
|
||||
onClick={() => setMenu((m) => !m)}
|
||||
>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<circle cx="5.5" cy="12" r="1.6" />
|
||||
<circle cx="12" cy="12" r="1.6" />
|
||||
<circle cx="18.5" cy="12" r="1.6" />
|
||||
</svg>
|
||||
</button>
|
||||
}
|
||||
>
|
||||
{menuItems.map((item) => (
|
||||
<button
|
||||
key={item.label}
|
||||
type="button"
|
||||
role="menuitem"
|
||||
className={item.danger ? "fpop-item fpop-danger" : "fpop-item"}
|
||||
onClick={() => {
|
||||
setMenu(false);
|
||||
item.run();
|
||||
}}
|
||||
>
|
||||
{item.label}
|
||||
</button>
|
||||
))}
|
||||
</Popover>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{reporting && (
|
||||
<div className="fp-report">
|
||||
<ReportForm path={`/forum/posts/${post.id}/report`} onClose={() => setReporting(false)} />
|
||||
</div>
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
/** The thread page: posts, reactions, replies, read marks, new replies while open. */
|
||||
export function ThreadView({ initial }: { initial: ThreadPage }) {
|
||||
const [page, setPage] = useState(initial);
|
||||
const [incoming, setIncoming] = useState<ThreadPage | null>(null);
|
||||
const [replyTo, setReplyTo] = useState<ForumPost | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
// Where the visitor stopped reading when they opened the page.
|
||||
const [readUpTo] = useState(initial.access?.last_read_post_id ?? null);
|
||||
const typingNow = useTypingWatch("thread", initial.thread.id);
|
||||
const imTyping = useTypingSender("thread", initial.thread.id);
|
||||
const composer = useRef<HTMLDivElement>(null);
|
||||
// Replying to a post: the box opens at the bottom of its branch (the
|
||||
// first-level post and the replies under it); what was typed moves along.
|
||||
const inline = useRef<HTMLDivElement>(null);
|
||||
const draft = useRef("");
|
||||
const replyBranch = replyTo ? (replyTo.parent_id ?? replyTo.id) : null;
|
||||
useEffect(() => {
|
||||
if (replyBranch === null) return;
|
||||
const box = inline.current;
|
||||
box?.scrollIntoView({ behavior: "smooth", block: "center" });
|
||||
box?.querySelector("textarea")?.focus({ preventScroll: true });
|
||||
}, [replyBranch, replyTo]);
|
||||
const { viewer, thread, access } = page;
|
||||
const member = viewer.member !== null;
|
||||
const base = `/forum/threads/${thread.id}`;
|
||||
|
||||
const lastId = page.posts.length ? page.posts[page.posts.length - 1].id : 0;
|
||||
|
||||
// Mark read up to the newest post shown.
|
||||
useEffect(() => {
|
||||
if (!member || lastId === 0) return;
|
||||
api(`${base}/read`, { body: { post_id: lastId } })
|
||||
// The answers read here leave the count on the "Válaszok" tab.
|
||||
.then(() => window.dispatchEvent(new Event("forum:nav")))
|
||||
.catch(() => {});
|
||||
}, [member, lastId, base]);
|
||||
|
||||
// New replies while the page is open: offered, not pushed into the text being read.
|
||||
const poll = useCallback(async () => {
|
||||
if (document.visibilityState !== "visible" || thread.deleted) return;
|
||||
try {
|
||||
const fresh = await api<ThreadPage>(base);
|
||||
const freshLast = fresh.posts.length ? fresh.posts[fresh.posts.length - 1].id : 0;
|
||||
if (freshLast > lastId) setIncoming(fresh);
|
||||
} catch {
|
||||
/* a missed poll is retried later */
|
||||
}
|
||||
}, [base, lastId, thread.deleted]);
|
||||
useEffect(() => {
|
||||
const timer = window.setInterval(poll, POLL_MS);
|
||||
// The live connection rings for this thread: look at once.
|
||||
const live = (e: Event) => {
|
||||
const notice = (e as CustomEvent<LiveNotice>).detail;
|
||||
if (notice.t === "thread" && notice.id === thread.id) void poll();
|
||||
};
|
||||
window.addEventListener("forum:live", live);
|
||||
return () => {
|
||||
window.clearInterval(timer);
|
||||
window.removeEventListener("forum:live", live);
|
||||
};
|
||||
}, [poll, thread.id]);
|
||||
|
||||
const newCount = incoming ? incoming.posts.filter((p) => p.id > lastId && !p.own).length : 0;
|
||||
|
||||
async function run<T>(work: () => Promise<T>): Promise<T | null> {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
return await work();
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
return null;
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const replacePost = useCallback((post: ForumPost) => {
|
||||
setPage((p) => ({ ...p, posts: p.posts.map((x) => (x.id === post.id ? post : x)) }));
|
||||
}, []);
|
||||
|
||||
const reload = useCallback(async () => {
|
||||
const fresh = await api<ThreadPage>(base);
|
||||
setPage(fresh);
|
||||
setIncoming(null);
|
||||
}, [base]);
|
||||
|
||||
const actions: Actions = {
|
||||
busy,
|
||||
react: (post, kind) =>
|
||||
void run(async () => {
|
||||
const updated =
|
||||
post.mine === kind
|
||||
? await api<ForumPost>(`/forum/posts/${post.id}/reaction`, { method: "DELETE" })
|
||||
: await api<ForumPost>(`/forum/posts/${post.id}/reaction`, { method: "PUT", body: { kind } });
|
||||
replacePost(updated);
|
||||
}),
|
||||
replyTo: (post) => setReplyTo(post),
|
||||
edit: async (post, body) => {
|
||||
const updated = await run(() => api<ForumPost>(`/forum/posts/${post.id}`, { method: "PATCH", body: { body } }));
|
||||
if (updated) replacePost(updated);
|
||||
return updated !== null;
|
||||
},
|
||||
remove: (post) => {
|
||||
let reason: string | null = null;
|
||||
if (post.own) {
|
||||
if (!window.confirm("Biztosan törlöd a hozzászólásodat?")) return;
|
||||
} else {
|
||||
reason = window.prompt("Miért távolítod el? Az indoklás a hozzászólás helyén látszik.");
|
||||
if (!reason) return;
|
||||
}
|
||||
void run(async () => {
|
||||
await api(`/forum/posts/${post.id}`, { method: "DELETE", body: { reason } });
|
||||
await reload();
|
||||
});
|
||||
},
|
||||
restore: (post) =>
|
||||
void run(async () => {
|
||||
await api(`/forum/posts/${post.id}/restore`, { method: "POST" });
|
||||
await reload();
|
||||
}),
|
||||
detachShare: (post) => {
|
||||
if (!window.confirm("Leveszed a csatolt képletet? A kártya eltűnik, és a link sem működik többé.")) return;
|
||||
void run(async () => {
|
||||
await api(`/forum/posts/${post.id}/share`, { method: "DELETE" });
|
||||
await reload();
|
||||
});
|
||||
},
|
||||
mute: (post) => {
|
||||
const nickname = post.author?.nickname;
|
||||
if (!nickname) return;
|
||||
if (
|
||||
!post.muted &&
|
||||
!window.confirm(
|
||||
`Elnémítod ${nickname} tagot? A szálai eltűnnek a listáidból, a hozzászólásai összecsukva látszanak, és nem kapsz értesítést tőle. Ő erről nem tud. A beállításoknál bármikor feloldhatod.`,
|
||||
)
|
||||
)
|
||||
return;
|
||||
void run(async () => {
|
||||
await api(`/forum/members/${encodeURIComponent(nickname)}/mute`, { method: post.muted ? "DELETE" : "PUT" });
|
||||
await reload();
|
||||
});
|
||||
},
|
||||
helped: (post) =>
|
||||
void run(async () => {
|
||||
const updated = await api<ForumPost>(`/forum/posts/${post.id}/helped`, {
|
||||
method: post.helped ? "DELETE" : "PUT",
|
||||
});
|
||||
replacePost(updated);
|
||||
}),
|
||||
};
|
||||
|
||||
/** A first-level reply (the box at the bottom), or one to `replyTo` (the box in its branch). */
|
||||
async function sendReply(text: string, to: ForumPost | null): Promise<boolean> {
|
||||
const post = await run(() => api<ForumPost>(`${base}/posts`, { body: { body: text, parent_id: to?.id ?? null } }));
|
||||
if (!post) return false;
|
||||
if (to) {
|
||||
draft.current = "";
|
||||
setReplyTo(null);
|
||||
}
|
||||
await reload().catch(() => setPage((p) => ({ ...p, posts: [...p.posts, post] })));
|
||||
requestAnimationFrame(() => document.getElementById(`h${post.id}`)?.scrollIntoView({ block: "center" }));
|
||||
return true;
|
||||
}
|
||||
|
||||
async function toggleFollow() {
|
||||
const following = access?.following ?? false;
|
||||
await run(() => api(`${base}/follow`, { method: following ? "DELETE" : "PUT" }));
|
||||
setPage((p) => (p.access ? { ...p, access: { ...p.access, following: !following } } : p));
|
||||
}
|
||||
|
||||
async function moderateThread(change: { locked?: boolean; pinned?: boolean }) {
|
||||
await run(() => api(base, { method: "PATCH", body: change }));
|
||||
await reload();
|
||||
}
|
||||
|
||||
async function removeThread() {
|
||||
const reason = window.prompt("Miért távolítod el az egész szálat? Az indoklás látszik a helyén.");
|
||||
if (!reason) return;
|
||||
await run(() => api(base, { method: "DELETE", body: { reason } }));
|
||||
await reload();
|
||||
}
|
||||
|
||||
const opening = page.posts.find((p) => p.is_opening);
|
||||
const replies = useMemo(() => page.posts.filter((p) => !p.is_opening), [page.posts]);
|
||||
const tops = replies.filter((p) => p.parent_id === null);
|
||||
const childrenOf = (id: number) => replies.filter((p) => p.parent_id === id);
|
||||
// "Itt hagytad abba": before the first post by someone else after the last visit.
|
||||
const firstUnread = readUpTo !== null ? (replies.find((p) => p.id > readUpTo && !p.own)?.id ?? null) : null;
|
||||
const unreadCount = firstUnread !== null ? replies.filter((p) => p.id >= firstUnread && !p.own).length : 0;
|
||||
const topOf = (id: number) => {
|
||||
const p = replies.find((x) => x.id === id);
|
||||
return p?.parent_id ?? id;
|
||||
};
|
||||
const markerTop = firstUnread !== null ? topOf(firstUnread) : null;
|
||||
const intent = thread.intent ? INTENTS[thread.intent] : null;
|
||||
const starter = thread.author?.nickname ?? "A szál indítója";
|
||||
|
||||
return (
|
||||
<div className="ftv">
|
||||
<nav className="forum-crumbs" aria-label="Morzsamenü">
|
||||
<Link href="/forum">Fórum</Link>
|
||||
<span aria-hidden="true">›</span>
|
||||
<Link href={`/forum/${thread.topic.slug}`}>{thread.topic.name}</Link>
|
||||
{thread.topic.visibility !== "public" && (
|
||||
<span
|
||||
className="ftv-private"
|
||||
title={
|
||||
thread.topic.visibility === "members"
|
||||
? "Csak belépett tagok látják, a keresők sem"
|
||||
: "Zárt kör: csak a jóváhagyott tagok látják"
|
||||
}
|
||||
>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<rect x="5" y="11" width="14" height="9" rx="2" />
|
||||
<path d="M8 11V8a4 4 0 0 1 8 0v3" />
|
||||
</svg>
|
||||
{thread.topic.visibility === "members" ? "csak tagoknak" : "zárt kör"}
|
||||
</span>
|
||||
)}
|
||||
</nav>
|
||||
|
||||
<div className="ftv-toolbar">
|
||||
{member && access && (
|
||||
<button type="button" className="btn btn-sm" aria-pressed={access.following} onClick={toggleFollow}>
|
||||
{access.following ? "Követem ✓" : "Követem"}
|
||||
</button>
|
||||
)}
|
||||
{viewer.moderator && !thread.deleted && (
|
||||
<details className="ftv-mod">
|
||||
<summary className="btn btn-sm btn-ghost">Moderálás</summary>
|
||||
<div className="ftv-mod-menu">
|
||||
<button type="button" onClick={() => moderateThread({ locked: !thread.locked })}>
|
||||
{thread.locked ? "Szál feloldása" : "Szál lezárása"}
|
||||
</button>
|
||||
<button type="button" onClick={() => moderateThread({ pinned: !thread.pinned })}>
|
||||
{thread.pinned ? "Kitűzés levétele" : "Kitűzés"}
|
||||
</button>
|
||||
<button type="button" className="danger" onClick={removeThread}>
|
||||
Szál eltávolítása
|
||||
</button>
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{thread.deleted ? (
|
||||
<div className="fp fp-removed">
|
||||
<span>A moderátor eltávolította ezt a szálat.</span>
|
||||
{thread.deleted.reason && <span className="hint">Ok: {thread.deleted.reason}</span>}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<h1 className="ftv-title">
|
||||
{thread.pinned && <span className="ft-pin">Kitűzve</span>}
|
||||
{thread.locked && <span className="ft-pin">Lezárva</span>}
|
||||
{thread.title}
|
||||
</h1>
|
||||
{intent && (
|
||||
<p className="ftv-intent-line">
|
||||
<span className={`ft-intent ft-intent-${thread.intent}`}>{intent.label}</span>
|
||||
{thread.intent === "listen"
|
||||
? "tanács helyett elég, ha jelen vagy, és leírod, ha veled is történt hasonló"
|
||||
: `${starter} kíváncsi a véleményetekre és a tapasztalataitokra`}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{opening && <PostCard post={opening} page={page} actions={actions} isNew={false} />}
|
||||
|
||||
{(replies.length > 0 || !thread.deleted) && (
|
||||
<div className="ftv-count">
|
||||
<h2>{replies.filter((p) => !p.deleted).length} válasz</h2>
|
||||
<span className="hint">időrendben</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tops.map((top) => (
|
||||
<div key={top.id} className="ftv-branch">
|
||||
{markerTop === top.id && (
|
||||
<div className="ftv-marker" role="separator" aria-label={`Itt hagytad abba, ${unreadCount} új`}>
|
||||
<span>Itt hagytad abba · {unreadCount} új</span>
|
||||
</div>
|
||||
)}
|
||||
<PostCard
|
||||
post={top}
|
||||
page={page}
|
||||
actions={actions}
|
||||
isNew={firstUnread !== null && top.id >= firstUnread && !top.own}
|
||||
/>
|
||||
{childrenOf(top.id).length > 0 && (
|
||||
<div className="ftv-children">
|
||||
{childrenOf(top.id).map((child) => (
|
||||
<PostCard
|
||||
key={child.id}
|
||||
nested
|
||||
post={child}
|
||||
page={page}
|
||||
actions={actions}
|
||||
isNew={firstUnread !== null && child.id >= firstUnread && !child.own}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{replyTo && replyBranch === top.id && (
|
||||
<div className="ftv-inline" ref={inline}>
|
||||
<p className="ftv-replyto">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d="M9 14L4 9l5-5" />
|
||||
<path d="M4 9h10a6 6 0 0 1 6 6v4" />
|
||||
</svg>
|
||||
Válasz neki: <strong>{replyTo.author?.nickname ?? "Törölt tag"}</strong>
|
||||
</p>
|
||||
<Composer
|
||||
key={top.id}
|
||||
mentions
|
||||
onTyping={imTyping}
|
||||
id={`valasz-${top.id}`}
|
||||
label={`Válasz neki: ${replyTo.author?.nickname ?? "Törölt tag"}`}
|
||||
placeholder="Írd meg a válaszod…"
|
||||
initial={draft.current}
|
||||
onChange={(text) => {
|
||||
draft.current = text;
|
||||
}}
|
||||
busy={busy}
|
||||
onSubmit={(text) => sendReply(text, replyTo)}
|
||||
onCancel={() => {
|
||||
draft.current = "";
|
||||
setReplyTo(null);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{newCount > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
className="ftv-incoming"
|
||||
onClick={() => incoming && (setPage(incoming), setIncoming(null))}
|
||||
>
|
||||
{newCount === 1 ? "1 új válasz érkezett" : `${newCount} új válasz érkezett`}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<TypingLine text={typingNow} />
|
||||
|
||||
<div className="ftv-compose" id="valasz" ref={composer}>
|
||||
{thread.deleted ? null : !viewer.logged_in ? (
|
||||
<p className="ftv-gate">
|
||||
<Link href={`/belepes?vissza=/forum/szal/${thread.id}-${thread.slug}`}>Lépj be</Link>, hogy hozzászólhass.
|
||||
</p>
|
||||
) : viewer.needs_nickname ? (
|
||||
<p className="ftv-gate">
|
||||
<Link href={`/forum/beallitasok?vissza=/forum/szal/${thread.id}-${thread.slug}`}>Válassz álnevet</Link>,
|
||||
hogy hozzászólhass.
|
||||
</p>
|
||||
) : viewer.member?.banned ? (
|
||||
<p className="ftv-gate">Most nem írhatsz a fórumba.</p>
|
||||
) : !access?.can_reply ? (
|
||||
<p className="ftv-gate">
|
||||
{thread.topic.archived
|
||||
? "Ez a téma archivált: olvasható, de új hozzászólás nem írható."
|
||||
: "Ez a szál le van zárva, új hozzászólás nem írható."}
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<Composer
|
||||
mentions
|
||||
onTyping={imTyping}
|
||||
id="valasz-szoveg"
|
||||
label="Válaszod"
|
||||
placeholder={thread.topic.listening ? "Írd le, ami benned van…" : "Írd meg a válaszod…"}
|
||||
busy={busy}
|
||||
onSubmit={(text) => sendReply(text, null)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import type { LiveNotice } from "./ForumNav";
|
||||
|
||||
/** The live connection's outgoing "I am typing" (ForumNav sends it). */
|
||||
export interface TypingOut {
|
||||
kind: "thread" | "conversation";
|
||||
id: number;
|
||||
}
|
||||
|
||||
/** A typing notice is sent at most this often while typing. */
|
||||
const SEND_EVERY_MS = 3000;
|
||||
/** "X gépel…" disappears this long after the last notice. */
|
||||
const SHOW_MS = 6000;
|
||||
|
||||
/** Call on every keystroke: tells the others (now and then) that the member is typing here. */
|
||||
export function useTypingSender(kind: TypingOut["kind"], id: number) {
|
||||
const last = useRef(0);
|
||||
return useCallback(() => {
|
||||
const now = Date.now();
|
||||
if (now - last.current < SEND_EVERY_MS) return;
|
||||
last.current = now;
|
||||
window.dispatchEvent(new CustomEvent<TypingOut>("forum:typing-out", { detail: { kind, id } }));
|
||||
}, [kind, id]);
|
||||
}
|
||||
|
||||
/** Who is typing here now: "Holdfény gépel…", "Holdfény és Zöldág gépel…", or null. */
|
||||
export function useTypingWatch(kind: TypingOut["kind"], id: number): string | null {
|
||||
const [who, setWho] = useState<Record<string, number>>({});
|
||||
useEffect(() => {
|
||||
const live = (e: Event) => {
|
||||
const n = (e as CustomEvent<LiveNotice & { kind?: string; who?: string }>).detail;
|
||||
if (n.t === "typing" && n.kind === kind && n.id === id && n.who) {
|
||||
setWho((w) => ({ ...w, [n.who as string]: Date.now() }));
|
||||
}
|
||||
// Their post or message arrived: they are done.
|
||||
if ((n.t === "thread" && kind === "thread" && n.id === id) || (n.t === "conversation" && n.id === id)) {
|
||||
setWho({});
|
||||
}
|
||||
};
|
||||
window.addEventListener("forum:live", live);
|
||||
const timer = window.setInterval(() => {
|
||||
setWho((w) => {
|
||||
const now = Date.now();
|
||||
const kept = Object.fromEntries(Object.entries(w).filter(([, at]) => now - at < SHOW_MS));
|
||||
return Object.keys(kept).length === Object.keys(w).length ? w : kept;
|
||||
});
|
||||
}, 1000);
|
||||
return () => {
|
||||
window.removeEventListener("forum:live", live);
|
||||
window.clearInterval(timer);
|
||||
};
|
||||
}, [kind, id]);
|
||||
const names = Object.keys(who);
|
||||
if (names.length === 0) return null;
|
||||
if (names.length === 1) return `${names[0]} gépel…`;
|
||||
if (names.length === 2) return `${names[0]} és ${names[1]} gépel…`;
|
||||
return `${names.length} tag gépel…`;
|
||||
}
|
||||
|
||||
/** The "… gépel" line with three soft dots. */
|
||||
export function TypingLine({ text }: { text: string | null }) {
|
||||
return (
|
||||
<p className="ftyping" aria-live="polite">
|
||||
{text && (
|
||||
<>
|
||||
<span className="ftyping-dots" aria-hidden="true">
|
||||
<span />
|
||||
<span />
|
||||
<span />
|
||||
</span>
|
||||
{text}
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
@@ -58,6 +58,7 @@ export const ROLE_LABELS: Record<string, string> = {
|
||||
premium: "Prémium",
|
||||
vip: "VIP",
|
||||
creator: "Szerző",
|
||||
moderator: "Moderátor",
|
||||
admin: "Admin",
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
// The old forums' character smileys, turned into emoji while typing (the
|
||||
// forum service converts the same list on save: services/forum/src/text.rs).
|
||||
// A smiley converts only standing alone, once a space or line break follows
|
||||
// it, so links and the like stay as typed.
|
||||
|
||||
export const EMOTICONS: [string, string][] = [
|
||||
[":)", "🙂"],
|
||||
[":-)", "🙂"],
|
||||
["(:", "🙂"],
|
||||
[":D", "😄"],
|
||||
[":-D", "😄"],
|
||||
["xD", "😆"],
|
||||
["XD", "😆"],
|
||||
[";)", "😉"],
|
||||
[";-)", "😉"],
|
||||
[":(", "🙁"],
|
||||
[":-(", "🙁"],
|
||||
[":'(", "😢"],
|
||||
[":P", "😛"],
|
||||
[":-P", "😛"],
|
||||
[":p", "😛"],
|
||||
[":O", "😮"],
|
||||
[":o", "😮"],
|
||||
[":-O", "😮"],
|
||||
[":*", "😘"],
|
||||
[":-*", "😘"],
|
||||
[":/", "😕"],
|
||||
[":|", "😐"],
|
||||
["B)", "😎"],
|
||||
["^^", "😊"],
|
||||
["^_^", "😊"],
|
||||
["<3", "❤️"],
|
||||
["</3", "💔"],
|
||||
];
|
||||
|
||||
const LOOKUP = new Map(EMOTICONS);
|
||||
const ALTERNATIVES = [...LOOKUP.keys()]
|
||||
.sort((a, b) => b.length - a.length)
|
||||
.map((code) => code.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
|
||||
.join("|");
|
||||
|
||||
/**
|
||||
* The text with its finished smileys as emoji, and where the caret goes.
|
||||
* `atEnd`: also a smiley at the very end (when sending).
|
||||
*/
|
||||
export function convertEmoticons(text: string, caret: number, atEnd = false): { text: string; caret: number } {
|
||||
const pattern = new RegExp(`(^|\\s)(${ALTERNATIVES})(?=\\s${atEnd ? "|$" : ""})`, "g");
|
||||
let shift = 0;
|
||||
const converted = text.replace(pattern, (match, space: string, code: string, offset: number) => {
|
||||
const emoji = LOOKUP.get(code) ?? code;
|
||||
if (offset + space.length < caret) shift += emoji.length - code.length;
|
||||
return space + emoji;
|
||||
});
|
||||
return { text: converted, caret: caret + shift };
|
||||
}
|
||||
|
||||
/**
|
||||
* For a text field's change: converts and puts the caret back where it was
|
||||
* (a controlled field would jump it to the end).
|
||||
*/
|
||||
export function withEmoji(e: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>, set: (text: string) => void) {
|
||||
const el = e.target;
|
||||
const { text, caret } = convertEmoticons(el.value, el.selectionStart ?? el.value.length);
|
||||
set(text);
|
||||
if (text !== el.value) {
|
||||
requestAnimationFrame(() => el.setSelectionRange(caret, caret));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
// The forum's data as the forum service sends it, and small helpers shared
|
||||
// by its server and client components.
|
||||
|
||||
/** The forum's colours: light by default, dark on request (a cookie). */
|
||||
export const FORUM_THEME_COOKIE = "sf_forum_theme";
|
||||
export type ForumTheme = "light" | "dark";
|
||||
|
||||
export type Rank = "vandor" | "kereso" | "fono" | "csillagfono" | "sorsfono";
|
||||
export type ReactionKind = "with_you" | "thanks" | "me_too" | "insight";
|
||||
export type ChartShare = "none" | "sun" | "big3" | "planets";
|
||||
|
||||
/** How a member appears next to what they wrote. */
|
||||
export interface ForumAuthor {
|
||||
nickname: string;
|
||||
avatar: string;
|
||||
rank: Rank;
|
||||
rank_name: string;
|
||||
moderator: boolean;
|
||||
online: boolean;
|
||||
/** Planet (or `ascendant`) → sign, as the member chose to share. */
|
||||
signs: Record<string, string> | null;
|
||||
/** A volunteer companion ("Kísérő") for the threads asking to be heard. */
|
||||
listener?: boolean;
|
||||
/** Bought a package and shows the "Támogató" badge. */
|
||||
supporter?: boolean;
|
||||
/** One of the first hundred members ("Alapító tag"). */
|
||||
founder?: boolean;
|
||||
}
|
||||
|
||||
export interface ForumViewer {
|
||||
logged_in: boolean;
|
||||
needs_nickname: boolean;
|
||||
moderator: boolean;
|
||||
member: { nickname: string; avatar: string; rank: Rank; rank_name: string; banned: boolean } | null;
|
||||
}
|
||||
|
||||
export interface TopicRef {
|
||||
slug: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface ForumTopic extends TopicRef {
|
||||
id: number;
|
||||
description: string;
|
||||
visibility: "public" | "members" | "restricted";
|
||||
listening: boolean;
|
||||
/** Archived: readable, but takes nothing new. */
|
||||
archived?: boolean;
|
||||
readable: boolean;
|
||||
/** A restricted topic: the viewer's place in it. */
|
||||
membership?: "none" | "pending" | "approved" | null;
|
||||
thread_count?: number;
|
||||
new_count?: number | null;
|
||||
last?: { author: ForumAuthor | null; at: string } | null;
|
||||
}
|
||||
|
||||
export interface ThreadCard {
|
||||
id: number;
|
||||
slug: string;
|
||||
title: string;
|
||||
intent: "listen" | "advice" | null;
|
||||
topic: TopicRef;
|
||||
author: ForumAuthor | null;
|
||||
created_at: string;
|
||||
last_post_at: string;
|
||||
reply_count: number;
|
||||
participants: number;
|
||||
pinned: boolean;
|
||||
locked: boolean;
|
||||
unread: number | null;
|
||||
/** The site's own thread (the daily sky). */
|
||||
system?: boolean;
|
||||
}
|
||||
|
||||
export interface ForumHome {
|
||||
viewer: ForumViewer;
|
||||
followed: { new_replies: number; threads: number } | null;
|
||||
/** Unread answers to the member. */
|
||||
replies: number | null;
|
||||
/** Listeners: threads asking to be heard that wait for a reply. */
|
||||
waiting: number | null;
|
||||
/** "Most itt vannak". */
|
||||
online: ForumAuthor[];
|
||||
topics: ForumTopic[];
|
||||
unanswered: ThreadCard[];
|
||||
hot: ThreadCard[];
|
||||
}
|
||||
|
||||
export interface TopicPage {
|
||||
viewer: ForumViewer;
|
||||
topic: TopicRef & { description: string; visibility: string; listening: boolean; archived?: boolean };
|
||||
threads: ThreadCard[];
|
||||
page: number;
|
||||
has_more: boolean;
|
||||
}
|
||||
|
||||
export interface ForumPost {
|
||||
id: number;
|
||||
parent_id: number | null;
|
||||
is_opening: boolean;
|
||||
author: ForumAuthor | null;
|
||||
own: boolean;
|
||||
body: string | null;
|
||||
deleted: { by_moderator: boolean; reason: string | null } | null;
|
||||
created_at: string;
|
||||
edited_at: string | null;
|
||||
helped: boolean;
|
||||
reactions: Record<ReactionKind, number>;
|
||||
score: number;
|
||||
collapsed: boolean;
|
||||
mine: ReactionKind | "down" | null;
|
||||
/** Moderators only. */
|
||||
down?: number;
|
||||
/** The nicknames the post names ("@Holdfény"). */
|
||||
mentions?: string[];
|
||||
/** Written by the site itself (the daily sky). */
|
||||
system?: boolean;
|
||||
/** The post this reply answered (it may sit on the same level). */
|
||||
reply_to?: { id: number; nickname: string | null } | null;
|
||||
/** The viewer muted the author: shown folded up. */
|
||||
muted?: boolean;
|
||||
/** A chart, forecast or synastry shared with the question. */
|
||||
share?: ShareCardData | null;
|
||||
/** Previews of the links a provider knows (YouTube for now). */
|
||||
links?: LinkPreview[] | null;
|
||||
}
|
||||
|
||||
/** A link the forum's link module knows, under a post. */
|
||||
export interface LinkPreview {
|
||||
provider: "youtube";
|
||||
id: string;
|
||||
/** As written in the post. */
|
||||
url: string;
|
||||
/** Where to start playing, in seconds. */
|
||||
start: number | null;
|
||||
title: string;
|
||||
author: string | null;
|
||||
/** Our own copy of the thumbnail. */
|
||||
thumbnail: string | null;
|
||||
}
|
||||
|
||||
/** A shared chart in a post: in full for members, `locked` for visitors, `revoked` when taken down. */
|
||||
export interface ShareCardData {
|
||||
slug?: string;
|
||||
kind: "chart" | "synastry" | "forecast";
|
||||
locked?: boolean;
|
||||
revoked?: boolean;
|
||||
title?: string;
|
||||
summary?: string | null;
|
||||
points?: { id: string; sign: string; degree: number | null; house: number | null }[];
|
||||
time_known?: boolean;
|
||||
}
|
||||
|
||||
export interface ThreadPage {
|
||||
viewer: ForumViewer;
|
||||
thread: {
|
||||
id: number;
|
||||
slug: string;
|
||||
title: string;
|
||||
intent: "listen" | "advice" | null;
|
||||
topic: TopicRef & { visibility: string; listening: boolean; archived?: boolean };
|
||||
author: ForumAuthor | null;
|
||||
created_at: string;
|
||||
locked: boolean;
|
||||
pinned: boolean;
|
||||
deleted: { reason: string | null } | null;
|
||||
system?: boolean;
|
||||
};
|
||||
posts: ForumPost[];
|
||||
access?: {
|
||||
can_reply: boolean;
|
||||
can_downvote: boolean;
|
||||
is_thread_author: boolean;
|
||||
following: boolean;
|
||||
last_read_post_id: number | null;
|
||||
};
|
||||
}
|
||||
|
||||
export interface EmailSettings {
|
||||
replies: "off" | "daily" | "instant";
|
||||
followed: "off" | "daily";
|
||||
messages: "off" | "instant";
|
||||
mentions: "off" | "instant";
|
||||
listener: "off" | "instant";
|
||||
weekly: boolean;
|
||||
}
|
||||
|
||||
export interface ForumMe {
|
||||
viewer: ForumViewer;
|
||||
member: {
|
||||
nickname: string;
|
||||
avatar: string;
|
||||
bio: string;
|
||||
chart_share: ChartShare;
|
||||
invisible: boolean;
|
||||
points: number;
|
||||
post_count: number;
|
||||
created_at: string;
|
||||
rank: Rank;
|
||||
rank_name: string;
|
||||
next_rank: { rank: Rank; name: string; points: number; days: number } | null;
|
||||
nickname_change_after: string | null;
|
||||
banned_until: string | null;
|
||||
ban_reason: string | null;
|
||||
email: EmailSettings;
|
||||
listener: boolean;
|
||||
supporter_badge: boolean;
|
||||
can_listen: boolean;
|
||||
can_upload_avatar: boolean;
|
||||
} | null;
|
||||
chart: Record<Exclude<ChartShare, "none">, Record<string, string> | null> | null;
|
||||
/** Bought a package: may show the "Támogató" badge. */
|
||||
can_supporter: boolean;
|
||||
}
|
||||
|
||||
export interface MemberProfile {
|
||||
viewer: ForumViewer;
|
||||
relation: MemberRelation | null;
|
||||
member: {
|
||||
author: ForumAuthor;
|
||||
bio: string;
|
||||
created_at: string;
|
||||
post_count: number;
|
||||
thread_count: number;
|
||||
last_seen: "online" | "day" | "week" | "earlier" | null;
|
||||
own: boolean;
|
||||
/** The viewer muted them. */
|
||||
muted: boolean;
|
||||
banned_until: string | null;
|
||||
ban_reason: string | null;
|
||||
};
|
||||
recent: {
|
||||
id: number;
|
||||
thread_id: number;
|
||||
thread_slug: string;
|
||||
thread_title: string;
|
||||
topic: TopicRef;
|
||||
created_at: string;
|
||||
excerpt: string;
|
||||
is_opening: boolean;
|
||||
}[];
|
||||
}
|
||||
|
||||
export interface ModLogEntry {
|
||||
id: number;
|
||||
actor: string | null;
|
||||
actor_kind: "human" | "ai";
|
||||
action: string;
|
||||
target: string | null;
|
||||
thread: { id: number; title: string | null } | null;
|
||||
post_id: number | null;
|
||||
reason: string | null;
|
||||
until: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export const REACTIONS: { kind: ReactionKind; emoji: string; label: string }[] = [
|
||||
{ kind: "with_you", emoji: "🤍", label: "Veled vagyok" },
|
||||
{ kind: "thanks", emoji: "🙏", label: "Köszönöm" },
|
||||
{ kind: "me_too", emoji: "✨", label: "Rám is igaz" },
|
||||
{ kind: "insight", emoji: "💡", label: "Érdekes gondolat" },
|
||||
];
|
||||
|
||||
export const INTENTS = {
|
||||
listen: { label: "Csak meghallgatást kér", short: "Meghallgatást kér" },
|
||||
advice: { label: "Tanácsot, véleményt kér", short: "Tanácsot kér" },
|
||||
} as const;
|
||||
|
||||
/** `/forum/szal/123-nem-tudom-elengedni`: the number decides, the words are for reading. */
|
||||
export function threadHref(t: { id: number; slug: string }, postId?: number): string {
|
||||
const path = t.slug ? `/forum/szal/${t.id}-${t.slug}` : `/forum/szal/${t.id}`;
|
||||
return postId ? `${path}#h${postId}` : path;
|
||||
}
|
||||
|
||||
/** The address of an uploaded avatar (`upload:<file>`), or null for a starter one. */
|
||||
export function uploadedAvatar(avatar: string | null | undefined): string | null {
|
||||
return avatar?.startsWith("upload:") ? `/api/v1/forum/avatars/${encodeURIComponent(avatar.slice(7))}` : null;
|
||||
}
|
||||
|
||||
export function memberHref(nickname: string): string {
|
||||
return `/forum/tag/${encodeURIComponent(nickname)}`;
|
||||
}
|
||||
|
||||
/** "most", "12 perce", "3 órája", "tegnap", "4 napja", then the date. */
|
||||
export function ago(iso: string, now: Date = new Date()): string {
|
||||
const then = new Date(iso);
|
||||
const minutes = Math.floor((now.getTime() - then.getTime()) / 60000);
|
||||
if (minutes < 1) return "most";
|
||||
if (minutes < 60) return `${minutes} perce`;
|
||||
const hours = Math.floor(minutes / 60);
|
||||
if (hours < 24) return `${hours} órája`;
|
||||
const days = Math.floor(hours / 24);
|
||||
if (days === 1) return "tegnap";
|
||||
if (days < 7) return `${days} napja`;
|
||||
return then.toLocaleDateString("hu-HU", {
|
||||
timeZone: "Europe/Budapest",
|
||||
year: then.getFullYear() === now.getFullYear() ? undefined : "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
});
|
||||
}
|
||||
|
||||
/** A ban's end as the member reads it. */
|
||||
export function banText(until: string | null): string {
|
||||
if (!until) return "";
|
||||
if (until === "infinity") return "véglegesen";
|
||||
return `eddig: ${new Date(until).toLocaleString("hu-HU", { timeZone: "Europe/Budapest", month: "long", day: "numeric", hour: "2-digit", minute: "2-digit" })}`;
|
||||
}
|
||||
|
||||
/** The viewer's relation to a member (profile page). */
|
||||
export interface MemberRelation {
|
||||
conversation_id: number | null;
|
||||
state: ConversationState | null;
|
||||
can_request: boolean;
|
||||
eligible: boolean;
|
||||
}
|
||||
|
||||
export type ConversationState = "accepted" | "incoming" | "outgoing" | "expired" | "blocked_by_me" | "closed";
|
||||
|
||||
export interface ConversationItem {
|
||||
id: number;
|
||||
other: ForumAuthor | null;
|
||||
state: ConversationState;
|
||||
intro: string;
|
||||
created_at: string;
|
||||
last_message_at: string | null;
|
||||
last_message: { excerpt: string; mine: boolean } | null;
|
||||
unread: number;
|
||||
}
|
||||
|
||||
export interface ChatMessage {
|
||||
id: number;
|
||||
mine: boolean;
|
||||
body: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface ConversationPage {
|
||||
viewer: ForumViewer;
|
||||
conversation: {
|
||||
id: number;
|
||||
other: ForumAuthor | null;
|
||||
state: ConversationState;
|
||||
intro: string;
|
||||
requested_by_me: boolean;
|
||||
created_at: string;
|
||||
};
|
||||
messages: ChatMessage[];
|
||||
}
|
||||
|
||||
export type ReportKind = "spam" | "ad" | "rude" | "crisis" | "illegal" | "other";
|
||||
|
||||
export const REPORT_KINDS: { kind: ReportKind; label: string }[] = [
|
||||
{ kind: "rude", label: "Bántó, kioktató vagy sértő" },
|
||||
{ kind: "ad", label: "Szolgáltatást hirdet (jóslás, gyógyítás, tanfolyam)" },
|
||||
{ kind: "spam", label: "Kéretlen reklám, spam" },
|
||||
{ kind: "crisis", label: "Aggódom érte: lelki krízisben lehet" },
|
||||
{ kind: "illegal", label: "Jogsértő tartalom" },
|
||||
{ kind: "other", label: "Más (írd le)" },
|
||||
];
|
||||
|
||||
export interface ReportEntry {
|
||||
id: number;
|
||||
kind: ReportKind;
|
||||
note: string;
|
||||
reporter: string;
|
||||
status: "open" | "resolved" | "dismissed";
|
||||
handled_by: string | null;
|
||||
handled_at: string | null;
|
||||
created_at: string;
|
||||
open_reports_of_target: number;
|
||||
target:
|
||||
| {
|
||||
type: "post";
|
||||
id: number;
|
||||
thread: { id: number; title: string; slug: string };
|
||||
author: ForumAuthor | null;
|
||||
body: string;
|
||||
deleted: boolean;
|
||||
}
|
||||
| {
|
||||
type: "message";
|
||||
id: number;
|
||||
conversation_id: number | null;
|
||||
messages: { id: number; sender: ForumAuthor | null; body: string; created_at: string; reported: boolean }[];
|
||||
}
|
||||
| null;
|
||||
}
|
||||
|
||||
/** The forum menu's counts. */
|
||||
export interface ForumNavData {
|
||||
viewer: ForumViewer;
|
||||
/** Unread answers to the member (a reply to them, in their thread, or naming them). */
|
||||
replies: number | null;
|
||||
messages: number | null;
|
||||
/** Moderators: open reports and requests to join restricted topics. */
|
||||
reports: number | null;
|
||||
}
|
||||
|
||||
/** An answer to the member, on the "Válaszok" page. */
|
||||
export interface ReplyEntry {
|
||||
id: number;
|
||||
thread: { id: number; title: string; slug: string };
|
||||
author: ForumAuthor | null;
|
||||
excerpt: string;
|
||||
created_at: string;
|
||||
/** `reply`: to one of their posts; `thread`: in their thread; `mention`: names them. */
|
||||
kind: "reply" | "thread" | "mention";
|
||||
unread: boolean;
|
||||
}
|
||||
|
||||
export interface TopicRequest {
|
||||
topic: TopicRef;
|
||||
member: ForumAuthor | null;
|
||||
status: "pending" | "approved";
|
||||
note: string;
|
||||
requested_at: string;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// Forum service calls from server components, with the visitor's session.
|
||||
// Without FORUM_URL the forum is switched off (no menu item, its pages 404).
|
||||
import "server-only";
|
||||
|
||||
import { cookies } from "next/headers";
|
||||
|
||||
import { BackendError, SESSION_COOKIE } from "./server";
|
||||
|
||||
export const FORUM_URL = (process.env.FORUM_URL ?? "").replace(/\/$/, "");
|
||||
|
||||
export function forumEnabled(): boolean {
|
||||
return FORUM_URL !== "";
|
||||
}
|
||||
|
||||
/** The answer of a forum GET: the data, or why there is none. */
|
||||
export type ForumResult<T> = { ok: true; data: T } | { ok: false; status: 401 | 404 };
|
||||
|
||||
/** GET from the forum service as the visitor (logged in or not). */
|
||||
export async function forumGet<T>(path: string): Promise<ForumResult<T>> {
|
||||
if (!forumEnabled()) return { ok: false, status: 404 };
|
||||
const token = (await cookies()).get(SESSION_COOKIE)?.value;
|
||||
const headers: HeadersInit = token ? { authorization: `Bearer ${token}` } : {};
|
||||
const res = await fetch(`${FORUM_URL}${path}`, { headers, cache: "no-store" });
|
||||
if (res.status === 401 || res.status === 404) return { ok: false, status: res.status };
|
||||
// Not allowed (e.g. the moderation log for a member): the page does not exist for them.
|
||||
if (res.status === 403) return { ok: false, status: 404 };
|
||||
if (!res.ok) throw new BackendError(res.status, `${path}: HTTP ${res.status}`);
|
||||
return { ok: true, data: (await res.json()) as T };
|
||||
}
|
||||
|
||||
/** The public forum pages for the sitemap (nothing when the forum is off or does not answer). */
|
||||
export async function forumSitemap(): Promise<{
|
||||
topics: { slug: string; updated: string | null }[];
|
||||
threads: { id: number; slug: string; updated: string }[];
|
||||
}> {
|
||||
const empty = { topics: [], threads: [] };
|
||||
if (!forumEnabled()) return empty;
|
||||
try {
|
||||
const res = await fetch(`${FORUM_URL}/v1/forum/sitemap`, { next: { revalidate: 3600 } });
|
||||
return res.ok ? await res.json() : empty;
|
||||
} catch {
|
||||
return empty;
|
||||
}
|
||||
}
|
||||
@@ -18,8 +18,8 @@ export const ARBITRATION_BOARD = {
|
||||
web: "https://panaszrendezes.hu",
|
||||
};
|
||||
|
||||
export const PRIVACY_UPDATED = "2026. november 24.";
|
||||
export const PRIVACY_UPDATED_EN = "24 November 2026";
|
||||
export const PRIVACY_UPDATED = "2026. november 26.";
|
||||
export const PRIVACY_UPDATED_EN = "26 November 2026";
|
||||
|
||||
/** The terms (ÁSZF) in force; the backend records this version with every purchase (TERMS_VERSION). */
|
||||
export const TERMS_UPDATED = "2026. november 23.";
|
||||
export const TERMS_UPDATED = "2026. november 26.";
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user