Forum: daily sky thread, listeners, mentions, own avatars, restricted topics

- The worker opens a "Mai égbolt" thread every morning from the day's sky
  (no AI), pinned for the day.
- Volunteer listeners (from the Kereső rank) get a badge, a count of the
  threads asking to be heard that still wait for a reply, and, if they ask,
  an e-mail after two hours of waiting.
- "@Holdfény" names a member (nicknames with spaces too): they follow the
  thread, hear of it live and, if they asked, by e-mail; a search helps
  typing it.
- From the Kereső rank a member may upload an own avatar: a small square
  JPEG without metadata in the object storage (now a shared crate with the
  backend), served by the forum; moderators can put the starter back.
- The "Támogató" badge for buyers who switch it on.
- The admin creates and edits topics; restricted ones are read by their
  approved members, who ask to join and moderators decide.
- "Most itt vannak" on the front page; the weekly summary e-mail on Sunday
  evening for those who ask (off by default).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-26 12:37:52 +00:00
co-authored by Claude Opus 5.5
parent 0a2308c491
commit 564c22176f
31 changed files with 2226 additions and 320 deletions
+1 -1
View File
@@ -60,7 +60,7 @@ jobs:
# astro-engine and horoscope-api need the Swiss Ephemeris sources and
# data (scripts/fetch-deps.sh); their tests run locally.
- name: Test
run: cargo test --locked -p backend -p worker -p forum -p db -p horoscope-client -p service-kit -p analysis-prompt -p email-templates
run: cargo test --locked -p backend -p worker -p forum -p object-storage -p db -p horoscope-client -p service-kit -p analysis-prompt -p email-templates
build:
needs: test
Generated
+19
View File
@@ -198,6 +198,7 @@ dependencies = [
"http-body-util",
"image",
"jsonwebtoken",
"object-storage",
"password-hash",
"rand 0.9.5",
"reqwest",
@@ -713,9 +714,12 @@ dependencies = [
"deunicode",
"futures-util",
"http-body-util",
"image",
"object-storage",
"serde",
"serde_json",
"service-kit",
"sha2",
"sqlx",
"thiserror",
"time",
@@ -1629,6 +1633,20 @@ dependencies = [
"libm",
]
[[package]]
name = "object-storage"
version = "0.1.0"
dependencies = [
"bytes",
"hmac",
"reqwest",
"sha2",
"thiserror",
"time",
"tokio",
"tracing",
]
[[package]]
name = "once_cell"
version = "1.21.4"
@@ -3560,6 +3578,7 @@ dependencies = [
"axum",
"base64 0.22.1",
"db",
"deunicode",
"email-templates",
"gift-card",
"hmac",
+2
View File
@@ -10,6 +10,7 @@ members = [
"crates/analysis-prompt",
"crates/email-templates",
"crates/gift-card",
"crates/object-storage",
"services/horoscope-api",
"services/backend",
"services/worker",
@@ -32,6 +33,7 @@ horoscope-client = { path = "crates/horoscope-client" }
analysis-prompt = { path = "crates/analysis-prompt" }
email-templates = { path = "crates/email-templates" }
gift-card = { path = "crates/gift-card" }
object-storage = { path = "crates/object-storage" }
anyhow = "1"
argon2 = { version = "0.5", features = ["std"] }
+55
View File
@@ -0,0 +1,55 @@
-- The forum, more (docs/kozosseg.md): the daily sky thread, volunteer
-- listeners, mentions, the weekly summary, the supporter badge, and
-- restricted topics with approval. (Own avatars need no column: the avatar
-- holds `upload:<file>` then.)
-- The site's own threads and posts (the daily "Mai égbolt"): no member author.
ALTER TABLE forum.threads ADD COLUMN system boolean NOT NULL DEFAULT false;
-- The daily sky thread of that day (one a day).
ALTER TABLE forum.threads ADD COLUMN daily_date date UNIQUE;
ALTER TABLE forum.posts ADD COLUMN system boolean NOT NULL DEFAULT false;
-- Volunteer listeners: told when a thread asking to be heard waits for a reply.
ALTER TABLE forum.members ADD COLUMN listener boolean NOT NULL DEFAULT false;
ALTER TABLE forum.members ADD COLUMN email_listener text NOT NULL DEFAULT 'off'
CHECK (email_listener IN ('off', 'instant'));
-- The listeners were told about this thread (once).
ALTER TABLE forum.threads ADD COLUMN listeners_notified_at timestamptz;
-- "@Holdfény" in a post: whom it names.
CREATE TABLE forum.mentions (
post_id bigint NOT NULL REFERENCES forum.posts ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (post_id, user_id)
);
CREATE INDEX mentions_user_idx ON forum.mentions (user_id, created_at DESC);
ALTER TABLE forum.members ADD COLUMN email_mentions text NOT NULL DEFAULT 'instant'
CHECK (email_mentions IN ('off', 'instant'));
-- The weekly summary e-mail: off until the member asks for it.
ALTER TABLE forum.members ADD COLUMN email_weekly boolean NOT NULL DEFAULT false;
ALTER TABLE forum.members ADD COLUMN weekly_sent_at timestamptz;
-- The "Támogató" badge: only for buyers, and only when they switch it on.
ALTER TABLE forum.members ADD COLUMN supporter_badge boolean NOT NULL DEFAULT false;
-- Members of a restricted topic: they ask, a moderator approves.
CREATE TABLE forum.topic_members (
topic_id smallint NOT NULL REFERENCES forum.topics ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE,
status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'approved')),
-- A few words from the member asking to join.
note text NOT NULL DEFAULT '',
requested_at timestamptz NOT NULL DEFAULT now(),
decided_at timestamptz,
decided_by uuid REFERENCES users ON DELETE SET NULL,
PRIMARY KEY (topic_id, user_id)
);
CREATE INDEX topic_members_user_idx ON forum.topic_members (user_id) WHERE status = 'approved';
ALTER TABLE forum.mod_log DROP CONSTRAINT mod_log_action_check;
ALTER TABLE forum.mod_log ADD CONSTRAINT mod_log_action_check
CHECK (action IN ('delete_post', 'restore_post', 'delete_thread', 'restore_thread', 'ban', 'unban',
'lock', 'unlock', 'pin', 'unpin', 'resolve_report', 'dismiss_report',
'approve_member', 'reject_member', 'remove_member', 'reset_avatar', 'topic'));
+100
View File
@@ -187,6 +187,9 @@ pub fn render(template: &str, locale: &str, payload: &Value) -> Result<Rendered,
("forum_digest", _) => forum_digest(payload, url)?,
("forum_message", _) => forum_message(payload, url)?,
("forum_moderation", _) => forum_moderation(payload, url)?,
("forum_mention", _) => forum_mention(payload, url)?,
("forum_listener", _) => forum_listener(payload, url)?,
("forum_weekly", _) => forum_weekly(payload, url)?,
("forum_report_result", _) => forum_report_result(payload, url)?,
_ => return Err(TemplateError::UnknownTemplate(template.to_owned())),
};
@@ -361,6 +364,90 @@ fn forum_reply(payload: &Value, url: String) -> Result<Content, TemplateError> {
forum_footer(payload, content, "a fórumon azonnali értesítést kértél a válaszokról")
}
/// Someone named the member ("@Holdfény") in a post.
fn forum_mention(payload: &Value, url: String) -> Result<Content, TemplateError> {
let author = name(payload, "author").unwrap_or_else(|| "Valaki".into());
let title = name(payload, "thread_title").ok_or(TemplateError::MissingField("thread_title"))?;
let content = Content {
subject: format!("{author} megemlített: „{title}”"),
preheader: excerpt(payload, "excerpt", 90),
greeting: hello(payload),
intro: format!("{author} megemlített a Sorsfonalak fórumán, a(z) „{title}” szálban:"),
quote: excerpt(payload, "excerpt", 300),
points: None,
code: None,
button: "Megnézem",
url,
note: "Az említésekről szóló leveleket a fórumprofilodnál kapcsolhatod ki.".into(),
reason: None,
unsubscribe: None,
unsubscribe_post_url: None,
};
forum_footer(payload, content, "a fórumon értesítést kértél, ha megemlítenek")
}
/// For a volunteer listener: a thread asking to be heard waits for a reply.
fn forum_listener(payload: &Value, url: String) -> Result<Content, TemplateError> {
let title = name(payload, "thread_title").ok_or(TemplateError::MissingField("thread_title"))?;
let content = Content {
subject: format!("Válaszra vár: „{title}”"),
preheader: Some("Valaki meghallgatást kért, és még senki nem válaszolt.".into()),
greeting: hello(payload),
intro: format!(
"A(z) „{title}” szálban valaki meghallgatást kért, és még senki nem válaszolt neki. Ha van rá időd, egy pár soros válasz is sokat jelenthet."
),
quote: None,
points: None,
code: None,
button: "Elolvasom",
url,
note: "Tanács helyett elég, ha leírod, hogy itt vagy, vagy hogy veled is történt hasonló.".into(),
reason: None,
unsubscribe: None,
unsubscribe_post_url: None,
};
forum_footer(payload, content, "önkéntes meghallgatóként értesítést kértél a válasz nélküli szálakról")
}
/// The weekly summary: the busiest threads, and those still waiting.
fn forum_weekly(payload: &Value, url: String) -> Result<Content, TemplateError> {
let lines = |key: &'static str| -> Vec<String> {
payload[key]
.as_array()
.into_iter()
.flatten()
.filter_map(|l| l.as_str())
.map(|l| l.chars().filter(|c| !c.is_control()).take(160).collect())
.collect()
};
let busy = lines("busy");
let waiting = lines("waiting");
if busy.is_empty() && waiting.is_empty() {
return Err(TemplateError::MissingField("busy"));
}
let mut items = busy;
if !waiting.is_empty() {
items.push("Még válaszra vár:".into());
items.extend(waiting.into_iter().map(|w| format!(" {w}")));
}
let content = Content {
subject: "A hét a fórumon".into(),
preheader: items.first().cloned(),
greeting: hello(payload),
intro: "Ezekről beszélgettünk a héten a Sorsfonalak fórumán:".into(),
quote: None,
points: Some(("A hét szálai:", items)),
code: None,
button: "Benézek a fórumra",
url,
note: "Hetente egyszer, vasárnap este küldjük, ha kérted.".into(),
reason: None,
unsubscribe: None,
unsubscribe_post_url: None,
};
forum_footer(payload, content, "a fórumon heti összefoglalót kértél")
}
/// The daily digest: the threads with new posts for the member.
fn forum_digest(payload: &Value, url: String) -> Result<Content, TemplateError> {
let lines: Vec<String> = payload["lines"]
@@ -1367,5 +1454,18 @@ mod tests {
let m = render("forum_report_result", "hu", &json!({"url": "u", "outcome": "no_violation"})).unwrap();
assert!(m.text.starts_with("Szia!") && m.text.contains("a tartalom marad"));
assert!(render("forum_report_result", "hu", &json!({"url": "u"})).is_err());
let mut p = forum_links();
p["author"] = json!("Zöldág");
p["thread_title"] = json!("Téli levesek");
p["excerpt"] = json!("@Csendesvíz szerinted?");
assert_eq!(render("forum_mention", "hu", &p).unwrap().subject, "Zöldág megemlített: „Téli levesek”");
let m = render("forum_listener", "hu", &p).unwrap();
assert_eq!(m.subject, "Válaszra vár: „Téli levesek”");
let mut p = forum_links();
p["busy"] = json!(["„Téli levesek” – 12 hozzászólás"]);
p["waiting"] = json!(["„Nehéz napok”"]);
let m = render("forum_weekly", "hu", &p).unwrap();
assert!(m.text.contains("Még válaszra vár") && m.unsubscribe_post_url.is_some());
}
}
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "object-storage"
description = "S3-compatible object storage (DigitalOcean Spaces, RustFS) for the Sorsfonalak services"
edition.workspace = true
version.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
bytes = "1"
hmac.workspace = true
reqwest.workspace = true
sha2.workspace = true
thiserror.workspace = true
time.workspace = true
tracing.workspace = true
[dev-dependencies]
tokio.workspace = true
+294
View File
@@ -0,0 +1,294 @@
//! Object storage for uploaded pictures (the backend's photos, the forum's
//! avatars): any S3-compatible service, addressed path-style
//! (`{endpoint}/{bucket}/{key}`). In production DigitalOcean Spaces, in
//! development a RustFS container.
//!
//! The bucket stays private: the services read the objects themselves and
//! serve them (the backend under `/v1/public/photos/...`, the forum under
//! `/v1/forum/avatars/...`).
//!
//! Requests are signed with AWS Signature Version 4.
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: bytes::Bytes,
pub content_type: Option<String>,
}
impl StorageConfig {
/// From `S3_ENDPOINT`, `S3_BUCKET`, `S3_REGION` (default `us-east-1`),
/// `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY`; `None` without an endpoint.
pub fn from_env() -> Result<Option<Self>, String> {
let var = |name: &str| std::env::var(name).ok().filter(|v| !v.trim().is_empty());
let Some(endpoint) = var("S3_ENDPOINT") else { return Ok(None) };
let required = |name: &str| var(name).ok_or_else(|| format!("{name} is required with S3_ENDPOINT"));
Ok(Some(Self {
endpoint: endpoint.trim_end_matches('/').to_string(),
bucket: required("S3_BUCKET")?,
region: var("S3_REGION").unwrap_or_else(|| "us-east-1".into()),
access_key: required("S3_ACCESS_KEY_ID")?,
secret_key: required("S3_SECRET_ACCESS_KEY")?,
}))
}
}
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 object-storage 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();
}
}
+11 -1
View File
@@ -134,8 +134,10 @@ services:
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-worker:${TAG:-latest}
environment:
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
# forum: the forum's daily e-mail digest.
# forum: the forum's digests, daily sky thread, listener e-mails, weekly summary.
WORKER_TASKS: email,cleanup,invoices,notify,forum
# The sky of the forum's daily thread.
BACKEND_URL: http://backend:8081
# Purchase notices to Telegram; the bot token (TELEGRAM_BOT_TOKEN) is in .env.secrets.
TELEGRAM_CHAT_ID: ${TELEGRAM_CHAT_ID:-}
# SMTP_URL or the SES credentials come from .env.secrets (docs/levelkuldes.md);
@@ -195,7 +197,15 @@ services:
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
# The links in the forum's e-mails.
PUBLIC_BASE_URL: https://${DOMAIN}
# Uploaded avatars: the same Spaces bucket as the backend's photos
# (S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY in .env.secrets).
S3_ENDPOINT: ${S3_ENDPOINT:-}
S3_BUCKET: ${S3_BUCKET:-}
S3_REGION: ${S3_REGION:-us-east-1}
LOG_DIR: /logs
env_file:
- path: .env.secrets
required: false
depends_on:
postgres:
condition: service_healthy
+8
View File
@@ -49,5 +49,13 @@ services:
mailpit:
condition: service_healthy
forum:
environment:
S3_ENDPOINT: http://rustfs:9000
S3_BUCKET: sorsfonalak-dev
S3_ACCESS_KEY_ID: rustfs-dev
S3_SECRET_ACCESS_KEY: rustfs-dev-secret
volumes:
rustfs:
+10
View File
@@ -96,6 +96,8 @@ services:
SMTP_URL: ${SMTP_URL:-}
MAIL_FROM: ${MAIL_FROM:-Sorsfonalak <noreply@sorsfonalak.local>}
PUBLIC_BASE_URL: ${PUBLIC_BASE_URL:-http://localhost:3001}
# The sky of the forum's daily thread.
BACKEND_URL: http://backend:8081
# Purchase notices to Telegram (TELEGRAM_BOT_TOKEN in .env.secrets).
TELEGRAM_CHAT_ID: ${TELEGRAM_CHAT_ID:-}
# OPENROUTER_API_KEY (not in git); without it analyses stay pending.
@@ -120,6 +122,14 @@ services:
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD:-sorsfonalak-dev}@postgres:5432/sorsfonalak
# The links in the forum's e-mails.
PUBLIC_BASE_URL: ${PUBLIC_BASE_URL:-http://localhost:3001}
# Uploaded avatars, in the same object storage as the backend's photos
# (the override file points it at RustFS in development).
S3_ENDPOINT: ${S3_ENDPOINT:-}
S3_BUCKET: ${S3_BUCKET:-}
S3_REGION: ${S3_REGION:-us-east-1}
env_file:
- path: .env.secrets
required: false
depends_on:
postgres:
condition: service_healthy
+1
View File
@@ -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
+2 -275
View File
@@ -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::*;
+3
View File
@@ -8,6 +8,9 @@ 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"] }
+18 -2
View File
@@ -38,10 +38,16 @@ pub struct Member {
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";
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 {
@@ -58,6 +64,8 @@ impl Member {
pub struct Viewer {
pub user: Option<User>,
pub member: Option<Member>,
/// The restricted topics the member was approved into.
pub topics: Vec<i16>,
}
impl Viewer {
@@ -129,7 +137,15 @@ impl FromRequestParts<Arc<AppState>> for Viewer {
.execute(&state.db)
.await?;
}
Ok(Viewer { user: Some(user), member })
let topics = if member.is_some() {
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?
} else {
Vec::new()
};
Ok(Viewer { user: Some(user), member, topics })
}
}
+45
View File
@@ -217,3 +217,48 @@ pub async fn notify_reporters(state: &AppState, reporters: &[Option<Uuid>], outc
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 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)
.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");
}
}
+18 -4
View File
@@ -6,7 +6,8 @@
//! or `Authorization: Bearer`) is valid here too.
//!
//! Configuration: `DATABASE_URL`, `PUBLIC_BASE_URL` (the site, for e-mail
//! links; default `http://localhost:3001`); `BIND_ADDR` (default `0.0.0.0:8083`),
//! 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).
@@ -37,11 +38,19 @@ pub struct AppState {
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>,
}
impl AppState {
pub fn new(db: PgPool, base_url: String) -> Self {
Self { db, flood_secs: 5, base_url: base_url.trim_end_matches('/').to_string(), hub: live::Hub::default() }
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,
}
}
}
@@ -56,7 +65,12 @@ async fn main() -> anyhow::Result<()> {
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 state = Arc::new(AppState::new(pool, base_url));
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}"))?;
+204
View File
@@ -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"));
}
}
+67 -4
View File
@@ -58,15 +58,34 @@ async fn topic_list(state: &St, viewer: &Viewer) -> ApiResult<Vec<Value>> {
.bind(since)
.fetch_all(&state.db)
.await?;
let readable: Vec<bool> = rows.iter().map(|r| may_read(viewer, &r.visibility)).collect();
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.is_moderator())
.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,
@@ -75,6 +94,7 @@ async fn topic_list(state: &St, viewer: &Viewer) -> ApiResult<Vec<Value>> {
"visibility": r.visibility,
"listening": r.listening,
"readable": readable,
"membership": membership,
});
if readable {
topic["thread_count"] = json!(r.thread_count);
@@ -143,9 +163,21 @@ pub async fn home(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
.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_map(|id| people.get(id).cloned()).collect();
Ok(Json(json!({
"viewer": viewer_json(&viewer),
"followed": followed,
"online": online,
"topics": topics,
"unanswered": cards_json(&state.db, unanswered).await?,
"hot": cards_json(&state.db, hot).await?,
@@ -170,18 +202,49 @@ async fn followed_counts(state: &St, viewer: &Viewer) -> ApiResult<Option<Value>
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)";
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() { Some(super::reports::open_count(&state.db).await?) } else { 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
};
// 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,
};
Ok(Json(json!({
"viewer": viewer_json(&viewer),
"followed": followed_counts(&state, &viewer).await?,
"messages": messages,
"reports": reports,
"waiting": waiting,
})))
}
@@ -208,7 +271,7 @@ pub async fn topic(
.fetch_optional(&state.db)
.await?;
let (id, name, description, visibility, listening) = topic.ok_or(ApiError::NotFound("topic"))?;
if !may_read(&viewer, &visibility) {
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") });
}
+56 -4
View File
@@ -52,12 +52,21 @@ pub async fn me(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
"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 })))
Ok(Json(json!({ "viewer": viewer_json(&viewer), "member": member, "chart": chart, "can_supporter": buyer })))
}
#[derive(Deserialize)]
@@ -74,6 +83,12 @@ pub struct SaveMe {
/// 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)]
@@ -84,6 +99,12 @@ pub struct EmailSettings {
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>> {
@@ -120,7 +141,13 @@ pub async fn save_me(
let user = viewer.require_user()?;
let nickname = text::nickname(&req.nickname)?;
let key = text::nickname_key(&nickname);
let avatar = req.avatar.as_deref().map(text::avatar).transpose()?;
// 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,
@@ -131,6 +158,18 @@ pub async fn save_me(
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("Meghallgatónak 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());
}
@@ -207,16 +246,28 @@ pub async fn save_me(
}
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_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
}
@@ -255,7 +306,8 @@ pub async fn unsubscribe(
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' \
"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())
+179
View File
@@ -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");
}
}
+41 -12
View File
@@ -5,13 +5,16 @@
//! role. A thread in a topic the viewer may not read answers 404, so its
//! existence is not revealed.
mod avatars;
mod home;
mod members;
mod mentions;
mod messages;
mod moderation;
mod posts;
mod reports;
mod threads;
mod topics;
use std::collections::HashMap;
use std::sync::Arc;
@@ -40,8 +43,10 @@ pub fn router(state: Arc<AppState>) -> Router {
.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))
.route("/v1/forum/topics/{slug}", get(home::topic))
.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/threads", post(threads::create))
.route("/v1/forum/threads/{id}", get(threads::show).patch(threads::update).delete(threads::remove))
@@ -63,10 +68,17 @@ pub fn router(state: Arc<AppState>) -> Router {
.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}/ban", post(moderation::ban).delete(moderation::unban))
.route("/v1/forum/mod/log", get(moderation::log))
@@ -83,23 +95,30 @@ async fn health(State(state): St) -> Result<Json<Value>, ApiError> {
}
/// The topics the viewer may read, as an SQL condition on `tp` (forum.topics).
/// Built from the viewer's flags only, never from input.
pub fn visible_topics(viewer: &Viewer) -> &'static str {
/// 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"
"TRUE".into()
} else if viewer.logged_in() {
"tp.visibility IN ('public', 'members')"
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'"
"tp.visibility = 'public'".into()
}
}
/// Whether the viewer may read a topic of this visibility.
pub fn may_read(viewer: &Viewer, visibility: &str) -> bool {
/// 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.is_moderator() || viewer.topics.contains(&topic),
}
}
@@ -120,6 +139,8 @@ pub struct CardRow {
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
@@ -136,7 +157,8 @@ pub fn card_sql(viewer: &Viewer) -> String {
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 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 \
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 ({})",
visible_topics(viewer)
@@ -170,6 +192,7 @@ pub async fn cards_json(db: &PgPool, rows: Vec<CardRow>) -> Result<Vec<Value>, s
"pinned": r.pinned,
"locked": r.locked,
"unread": r.unread,
"system": r.system,
})
})
.collect())
@@ -186,6 +209,8 @@ struct AuthorRow {
last_seen_at: Option<OffsetDateTime>,
chart_share: String,
roles: Vec<String>,
listener: bool,
supporter: bool,
}
/// How members appear next to what they wrote: nickname, avatar, rank,
@@ -199,7 +224,9 @@ pub async fn authors(db: &PgPool, ids: impl IntoIterator<Item = Uuid>) -> Result
}
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.chart_share, u.roles, m.listener, \
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)
@@ -222,6 +249,8 @@ pub async fn authors(db: &PgPool, ids: impl IntoIterator<Item = Uuid>) -> Result
"moderator": moderator,
"online": online(r.invisible, r.last_seen_at, now),
"signs": shown,
"listener": r.listener,
"supporter": r.supporter,
});
(r.user_id, value)
})
+10
View File
@@ -29,6 +29,11 @@ pub enum Action {
Unpin,
ResolveReport,
DismissReport,
ApproveMember,
RejectMember,
RemoveMember,
ResetAvatar,
Topic,
}
impl Action {
@@ -46,6 +51,11 @@ impl Action {
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",
}
}
}
+1
View File
@@ -61,6 +61,7 @@ pub async fn edit(
.fetch_one(&state.db)
.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)))
}
+22 -5
View File
@@ -28,6 +28,7 @@ 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,
@@ -40,11 +41,12 @@ pub struct ThreadRow {
pub pinned: bool,
pub deleted_at: Option<OffsetDateTime>,
pub delete_reason: Option<String>,
pub system: bool,
}
const THREAD_SELECT: &str = "SELECT th.id, tp.slug AS topic_slug, tp.name AS topic_name, tp.visibility, \
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.delete_reason, th.system \
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
@@ -55,7 +57,7 @@ pub async fn readable_thread(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult
.fetch_optional(db)
.await?
.ok_or(ApiError::NotFound("thread"))?;
if !may_read(viewer, &thread.visibility) {
if !may_read(viewer, &thread.visibility, thread.topic_id) {
return Err(if thread.visibility == "members" { ApiError::Unauthorized } else { ApiError::NotFound("thread") });
}
Ok(thread)
@@ -88,10 +90,12 @@ pub struct PostRow {
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,
}
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";
delete_reason, system";
/// Posts as the thread page shows them: authors, reactions, the viewer's own
/// reaction. A removed post keeps its place with the reason; only
@@ -120,10 +124,18 @@ pub async fn posts_json(db: &PgPool, viewer: &Viewer, posts: &[PostRow]) -> ApiR
}
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?;
let moderator = viewer.is_moderator();
Ok(posts
.iter()
.map(|p| {
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);
@@ -150,6 +162,8 @@ pub async fn posts_json(db: &PgPool, viewer: &Viewer, posts: &[PostRow]) -> ApiR
"score": score,
"collapsed": score <= COLLAPSE_SCORE,
"mine": mine.get(&p.id),
"mentions": mentions,
"system": p.system,
});
if moderator {
post["down"] = json!(down);
@@ -225,6 +239,7 @@ fn thread_json(thread: &ThreadRow, author: Option<Value>) -> Value {
"locked": thread.locked,
"pinned": thread.pinned,
"deleted": thread.deleted_at.map(|_| json!({ "reason": thread.delete_reason })),
"system": thread.system,
})
}
@@ -292,7 +307,7 @@ pub async fn create(
.fetch_optional(&state.db)
.await?;
let (topic_id, visibility, listening) = topic.ok_or_else(|| ApiError::bad("Ismeretlen téma."))?;
if !may_read(&viewer, &visibility) {
if !may_read(&viewer, &visibility, topic_id) {
return Err(ApiError::bad("Ismeretlen téma."));
}
let title = text::title(&req.title)?;
@@ -325,6 +340,7 @@ pub async fn create(
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;
Ok((StatusCode::CREATED, Json(json!({ "id": thread_id, "slug": text::slug(&title) }))))
}
@@ -421,6 +437,7 @@ pub async fn reply(
after_post(&mut tx, member.user_id, id, post.id).await?;
tx.commit().await?;
crate::mail::after_reply(&state, id, post.id, member.user_id, post.parent_id, &body).await;
super::mentions::after_post(&state, id, post.id, member.user_id, &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;
+296
View File
@@ -0,0 +1,296 @@
//! 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>,
}
/// 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) WHERE slug = $1",
)
.bind(&slug)
.bind(&name)
.bind(&description)
.bind(&visibility)
.bind(req.listening)
.bind(req.position)
.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(&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(&note)
.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)
}
+156 -2
View File
@@ -35,6 +35,7 @@ impl TestApp {
flood_secs: 0,
base_url: "https://sorsfonalak.test".into(),
hub: crate::live::Hub::default(),
storage: None,
};
Self { router: routes::router(Arc::new(state)), pool }
}
@@ -744,7 +745,11 @@ async fn instant_mails_and_unsubscribe(pool: PgPool) {
let bea = app.member("bea@example.com", "Holdfény", &["user"]).await;
let cili = app.member("cili@example.com", "Zöldág", &["user"]).await;
let me = app.get("/v1/forum/me", Some(&anna)).await;
assert_eq!(me["member"]["email"], json!({"replies": "daily", "followed": "off", "messages": "instant"}));
assert_eq!(
me["member"]["email"],
json!({"replies": "daily", "followed": "off", "messages": "instant", "mentions": "instant",
"listener": "off", "weekly": false})
);
let (status, _) = app
.call(
"PUT",
@@ -845,7 +850,11 @@ async fn instant_mails_and_unsubscribe(pool: PgPool) {
let (status, _) = app.call("POST", &format!("/v1/forum/unsubscribe?token={token}"), None, Value::Null).await;
assert_eq!(status, StatusCode::OK);
let me = app.get("/v1/forum/me", Some(&anna)).await;
assert_eq!(me["member"]["email"], json!({"replies": "off", "followed": "off", "messages": "off"}));
assert_eq!(
me["member"]["email"],
json!({"replies": "off", "followed": "off", "messages": "off", "mentions": "off",
"listener": "off", "weekly": false})
);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
@@ -857,6 +866,7 @@ async fn live_doorbell_over_websocket(pool: PgPool) {
flood_secs: 0,
base_url: "https://sorsfonalak.test".into(),
hub: crate::live::Hub::default(),
storage: None,
});
tokio::spawn(crate::live::listen(pool.clone(), state.hub.clone()));
let router = routes::router(state.clone());
@@ -924,3 +934,147 @@ async fn futures_next(
}
}
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn restricted_topics_by_approval(pool: PgPool) {
let app = TestApp::new(pool);
let admin = app.member("admin@example.com", "Gondnok", &["admin"]).await;
let moderator = app.member("mod@example.com", "Őrangyal", &["moderator"]).await;
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
let bea = app.member("bea@example.com", "Holdfény", &["user"]).await;
// Only the admin opens topics.
let body =
json!({ "name": "Gyászolók köre", "description": "Akik elveszítettek valakit", "visibility": "restricted" });
assert_eq!(app.call("POST", "/v1/forum/topics", Some(&moderator), body.clone()).await.0, StatusCode::FORBIDDEN);
let (status, created) = app.call("POST", "/v1/forum/topics", Some(&admin), body).await;
assert_eq!(status, StatusCode::CREATED, "{created}");
assert_eq!(created["slug"], "gyaszolok-kore");
// Members see it by name and may ask to join; visitors do not see it.
let home = app.get("/v1/forum/home", Some(&anna)).await;
let topic = home["topics"].as_array().unwrap().iter().find(|t| t["slug"] == "gyaszolok-kore").unwrap().clone();
assert_eq!((topic["readable"].as_bool(), topic["membership"].as_str()), (Some(false), Some("none")));
assert!(
app.get("/v1/forum/home", None).await["topics"]
.as_array()
.unwrap()
.iter()
.all(|t| t["slug"] != "gyaszolok-kore")
);
let (status, _) = app.call("GET", "/v1/forum/topics/gyaszolok-kore", Some(&anna), Value::Null).await;
assert_eq!(status, StatusCode::NOT_FOUND);
let (status, _) = app
.call(
"POST",
"/v1/forum/threads",
Some(&anna),
json!({ "topic": "gyaszolok-kore", "title": "Apukám", "body": "x" }),
)
.await;
assert_eq!(status, StatusCode::BAD_REQUEST);
let (status, _) = app
.call(
"POST",
"/v1/forum/topics/gyaszolok-kore/join",
Some(&anna),
json!({ "note": "Tavaly vesztettem el anyukámat." }),
)
.await;
assert_eq!(status, StatusCode::NO_CONTENT);
assert_eq!(app.get("/v1/forum/nav", Some(&moderator)).await["reports"], 1, "the request shows for moderators");
// A moderator approves: now Anna reads and writes there, Bea still not.
let requests = app.get("/v1/forum/mod/topic-requests", Some(&moderator)).await;
assert_eq!(requests["requests"][0]["member"]["nickname"], "Csendesvíz");
assert_eq!(requests["requests"][0]["note"], "Tavaly vesztettem el anyukámat.");
let (status, _) = app
.call(
"POST",
"/v1/forum/mod/topic-requests",
Some(&moderator),
json!({ "topic": "gyaszolok-kore", "nickname": "Csendesvíz", "action": "approve" }),
)
.await;
assert_eq!(status, StatusCode::NO_CONTENT);
let thread = app.thread(&anna, "gyaszolok-kore", "Apukám emléke").await;
app.get(&format!("/v1/forum/threads/{thread}"), Some(&anna)).await;
let (status, _) = app.call("GET", &format!("/v1/forum/threads/{thread}"), Some(&bea), Value::Null).await;
assert_eq!(status, StatusCode::NOT_FOUND);
app.get(&format!("/v1/forum/threads/{thread}"), Some(&moderator)).await;
assert_eq!(app.get("/v1/forum/mod/log", Some(&moderator)).await["entries"][0]["action"], "approve_member");
// The admin renames it; the address stays.
let (status, _) = app
.call("PATCH", "/v1/forum/topics/gyaszolok-kore", Some(&admin), json!({ "name": "Gyász és emlékezés" }))
.await;
assert_eq!(status, StatusCode::NO_CONTENT);
assert_eq!(app.get("/v1/forum/topics/gyaszolok-kore", Some(&anna)).await["topic"]["name"], "Gyász és emlékezés");
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn mentions_listeners_supporters_and_who_is_here(pool: PgPool) {
let app = TestApp::new(pool);
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
let bea = app.member("bea@example.com", "Hold fény", &["user"]).await;
let cili = app.member("cili@example.com", "Zöldág", &["user"]).await;
// "@Hold fény" (with its space) names Bea: she follows the thread, it is new for her.
let thread = app.thread(&anna, "torzsasztal", "Téli levesek").await;
let post = app.reply(&cili, thread, "Szerinted, @Hold fény, mi a legjobb? És @Senki?", None).await;
assert_eq!(post["mentions"], json!(["Hold fény"]));
let followed = app.get("/v1/forum/followed", Some(&bea)).await;
assert_eq!(followed["threads"][0]["id"], thread);
let found = app.get("/v1/forum/members/search?q=hold", Some(&anna)).await;
assert_eq!(found["members"][0]["nickname"], "Hold fény");
// Listening volunteers: from the Kereső rank; they see what waits for a reply.
let (status, _) =
app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Hold fény", "listener": true })).await;
assert_eq!(status, StatusCode::FORBIDDEN);
app.season(&bea, 5, 10).await;
let (status, _) =
app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Hold fény", "listener": true })).await;
assert_eq!(status, StatusCode::OK);
let waiting = app.thread(&anna, "ami-a-szivemen-van", "Nehéz napok").await;
sqlx::query("UPDATE forum.threads SET created_at = now() - interval '2 hours' WHERE id = $1")
.bind(waiting)
.execute(&app.pool)
.await
.unwrap();
assert_eq!(app.get("/v1/forum/nav", Some(&bea)).await["waiting"], 1);
assert!(app.get("/v1/forum/nav", Some(&cili)).await["waiting"].is_null());
let shown = app.get(&format!("/v1/forum/threads/{thread}"), Some(&anna)).await;
assert!(shown["posts"].as_array().unwrap().iter().all(|p| p["author"]["supporter"] == false));
// The supporter badge: buyers only, and only when they switch it on.
let (status, _) =
app.call("PUT", "/v1/forum/me", Some(&cili), json!({ "nickname": "Zöldág", "supporter_badge": true })).await;
assert_eq!(status, StatusCode::FORBIDDEN);
sqlx::query("INSERT INTO package_orders (id, user_id, package, source, price_huf) VALUES ($1, $2, 'egyeni', 'stripe', 4900)")
.bind(Uuid::now_v7())
.bind(cili.id)
.execute(&app.pool)
.await
.unwrap();
assert_eq!(app.get("/v1/forum/me", Some(&cili)).await["can_supporter"], true);
let (status, _) =
app.call("PUT", "/v1/forum/me", Some(&cili), json!({ "nickname": "Zöldág", "supporter_badge": true })).await;
assert_eq!(status, StatusCode::OK);
let profile = app.get("/v1/forum/members/Zöldág", None).await;
assert_eq!(
(profile["member"]["author"]["supporter"].as_bool(), profile["member"]["author"]["listener"].as_bool()),
(Some(true), Some(false))
);
assert_eq!(app.get("/v1/forum/members/hold%20f%C3%A9ny", None).await["member"]["author"]["listener"], true);
// Who is here: the members seen in the last minutes, not the invisible.
app.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": "Csendesvíz", "invisible": true })).await;
let here: Vec<String> = app.get("/v1/forum/home", None).await["online"]
.as_array()
.unwrap()
.iter()
.map(|m| m["nickname"].as_str().unwrap().to_string())
.collect();
assert!(here.contains(&"Zöldág".to_string()) && !here.contains(&"Csendesvíz".to_string()));
}
+1
View File
@@ -13,6 +13,7 @@ email-templates.workspace = true
gift-card.workspace = true
service-kit.workspace = true
anyhow.workspace = true
deunicode.workspace = true
axum.workspace = true
base64.workspace = true
hmac.workspace = true
+4
View File
@@ -76,6 +76,9 @@ pub struct Config {
pub openrouter_base_url: String,
/// Frontend address, sent to OpenRouter as `HTTP-Referer`.
pub public_base_url: Option<String>,
/// The backend (`BACKEND_URL`, default `http://backend:8081`): the sky of
/// the forum's daily thread.
pub backend_url: String,
/// Detailed analyses and forecasts written at the same time (0: none).
pub analysis_concurrency: usize,
/// Summaries and answers written at the same time (0: none).
@@ -137,6 +140,7 @@ impl Config {
openrouter_base_url: var("OPENROUTER_BASE_URL")
.unwrap_or_else(|| crate::analysis::openrouter::DEFAULT_BASE_URL.into()),
public_base_url: var("PUBLIC_BASE_URL"),
backend_url: var("BACKEND_URL").unwrap_or_else(|| "http://backend:8081".into()),
analysis_concurrency: parsed("ANALYSIS_CONCURRENCY", 4)?,
quick_concurrency: parsed("QUICK_CONCURRENCY", 2)?,
max_analysis_attempts: parsed("MAX_ANALYSIS_ATTEMPTS", 3)?,
+292 -7
View File
@@ -1,9 +1,14 @@
//! The `forum` task: the forum's daily e-mail digest. In the evening
//! (18–22 h, Hungarian time) every member who asked for it gets one e-mail
//! listing the threads with posts they have not read yet: replies to them
//! (`email_replies = 'daily'`) and new posts in followed threads
//! (`email_followed = 'daily'`). Nothing new, no e-mail. The instant e-mails
//! are queued by the forum service itself.
//! The `forum` task: the forum's scheduled work.
//!
//! * The daily e-mail digest: in the evening (18–22 h, Hungarian time) every
//! member who asked for it gets one e-mail listing the threads with posts
//! they have not read yet: replies to them (`email_replies = 'daily'`) and
//! new posts in followed threads (`email_followed = 'daily'`). Nothing new,
//! no e-mail. The instant e-mails are queued by the forum service itself.
//! * The daily "Mai égbolt" thread (`forum_sky`).
//! * Volunteer listeners: a thread asking to be heard that waited two hours
//! without a reply is sent to those who asked for such e-mails.
//! * The weekly summary, on Sunday evening, for those who asked for it.
use std::time::Duration;
@@ -113,11 +118,179 @@ pub async fn run_once(db: &PgPool, base_url: &str, any_time: bool) -> Result<usi
Ok(queued)
}
pub async fn run(db: PgPool, base_url: String, stop: watch::Receiver<bool>) {
/// A waiting thread is sent to the listeners after this long without a reply.
const LISTENER_AFTER: &str = "2 hours";
/// Sends the listeners the threads that wait for a first reply; returns how
/// many e-mails were queued. Each thread once; a listener at most one such
/// e-mail in six hours.
pub async fn listeners_once(db: &PgPool, base_url: &str) -> Result<usize, sqlx::Error> {
let base = base_url.trim_end_matches('/');
let mut tx = db.begin().await?;
let threads: Vec<(i64, String, Option<Uuid>)> = sqlx::query_as(&format!(
"SELECT th.id, th.title, th.author_id FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
WHERE th.reply_count = 0 AND NOT th.locked AND th.deleted_at IS NULL AND NOT th.system \
AND th.listeners_notified_at IS NULL AND tp.visibility <> 'restricted' \
AND (th.intent = 'listen' OR tp.listening) \
AND th.created_at < now() - interval '{LISTENER_AFTER}' AND th.created_at > now() - interval '3 days' \
ORDER BY th.created_at LIMIT 20 FOR UPDATE OF th SKIP LOCKED"
))
.fetch_all(&mut *tx)
.await?;
let mut queued = 0;
for (id, title, author) in threads {
let listeners: Vec<(Uuid, String, String, String, String)> = sqlx::query_as(
"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.listener AND m.email_listener = 'instant' AND m.user_id IS DISTINCT FROM $1 \
AND (m.banned_until IS NULL OR m.banned_until < now()) \
AND (m.last_seen_at IS NULL OR m.last_seen_at < now() - interval '5 minutes') \
AND NOT EXISTS (SELECT 1 FROM email_outbox e WHERE e.user_id = m.user_id \
AND e.template = 'forum_listener' AND e.created_at > now() - interval '6 hours')",
)
.bind(author)
.fetch_all(&mut *tx)
.await?;
let slug = thread_slug(&title);
for (user, email, locale, nickname, token) in listeners {
let payload = json!({
"url": format!("{base}/forum/szal/{id}-{slug}#valasz"),
"nickname": nickname,
"thread_title": title,
"unsubscribe_url": format!("{base}/forum/leiratkozas?token={token}"),
"unsubscribe_post_url": format!("{base}/api/v1/forum/unsubscribe?token={token}"),
});
queue(&mut tx, user, &email, &locale, "forum_listener", payload).await?;
queued += 1;
}
sqlx::query("UPDATE forum.threads SET listeners_notified_at = now() WHERE id = $1")
.bind(id)
.execute(&mut *tx)
.await?;
}
tx.commit().await?;
Ok(queued)
}
/// Sunday evening: the week's busiest threads and those still waiting, to the
/// members who asked for it; returns how many e-mails were queued.
pub async fn weekly_once(db: &PgPool, base_url: &str, any_time: bool) -> Result<usize, sqlx::Error> {
if !any_time {
let (dow, hour): (i32, i32) = sqlx::query_as(
"SELECT extract(dow FROM now() AT TIME ZONE 'Europe/Budapest')::int, \
extract(hour FROM now() AT TIME ZONE 'Europe/Budapest')::int",
)
.fetch_one(db)
.await?;
if dow != 0 || !(18..22).contains(&hour) {
return Ok(0);
}
}
let base = base_url.trim_end_matches('/');
let busy: Vec<(i64, String, i64)> = sqlx::query_as(
"SELECT th.id, th.title, count(p.id) FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
JOIN forum.posts p ON p.thread_id = th.id AND p.deleted_at IS NULL AND p.created_at > now() - interval '7 days' \
WHERE th.deleted_at IS NULL AND tp.visibility <> 'restricted' \
GROUP BY th.id, th.title ORDER BY count(p.id) DESC, max(p.id) DESC LIMIT 5",
)
.fetch_all(db)
.await?;
let waiting: Vec<String> = sqlx::query_scalar(
"SELECT th.title FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
WHERE th.reply_count = 0 AND th.deleted_at IS NULL AND NOT th.locked AND NOT th.system \
AND tp.visibility <> 'restricted' AND th.created_at > now() - interval '7 days' \
ORDER BY th.created_at LIMIT 3",
)
.fetch_all(db)
.await?;
let busy: Vec<String> = busy.iter().map(|(_, title, n)| format!("„{title}” – {n} hozzászólás")).collect();
let waiting: Vec<String> = waiting.iter().map(|t| format!("„{t}”")).collect();
let mut tx = db.begin().await?;
let due: Vec<(Uuid, String, String, String, String)> = sqlx::query_as(
"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_weekly AND (m.weekly_sent_at IS NULL OR m.weekly_sent_at < now() - interval '6 days') \
ORDER BY m.user_id LIMIT $1 FOR UPDATE OF m SKIP LOCKED",
)
.bind(BATCH)
.fetch_all(&mut *tx)
.await?;
let mut queued = 0;
for (user, email, locale, nickname, token) in due {
if !busy.is_empty() || !waiting.is_empty() {
let payload = json!({
"url": format!("{base}/forum"),
"nickname": nickname,
"busy": busy,
"waiting": waiting,
"unsubscribe_url": format!("{base}/forum/leiratkozas?token={token}"),
"unsubscribe_post_url": format!("{base}/api/v1/forum/unsubscribe?token={token}"),
});
queue(&mut tx, user, &email, &locale, "forum_weekly", payload).await?;
queued += 1;
}
sqlx::query("UPDATE forum.members SET weekly_sent_at = now() WHERE user_id = $1")
.bind(user)
.execute(&mut *tx)
.await?;
}
tx.commit().await?;
Ok(queued)
}
async fn queue(
tx: &mut sqlx::PgConnection,
user: Uuid,
email: &str,
locale: &str,
template: &str,
payload: serde_json::Value,
) -> Result<(), sqlx::Error> {
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(email)
.bind(template)
.bind(locale)
.bind(payload)
.execute(&mut *tx)
.await?;
Ok(())
}
/// The readable part of a thread's address (the forum service's `text::slug`).
fn thread_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
}
pub async fn run(db: PgPool, base_url: String, backend_url: String, stop: watch::Receiver<bool>) {
let http = reqwest::Client::builder().timeout(Duration::from_secs(20)).build().expect("static configuration");
loop {
if let Err(e) = run_once(&db, &base_url, false).await {
tracing::error!(error = %e, "forum digests");
}
if let Err(e) = crate::forum_sky::run_once(&db, &http, &backend_url, false).await {
tracing::error!(error = %e, "daily sky thread");
}
if let Err(e) = listeners_once(&db, &base_url).await {
tracing::error!(error = %e, "forum listener e-mails");
}
if let Err(e) = weekly_once(&db, &base_url, false).await {
tracing::error!(error = %e, "forum weekly summary");
}
tokio::select! {
() = tokio::time::sleep(Duration::from_secs(10 * 60)) => {}
() = crate::stopped(stop.clone()) => break,
@@ -210,3 +383,115 @@ mod tests {
assert_eq!(run_once(&pool, "https://sorsfonalak.hu", true).await.unwrap(), 0);
}
}
#[cfg(test)]
mod more_tests {
use axum::Json;
use axum::routing::get;
use super::*;
async fn user(db: &PgPool, email: &str, nickname: &str) -> Uuid {
let id = Uuid::now_v7();
sqlx::query("INSERT INTO users (id, email) VALUES ($1, $2)").bind(id).bind(email).execute(db).await.unwrap();
sqlx::query("INSERT INTO forum.members (user_id, nickname, nickname_key, avatar) VALUES ($1, $2, lower($2), 'hold-ejkek')")
.bind(id)
.bind(nickname)
.execute(db)
.await
.unwrap();
id
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn listeners_hear_of_a_waiting_thread_once(pool: PgPool) {
let anna = user(&pool, "anna@example.com", "Anna").await;
let bea = user(&pool, "bea@example.com", "Bea").await;
let cili = user(&pool, "cili@example.com", "Cili").await;
sqlx::query("UPDATE forum.members SET listener = true, email_listener = 'instant' WHERE user_id IN ($1, $2)")
.bind(bea)
.bind(cili)
.execute(&pool)
.await
.unwrap();
// Anna asks to be heard; three hours, no reply. Another thread is fresh.
sqlx::query(
"INSERT INTO forum.threads (topic_id, author_id, title, intent, created_at) VALUES \
(2, $1, 'Nehéz napok', 'listen', now() - interval '3 hours'), (2, $1, 'Friss', 'listen', now())",
)
.bind(anna)
.execute(&pool)
.await
.unwrap();
assert_eq!(listeners_once(&pool, "https://sorsfonalak.hu").await.unwrap(), 2);
assert_eq!(listeners_once(&pool, "https://sorsfonalak.hu").await.unwrap(), 0, "once per thread");
let to: Vec<String> =
sqlx::query_scalar("SELECT to_email FROM email_outbox WHERE template = 'forum_listener' ORDER BY to_email")
.fetch_all(&pool)
.await
.unwrap();
assert_eq!(to, vec!["bea@example.com", "cili@example.com"]);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn the_weekly_summary_only_for_those_who_asked(pool: PgPool) {
let anna = user(&pool, "anna@example.com", "Anna").await;
user(&pool, "bea@example.com", "Bea").await;
sqlx::query("UPDATE forum.members SET email_weekly = true WHERE user_id = $1")
.bind(anna)
.execute(&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)
.fetch_one(&pool)
.await
.unwrap();
sqlx::query("INSERT INTO forum.posts (thread_id, author_id, is_opening, body) VALUES ($1, $2, true, 'x')")
.bind(thread)
.bind(anna)
.execute(&pool)
.await
.unwrap();
assert_eq!(weekly_once(&pool, "https://sorsfonalak.hu", true).await.unwrap(), 1);
assert_eq!(weekly_once(&pool, "https://sorsfonalak.hu", true).await.unwrap(), 0, "once a week");
let payload: serde_json::Value =
sqlx::query_scalar("SELECT payload FROM email_outbox WHERE template = 'forum_weekly'")
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(payload["busy"][0], "„Téli levesek” – 1 hozzászólás");
assert!(email_templates::render("forum_weekly", "hu", &payload).is_ok());
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn the_daily_sky_thread_is_opened_once(pool: PgPool) {
async fn sky() -> Json<serde_json::Value> {
Json(serde_json::json!({
"local_time": "2026-11-27T06:10",
"moon": {"position": {"sign": "cancer"}, "phase": "waning_gibbous", "illumination": 0.9,
"sign_change": null, "next_phases": []},
"planets": []
}))
}
let app = axum::Router::new().route("/v1/public/sky", get(sky));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let http = reqwest::Client::new();
let url = format!("http://{addr}");
assert!(crate::forum_sky::run_once(&pool, &http, &url, true).await.unwrap());
assert!(!crate::forum_sky::run_once(&pool, &http, &url, true).await.unwrap(), "one a day");
let (title, system, pinned, body): (String, bool, bool, String) = sqlx::query_as(
"SELECT th.title, th.system, th.pinned, p.body FROM forum.threads th \
JOIN forum.posts p ON p.thread_id = th.id AND p.is_opening",
)
.fetch_one(&pool)
.await
.unwrap();
assert!(title.starts_with("Mai égbolt · ") && system && pinned);
assert!(body.starts_with("A Hold ma a Rákban jár."));
}
}
+287
View File
@@ -0,0 +1,287 @@
//! The forum's daily "Mai égbolt" thread: every morning the worker opens it
//! in the "Égbolt és képletek" topic from the sky of the day (the backend's
//! public sky: the Moon's sign and phase, a sign change, the retrograde
//! planets, the next lunation). No AI: fixed Hungarian sentences. The new
//! thread is pinned for the day; yesterday's is unpinned.
use serde_json::Value;
use sqlx::PgPool;
/// The topic it goes to.
const TOPIC: &str = "egbolt-es-kepletek";
/// From this hour (Hungarian time) it is made, once a day.
const FROM_HOUR: i32 = 5;
/// "a Rákban": the sign with the inessive ending.
fn sign_in(sign: &str) -> &'static str {
match sign {
"aries" => "Kosban",
"taurus" => "Bikában",
"gemini" => "Ikrekben",
"cancer" => "Rákban",
"leo" => "Oroszlánban",
"virgo" => "Szűzben",
"libra" => "Mérlegben",
"scorpio" => "Skorpióban",
"sagittarius" => "Nyilasban",
"capricorn" => "Bakban",
"aquarius" => "Vízöntőben",
_ => "Halakban",
}
}
/// "a Rákba": the sign with the illative ending.
fn sign_into(sign: &str) -> &'static str {
match sign {
"aries" => "Kosba",
"taurus" => "Bikába",
"gemini" => "Ikrekbe",
"cancer" => "Rákba",
"leo" => "Oroszlánba",
"virgo" => "Szűzbe",
"libra" => "Mérlegbe",
"scorpio" => "Skorpióba",
"sagittarius" => "Nyilasba",
"capricorn" => "Bakba",
"aquarius" => "Vízöntőbe",
_ => "Halakba",
}
}
/// The Moon in a sign, as the frontend's sky card says it.
fn moon_mood(sign: &str) -> &'static str {
match sign {
"aries" => "Lendület és türelmetlenség. Jó nap elkezdeni valamit.",
"taurus" => "Nyugalom, kényelem, érzéki örömök. Ráérősebb tempó.",
"gemini" => "Kíváncsiság, beszélgetések, sok apró ügy egyszerre.",
"cancer" => "Otthon, család, érzékenység. Jólesik a biztonság.",
"leo" => "Önkifejezés, játékosság, a figyelem öröme.",
"virgo" => "Rendrakás, részletek, a test és a napi rutin.",
"libra" => "Kapcsolatok, harmónia, kompromisszumok.",
"scorpio" => "Mélység és intenzitás: erősebb érzések, kevesebb felszínesség.",
"sagittarius" => "Derűlátás, tanulás, kalandvágy.",
"capricorn" => "Kötelességek, tervezés, kitartó munka.",
"aquarius" => "Szabadság, barátok, szokatlan ötletek.",
_ => "Álmodozás, együttérzés, megérzések.",
}
}
fn phase_name(phase: &str) -> &'static str {
match phase {
"new_moon" => "Újhold",
"waxing_crescent" => "Növő holdsarló",
"first_quarter" => "Első negyed",
"waxing_gibbous" => "Növő hold",
"full_moon" => "Telihold",
"waning_gibbous" => "Fogyó hold",
"last_quarter" => "Utolsó negyed",
_ => "Fogyó holdsarló",
}
}
fn lunation_name(kind: &str) -> &'static str {
match kind {
"new_moon" => "újhold",
"first_quarter" => "első negyed",
"full_moon" => "telihold",
_ => "utolsó negyed",
}
}
fn planet_name(id: &str) -> Option<&'static str> {
Some(match id {
"mercury" => "Merkúr",
"venus" => "Vénusz",
"mars" => "Mars",
"jupiter" => "Jupiter",
"saturn" => "Szaturnusz",
"uranus" => "Uránusz",
"neptune" => "Neptunusz",
"pluto" => "Plútó",
_ => return None,
})
}
/// "a" or "az" before a word.
fn article(word: &str) -> &'static str {
if word.starts_with(['A', 'Á', 'E', 'É', 'I', 'Í', 'O', 'Ó', 'Ö', 'Ő', 'U', 'Ú', 'Ü', 'Ű']) {
"az"
} else {
"a"
}
}
const MONTHS: [&str; 12] = [
"január",
"február",
"március",
"április",
"május",
"június",
"július",
"augusztus",
"szeptember",
"október",
"november",
"december",
];
const WEEKDAYS: [&str; 7] = ["hétfő", "kedd", "szerda", "csütörtök", "péntek", "szombat", "vasárnap"];
/// "november 27., csütörtök" from "2026-11-27".
fn day_title(date: &str) -> Option<String> {
let mut parts = date.split('-').map(|p| p.parse::<i32>().ok());
let (year, month, day) = (parts.next()??, parts.next()??, parts.next()??);
let month_enum = time::Month::try_from(u8::try_from(month).ok()?).ok()?;
let d = time::Date::from_calendar_date(year, month_enum, u8::try_from(day).ok()?).ok()?;
let weekday = WEEKDAYS[d.weekday().number_days_from_monday() as usize];
Some(format!("{} {day}., {weekday}", MONTHS[(month - 1) as usize]))
}
/// "december 1." from "2026-12-01T07:09".
fn short_date(local: &str) -> Option<String> {
let month: usize = local.get(5..7)?.parse().ok()?;
let day: u32 = local.get(8..10)?.parse().ok()?;
Some(format!("{} {day}.", MONTHS.get(month.checked_sub(1)?)?))
}
/// The title and the opening post of the day's thread, from the sky now.
pub fn compose(sky: &Value) -> Option<(String, String)> {
let local = sky["local_time"].as_str()?;
let today = local.get(..10)?;
let moon = &sky["moon"];
let sign = moon["position"]["sign"].as_str()?;
let phase = moon["phase"].as_str().unwrap_or("");
let lit = (moon["illumination"].as_f64().unwrap_or(0.0) * 100.0).round() as i64;
let title = format!("Mai égbolt · {}", day_title(today)?);
let place = sign_in(sign);
let mut first = format!(
"A Hold ma {} {place} jár. {}, {lit}%-os megvilágítással. {}",
article(place),
phase_name(phase),
moon_mood(sign)
);
if let (Some(at), Some(next)) = (moon["sign_change"]["local_time"].as_str(), moon["sign_change"]["sign"].as_str())
&& at.starts_with(today)
&& let Some(time) = at.get(11..16)
{
let into = sign_into(next);
first.push_str(&format!(" {time}-kor átlép {} {into}.", article(into)));
}
let mut lines = vec![first];
let retro: Vec<&str> = sky["planets"]
.as_array()
.into_iter()
.flatten()
.filter(|p| p["retrograde"].as_bool() == Some(true))
.filter_map(|p| planet_name(p["id"].as_str()?))
.collect();
if !retro.is_empty() {
lines.push(format!("Retrográd most: {}.", retro.join(", ")));
}
if let Some(next) = moon["next_phases"].as_array().and_then(|p| p.first()) {
let kind = next["kind"].as_str().unwrap_or("");
let at = next["local_time"].as_str().and_then(short_date);
let place = next["position"]["sign"].as_str().map(sign_in);
if let (Some(at), Some(place)) = (at, place) {
let name = lunation_name(kind);
lines.push(format!(
"{}{}: {at}, {} {place}.",
name.chars().next().map(|c| c.to_uppercase().to_string()).unwrap_or_default(),
&name[name.chars().next().map(char::len_utf8).unwrap_or(0)..],
article(place)
));
}
}
lines.push(
"Hogy telik a napotok? Írjátok meg, mit hozott a mai égbolt, vagy egyszerűen csak azt, hogy vagytok.".into(),
);
Some((title, lines.join("\n\n")))
}
/// Opens today's thread if it is morning and there is none yet; true when made.
pub async fn run_once(db: &PgPool, http: &reqwest::Client, backend_url: &str, any_time: bool) -> anyhow::Result<bool> {
let (hour, exists): (i32, bool) = sqlx::query_as(
"SELECT extract(hour FROM now() AT TIME ZONE 'Europe/Budapest')::int, \
EXISTS (SELECT 1 FROM forum.threads WHERE daily_date = (now() AT TIME ZONE 'Europe/Budapest')::date)",
)
.fetch_one(db)
.await?;
if exists || (!any_time && hour < FROM_HOUR) {
return Ok(false);
}
let sky: Value = http
.get(format!("{}/v1/public/sky", backend_url.trim_end_matches('/')))
.send()
.await?
.error_for_status()?
.json()
.await?;
let Some((title, body)) = compose(&sky) else {
anyhow::bail!("the sky answer has no Moon");
};
let mut tx = db.begin().await?;
let thread: Option<i64> = sqlx::query_scalar(
"INSERT INTO forum.threads (topic_id, author_id, title, system, pinned, daily_date) \
SELECT id, NULL, $2, true, true, (now() AT TIME ZONE 'Europe/Budapest')::date FROM forum.topics WHERE slug = $1 \
ON CONFLICT (daily_date) DO NOTHING RETURNING id",
)
.bind(TOPIC)
.bind(&title)
.fetch_optional(&mut *tx)
.await?;
let Some(thread) = thread else { return Ok(false) };
sqlx::query(
"INSERT INTO forum.posts (thread_id, author_id, is_opening, body, system) VALUES ($1, NULL, true, $2, true)",
)
.bind(thread)
.bind(&body)
.execute(&mut *tx)
.await?;
sqlx::query("UPDATE forum.threads SET pinned = false WHERE daily_date IS NOT NULL AND id <> $1 AND pinned")
.bind(thread)
.execute(&mut *tx)
.await?;
tx.commit().await?;
tracing::info!(thread, "daily sky thread opened");
Ok(true)
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
fn sky() -> Value {
json!({
"local_time": "2026-11-27T06:10",
"moon": {
"position": {"sign": "cancer"}, "phase": "waning_gibbous", "illumination": 0.887,
"sign_change": {"local_time": "2026-11-27T12:21", "sign": "leo"},
"next_phases": [{"kind": "last_quarter", "local_time": "2026-12-01T07:09", "position": {"sign": "virgo"}}]
},
"planets": [
{"id": "sun", "retrograde": false},
{"id": "saturn", "retrograde": true},
{"id": "neptune", "retrograde": true}
]
})
}
#[test]
fn writes_the_day_in_hungarian() {
let (title, body) = compose(&sky()).unwrap();
assert_eq!(title, "Mai égbolt · november 27., péntek");
assert!(body.starts_with("A Hold ma a Rákban jár. Fogyó hold, 89%-os megvilágítással. Otthon, család"));
assert!(body.contains("12:21-kor átlép az Oroszlánba."), "{body}");
assert!(body.contains("Retrográd most: Szaturnusz, Neptunusz."));
assert!(body.contains("Utolsó negyed: december 1., a Szűzben."), "{body}");
assert!(body.ends_with("hogy vagytok."));
// A sign change on another day is left out.
let mut other = sky();
other["moon"]["sign_change"]["local_time"] = json!("2026-11-28T09:00");
assert!(!compose(&other).unwrap().1.contains("átlép"));
}
}
+4 -3
View File
@@ -20,6 +20,7 @@ mod compare;
mod config;
mod email;
mod forum_digest;
mod forum_sky;
mod invoices;
mod notify;
mod ses;
@@ -172,10 +173,10 @@ async fn main() -> anyhow::Result<()> {
match &config.public_base_url {
_ if !tasks.forum => {}
Some(base) => {
tracing::info!("forum digests enabled");
jobs.spawn(forum_digest::run(pool.clone(), base.clone(), stop.clone()));
tracing::info!("forum task enabled (digests, daily sky thread, listeners, weekly summary)");
jobs.spawn(forum_digest::run(pool.clone(), base.clone(), config.backend_url.clone(), stop.clone()));
}
None => tracing::warn!("PUBLIC_BASE_URL is not set: no forum digests (their links need it)"),
None => tracing::warn!("PUBLIC_BASE_URL is not set: no forum task (its e-mail links need it)"),
}
let app = Router::new().route("/healthz", get(healthz)).with_state(pool);