"Holdfény gépel…" shows in threads and private conversations: the page says over the live connection (every few seconds while typing) that its member types, and the forum service passes it to those who may see that place, never back to the typer. The emoji tray is gone (phones have their emoji keyboard); character smileys turn into emoji as they are typed, from a longer list shared with the server (which also converts titles now; <3 is a red heart). Emoji show in colour: the forum's font stack names the systems' colour emoji fonts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
927 lines
45 KiB
Rust
927 lines
45 KiB
Rust
//! End-to-end tests against a real PostgreSQL database.
|
|
//!
|
|
//! `DATABASE_URL` must point to a server where the user may create databases
|
|
//! (e.g. the `postgres` service of docker-compose); every test gets a fresh,
|
|
//! migrated database. Users and sessions are made directly in the database,
|
|
//! as the backend would.
|
|
|
|
use std::sync::Arc;
|
|
|
|
use axum::Router;
|
|
use axum::body::Body;
|
|
use axum::http::{Request, StatusCode};
|
|
use http_body_util::BodyExt;
|
|
use serde_json::{Value, json};
|
|
use sqlx::PgPool;
|
|
use tower::ServiceExt;
|
|
use uuid::Uuid;
|
|
|
|
use crate::{AppState, routes};
|
|
|
|
struct TestApp {
|
|
router: Router,
|
|
pool: PgPool,
|
|
}
|
|
|
|
struct User {
|
|
id: Uuid,
|
|
token: String,
|
|
}
|
|
|
|
impl TestApp {
|
|
fn new(pool: PgPool) -> Self {
|
|
let state = AppState {
|
|
db: pool.clone(),
|
|
flood_secs: 0,
|
|
base_url: "https://sorsfonalak.test".into(),
|
|
hub: crate::live::Hub::default(),
|
|
};
|
|
Self { router: routes::router(Arc::new(state)), pool }
|
|
}
|
|
|
|
/// A user with a session, as after a login in the backend.
|
|
async fn user(&self, email: &str, roles: &[&str]) -> User {
|
|
let id = Uuid::now_v7();
|
|
sqlx::query("INSERT INTO users (id, email, display_name, roles) VALUES ($1, $2, 'Valódi Név', $3)")
|
|
.bind(id)
|
|
.bind(email)
|
|
.bind(roles.iter().map(|r| r.to_string()).collect::<Vec<_>>())
|
|
.execute(&self.pool)
|
|
.await
|
|
.unwrap();
|
|
let token = db::new_token();
|
|
sqlx::query(
|
|
"INSERT INTO sessions (id, user_id, token_hash, expires_at) VALUES ($1, $2, $3, now() + interval '1 day')",
|
|
)
|
|
.bind(Uuid::now_v7())
|
|
.bind(id)
|
|
.bind(db::token_hash(&token))
|
|
.execute(&self.pool)
|
|
.await
|
|
.unwrap();
|
|
User { id, token }
|
|
}
|
|
|
|
/// A user who already chose a nickname.
|
|
async fn member(&self, email: &str, nickname: &str, roles: &[&str]) -> User {
|
|
let user = self.user(email, roles).await;
|
|
let (status, body) = self.call("PUT", "/v1/forum/me", Some(&user), json!({ "nickname": nickname })).await;
|
|
assert_eq!(status, StatusCode::OK, "{body}");
|
|
user
|
|
}
|
|
|
|
/// Makes a member older and gives them points (rank Kereső and up).
|
|
async fn season(&self, user: &User, days: i32, points: i32) {
|
|
sqlx::query(
|
|
"UPDATE forum.members SET created_at = now() - make_interval(days => $2), points = $3, \
|
|
nickname_changed_at = now() - make_interval(days => $2) WHERE user_id = $1",
|
|
)
|
|
.bind(user.id)
|
|
.bind(days)
|
|
.bind(points)
|
|
.execute(&self.pool)
|
|
.await
|
|
.unwrap();
|
|
}
|
|
|
|
async fn points(&self, user: &User) -> i32 {
|
|
sqlx::query_scalar("SELECT points FROM forum.members WHERE user_id = $1")
|
|
.bind(user.id)
|
|
.fetch_one(&self.pool)
|
|
.await
|
|
.unwrap()
|
|
}
|
|
|
|
async fn call(&self, method: &str, uri: &str, user: Option<&User>, body: Value) -> (StatusCode, Value) {
|
|
let mut req = Request::builder().method(method).uri(uri);
|
|
if let Some(u) = user {
|
|
req = req.header("authorization", format!("Bearer {}", u.token));
|
|
}
|
|
let req = if body.is_null() {
|
|
req.body(Body::empty()).unwrap()
|
|
} else {
|
|
req.header("content-type", "application/json").body(Body::from(body.to_string())).unwrap()
|
|
};
|
|
let resp = self.router.clone().oneshot(req).await.unwrap();
|
|
let status = resp.status();
|
|
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
|
|
let value = if bytes.is_empty() { Value::Null } else { serde_json::from_slice(&bytes).unwrap() };
|
|
(status, value)
|
|
}
|
|
|
|
/// The queued e-mails of a template: (recipient, payload), oldest first.
|
|
async fn mails(&self, template: &str) -> Vec<(String, Value)> {
|
|
sqlx::query_as("SELECT to_email, payload FROM email_outbox WHERE template = $1 ORDER BY created_at, id")
|
|
.bind(template)
|
|
.fetch_all(&self.pool)
|
|
.await
|
|
.unwrap()
|
|
}
|
|
|
|
async fn get(&self, uri: &str, user: Option<&User>) -> Value {
|
|
let (status, body) = self.call("GET", uri, user, Value::Null).await;
|
|
assert_eq!(status, StatusCode::OK, "GET {uri}: {body}");
|
|
body
|
|
}
|
|
|
|
/// Starts a thread; returns its id.
|
|
async fn thread(&self, user: &User, topic: &str, title: &str) -> i64 {
|
|
let (status, body) = self
|
|
.call(
|
|
"POST",
|
|
"/v1/forum/threads",
|
|
Some(user),
|
|
json!({ "topic": topic, "title": title, "body": "Az első gondolat." }),
|
|
)
|
|
.await;
|
|
assert_eq!(status, StatusCode::CREATED, "{body}");
|
|
body["id"].as_i64().unwrap()
|
|
}
|
|
|
|
/// Replies; returns the new post.
|
|
async fn reply(&self, user: &User, thread: i64, body: &str, parent: Option<i64>) -> Value {
|
|
let (status, post) = self
|
|
.call(
|
|
"POST",
|
|
&format!("/v1/forum/threads/{thread}/posts"),
|
|
Some(user),
|
|
json!({ "body": body, "parent_id": parent }),
|
|
)
|
|
.await;
|
|
assert_eq!(status, StatusCode::CREATED, "{post}");
|
|
post
|
|
}
|
|
}
|
|
|
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
|
async fn a_nickname_comes_first_and_stays_unique(pool: PgPool) {
|
|
let app = TestApp::new(pool);
|
|
let visitor_try = app
|
|
.call("POST", "/v1/forum/threads", None, json!({ "topic": "torzsasztal", "title": "Szia", "body": "x" }))
|
|
.await;
|
|
assert_eq!(visitor_try.0, StatusCode::UNAUTHORIZED);
|
|
|
|
let anna = app.user("anna@example.com", &["user"]).await;
|
|
let (status, body) = app
|
|
.call(
|
|
"POST",
|
|
"/v1/forum/threads",
|
|
Some(&anna),
|
|
json!({ "topic": "torzsasztal", "title": "Szia mindenki", "body": "x" }),
|
|
)
|
|
.await;
|
|
assert_eq!((status, body["error"]["code"].as_str()), (StatusCode::FORBIDDEN, Some("nickname_required")));
|
|
let me = app.get("/v1/forum/me", Some(&anna)).await;
|
|
assert!(me["member"].is_null());
|
|
assert_eq!(me["viewer"]["needs_nickname"], true);
|
|
|
|
// The real name is never offered or shown.
|
|
let (status, me) = app.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": " Hold fény " })).await;
|
|
assert_eq!(status, StatusCode::OK, "{me}");
|
|
assert_eq!(me["member"]["nickname"], "Hold fény");
|
|
assert_eq!(me["member"]["rank"], "vandor");
|
|
assert!(!me.to_string().contains("Valódi"));
|
|
|
|
// Folded the same: taken.
|
|
let bea = app.user("bea@example.com", &["user"]).await;
|
|
let check = app.get("/v1/forum/nickname-check?name=holdfeny", Some(&bea)).await;
|
|
assert_eq!(check["ok"], false);
|
|
let (status, body) = app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Ho1dfény" })).await;
|
|
assert_eq!((status, body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("nickname_taken")));
|
|
assert_eq!(app.get("/v1/forum/nickname-check?name=Napraforgó", Some(&bea)).await["ok"], true);
|
|
app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Napraforgó" })).await;
|
|
|
|
// A spelling fix any time; a new name once in 30 days.
|
|
let (status, _) = app.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": "Holdfény" })).await;
|
|
assert_eq!(status, StatusCode::OK);
|
|
let (status, body) = app.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": "Csillagpor" })).await;
|
|
assert_eq!((status, body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("nickname_too_soon")));
|
|
app.season(&anna, 31, 0).await;
|
|
let (status, _) = app.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": "Csillagpor" })).await;
|
|
assert_eq!(status, StatusCode::OK);
|
|
// The old name stays reserved for others…
|
|
let (status, _) = app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Holdfény" })).await;
|
|
assert_eq!(status, StatusCode::CONFLICT);
|
|
// …and the profile is found by the new one, in any spelling.
|
|
let profile = app.get("/v1/forum/members/csillagpor", None).await;
|
|
assert_eq!(profile["member"]["author"]["nickname"], "Csillagpor");
|
|
|
|
let (status, _) = app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Admin Bea" })).await;
|
|
assert_eq!(status, StatusCode::BAD_REQUEST);
|
|
let (status, _) =
|
|
app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Bea", "avatar": "hold-piros" })).await;
|
|
assert_eq!(status, StatusCode::BAD_REQUEST);
|
|
}
|
|
|
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
|
async fn threads_replies_and_what_is_new(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", "Holdfény", &["user"]).await;
|
|
|
|
// A listening topic: members only, threads ask for listening by default.
|
|
let heart = app.thread(&anna, "ami-a-szivemen-van", "Nem tudom elengedni anyukám házát").await;
|
|
let (status, _) = app.call("GET", &format!("/v1/forum/threads/{heart}"), None, Value::Null).await;
|
|
assert_eq!(status, StatusCode::UNAUTHORIZED, "visitors may not read a members-only topic");
|
|
let (status, _) = app.call("GET", "/v1/forum/topics/ami-a-szivemen-van", None, Value::Null).await;
|
|
assert_eq!(status, StatusCode::UNAUTHORIZED);
|
|
let shown = app.get(&format!("/v1/forum/threads/{heart}"), Some(&bea)).await;
|
|
assert_eq!(shown["thread"]["intent"], "listen");
|
|
assert_eq!(shown["thread"]["slug"], "nem-tudom-elengedni-anyukam-hazat");
|
|
assert_eq!(shown["access"]["can_downvote"], false);
|
|
|
|
// A visitor sees the public topics and that the members-only one exists.
|
|
let public = app.thread(&anna, "torzsasztal", "Téli levesek").await;
|
|
let home = app.get("/v1/forum/home", None).await;
|
|
let topics = home["topics"].as_array().unwrap();
|
|
assert_eq!(topics[0]["readable"], false);
|
|
assert!(topics[0].get("thread_count").is_none());
|
|
assert_eq!(topics[3]["thread_count"], 1);
|
|
let waiting: Vec<i64> = home["unanswered"].as_array().unwrap().iter().map(|t| t["id"].as_i64().unwrap()).collect();
|
|
assert_eq!(waiting, vec![public], "the visitor sees only the public thread waiting");
|
|
|
|
// Bea sees both waiting and both as new; Anna does not see her own.
|
|
let home = app.get("/v1/forum/home", Some(&bea)).await;
|
|
assert_eq!(home["unanswered"].as_array().unwrap().len(), 2);
|
|
assert_eq!(home["topics"][0]["new_count"], 1);
|
|
assert!(app.get("/v1/forum/home", Some(&anna)).await["unanswered"].as_array().unwrap().is_empty());
|
|
|
|
// Replies: a reply to a reply stays on the second level.
|
|
let first = app.reply(&bea, heart, "Nem vagy egyedül :)", None).await;
|
|
assert_eq!(first["body"], "Nem vagy egyedül 🙂");
|
|
assert_eq!(first["author"]["nickname"], "Holdfény");
|
|
let second = app.reply(&anna, heart, "Köszönöm.", first["id"].as_i64()).await;
|
|
let third = app.reply(&bea, heart, "Szívesen.", second["id"].as_i64()).await;
|
|
assert_eq!(third["parent_id"], first["id"]);
|
|
|
|
// Anna follows her thread: one new reply from Bea since she last read.
|
|
let home = app.get("/v1/forum/home", Some(&anna)).await;
|
|
assert_eq!(home["followed"]["new_replies"], 1);
|
|
let shown = app.get(&format!("/v1/forum/threads/{heart}"), Some(&anna)).await;
|
|
assert_eq!(shown["posts"].as_array().unwrap().len(), 4);
|
|
assert_eq!(shown["access"]["last_read_post_id"], second["id"]);
|
|
let (status, _) = app
|
|
.call("POST", &format!("/v1/forum/threads/{heart}/read"), Some(&anna), json!({ "post_id": third["id"] }))
|
|
.await;
|
|
assert_eq!(status, StatusCode::NO_CONTENT);
|
|
assert_eq!(app.get("/v1/forum/home", Some(&anna)).await["followed"]["new_replies"], 0);
|
|
let followed = app.get("/v1/forum/followed", Some(&anna)).await;
|
|
assert_eq!(followed["threads"].as_array().unwrap().len(), 2);
|
|
assert_eq!(followed["threads"][0]["reply_count"], 3);
|
|
|
|
// Busy today: three replies make it "pörgős".
|
|
assert_eq!(app.get("/v1/forum/home", Some(&bea)).await["hot"][0]["id"], heart);
|
|
|
|
// Editing one's own post only.
|
|
let (status, _) =
|
|
app.call("PATCH", &format!("/v1/forum/posts/{}", first["id"]), Some(&anna), json!({ "body": "Átírva" })).await;
|
|
assert_eq!(status, StatusCode::FORBIDDEN);
|
|
let (status, edited) = app
|
|
.call("PATCH", &format!("/v1/forum/posts/{}", first["id"]), Some(&bea), json!({ "body": "Nem vagy egyedül." }))
|
|
.await;
|
|
assert_eq!(status, StatusCode::OK);
|
|
assert!(edited["edited_at"].is_string());
|
|
|
|
// Taking back one's own post: its place stays, the text goes.
|
|
let (status, _) = app.call("DELETE", &format!("/v1/forum/posts/{}", third["id"]), Some(&bea), json!({})).await;
|
|
assert_eq!(status, StatusCode::NO_CONTENT);
|
|
let shown = app.get(&format!("/v1/forum/threads/{heart}"), Some(&anna)).await;
|
|
let gone = shown["posts"].as_array().unwrap().iter().find(|p| p["id"] == third["id"]).unwrap().clone();
|
|
assert!(gone["body"].is_null());
|
|
assert_eq!(gone["deleted"]["by_moderator"], false);
|
|
assert_eq!(app.get("/v1/forum/followed", Some(&anna)).await["threads"][0]["reply_count"], 2);
|
|
}
|
|
|
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
|
async fn reactions_give_points_and_ranks(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", "Holdfény", &["user"]).await;
|
|
let cili = app.member("cili@example.com", "Zöldág", &["user"]).await;
|
|
let thread = app.thread(&anna, "belso-utak", "Reggeli csend").await;
|
|
let post = app.reply(&bea, thread, "Én hajnalban ülök le.", None).await;
|
|
let post_id = post["id"].as_i64().unwrap();
|
|
let react = |user: &User, kind: &str| {
|
|
let uri = format!("/v1/forum/posts/{post_id}/reaction");
|
|
let body = json!({ "kind": kind });
|
|
let user = User { id: user.id, token: user.token.clone() };
|
|
let app = &app;
|
|
async move { app.call("PUT", &uri, Some(&user), body).await }
|
|
};
|
|
|
|
// A newcomer's reaction shows but gives no points; no ⌄ for newcomers.
|
|
let (status, shown) = react(&cili, "with_you").await;
|
|
assert_eq!(status, StatusCode::OK, "{shown}");
|
|
assert_eq!(shown["reactions"]["with_you"], 1);
|
|
assert_eq!(app.points(&bea).await, 0);
|
|
assert_eq!(react(&cili, "down").await.0, StatusCode::FORBIDDEN);
|
|
assert_eq!(react(&bea, "thanks").await.0, StatusCode::FORBIDDEN, "not on one's own post");
|
|
assert_eq!(react(&cili, "hug").await.0, StatusCode::BAD_REQUEST);
|
|
|
|
// A seasoned member's reaction counts; changing it to ⌄ swings by two.
|
|
app.season(&anna, 10, 5).await;
|
|
let (_, shown) = react(&anna, "insight").await;
|
|
assert_eq!(shown["mine"], "insight");
|
|
assert_eq!(app.points(&bea).await, 1);
|
|
let (_, shown) = react(&anna, "down").await;
|
|
assert_eq!(app.points(&bea).await, -1);
|
|
assert!(shown.get("down").is_none(), "only moderators see the ⌄ count");
|
|
assert_eq!(shown["score"], 0);
|
|
let (status, _) =
|
|
app.call("DELETE", &format!("/v1/forum/posts/{post_id}/reaction"), Some(&anna), Value::Null).await;
|
|
assert_eq!(status, StatusCode::OK);
|
|
assert_eq!(app.points(&bea).await, 0);
|
|
|
|
// "Ez segített": only the thread's author, worth five.
|
|
let (status, _) = app.call("PUT", &format!("/v1/forum/posts/{post_id}/helped"), Some(&cili), Value::Null).await;
|
|
assert_eq!(status, StatusCode::FORBIDDEN);
|
|
let (status, shown) = app.call("PUT", &format!("/v1/forum/posts/{post_id}/helped"), Some(&anna), Value::Null).await;
|
|
assert_eq!(status, StatusCode::OK);
|
|
assert_eq!(shown["helped"], true);
|
|
app.call("PUT", &format!("/v1/forum/posts/{post_id}/helped"), Some(&anna), Value::Null).await;
|
|
assert_eq!(app.points(&bea).await, 5, "marking twice counts once");
|
|
|
|
// Points alone do not make a rank: time does too.
|
|
let me = app.get("/v1/forum/me", Some(&bea)).await;
|
|
assert_eq!(me["member"]["rank"], "vandor");
|
|
assert_eq!(me["member"]["next_rank"]["name"], "Kereső");
|
|
app.season(&bea, 3, 5).await;
|
|
assert_eq!(app.get("/v1/forum/me", Some(&bea)).await["member"]["rank"], "kereso");
|
|
|
|
// No ⌄ in a listening topic, whatever the rank.
|
|
let heart = app.thread(&cili, "ami-a-szivemen-van", "Nehéz napok").await;
|
|
let opening = app.get(&format!("/v1/forum/threads/{heart}"), Some(&anna)).await["posts"][0]["id"].as_i64().unwrap();
|
|
let (status, _) =
|
|
app.call("PUT", &format!("/v1/forum/posts/{opening}/reaction"), Some(&anna), json!({ "kind": "down" })).await;
|
|
assert_eq!(status, StatusCode::FORBIDDEN);
|
|
}
|
|
|
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
|
async fn moderators_remove_and_ban(pool: PgPool) {
|
|
let app = TestApp::new(pool);
|
|
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
|
|
let spam = app.member("spam@example.com", "Gyógyító", &["user"]).await;
|
|
let moderator = app.member("mod@example.com", "Őrangyal", &["user", "moderator"]).await;
|
|
let admin = app.member("admin@example.com", "Gondnok", &["admin"]).await;
|
|
let thread = app.thread(&anna, "belso-utak", "Energiák").await;
|
|
let ad = app.reply(&spam, thread, "Energetikai gyógyítás, írj privátban!", None).await;
|
|
let ad_id = ad["id"].as_i64().unwrap();
|
|
|
|
// Members may not remove others' posts; a moderator needs a reason.
|
|
let (status, _) = app.call("DELETE", &format!("/v1/forum/posts/{ad_id}"), Some(&anna), json!({})).await;
|
|
assert_eq!(status, StatusCode::FORBIDDEN);
|
|
let (status, _) = app.call("DELETE", &format!("/v1/forum/posts/{ad_id}"), Some(&moderator), json!({})).await;
|
|
assert_eq!(status, StatusCode::BAD_REQUEST);
|
|
let (status, _) = app
|
|
.call(
|
|
"DELETE",
|
|
&format!("/v1/forum/posts/{ad_id}"),
|
|
Some(&moderator),
|
|
json!({ "reason": "szolgáltatás hirdetése" }),
|
|
)
|
|
.await;
|
|
assert_eq!(status, StatusCode::NO_CONTENT);
|
|
let seen = app.get(&format!("/v1/forum/threads/{thread}"), Some(&anna)).await;
|
|
assert!(seen["posts"][1]["body"].is_null());
|
|
assert_eq!(seen["posts"][1]["deleted"]["reason"], "szolgáltatás hirdetése");
|
|
assert_eq!(seen["posts"][1]["deleted"]["by_moderator"], true);
|
|
let seen = app.get(&format!("/v1/forum/threads/{thread}"), Some(&moderator)).await;
|
|
assert!(seen["posts"][1]["body"].is_string(), "moderators still see the text");
|
|
// The author is told what and why (whatever their notification settings).
|
|
let told = app.mails("forum_moderation").await;
|
|
assert_eq!(told.len(), 1);
|
|
assert_eq!(told[0].0, "spam@example.com");
|
|
assert_eq!(told[0].1["action"], "post_removed");
|
|
assert_eq!(told[0].1["reason"], "szolgáltatás hirdetése");
|
|
assert_eq!(told[0].1["thread_title"], "Energiák");
|
|
assert_eq!(told[0].1["nickname"], "Gyógyító");
|
|
|
|
// Only the admin restores.
|
|
let (status, _) =
|
|
app.call("POST", &format!("/v1/forum/posts/{ad_id}/restore"), Some(&moderator), Value::Null).await;
|
|
assert_eq!(status, StatusCode::FORBIDDEN);
|
|
let (status, _) = app.call("POST", &format!("/v1/forum/posts/{ad_id}/restore"), Some(&admin), Value::Null).await;
|
|
assert_eq!(status, StatusCode::NO_CONTENT);
|
|
|
|
// A ban: reading yes, writing no; moderators cannot be banned.
|
|
let (status, body) = app
|
|
.call("POST", "/v1/forum/members/gyogyito/ban", Some(&moderator), json!({ "hours": 48, "reason": "hirdetés" }))
|
|
.await;
|
|
assert_eq!(status, StatusCode::OK, "{body}");
|
|
let told = app.mails("forum_moderation").await;
|
|
assert_eq!((told[1].1["action"].as_str(), told[1].1["duration"].as_str()), (Some("banned"), Some("2 napos")));
|
|
let (status, body) = app
|
|
.call("POST", &format!("/v1/forum/threads/{thread}/posts"), Some(&spam), json!({ "body": "Még egyszer" }))
|
|
.await;
|
|
assert_eq!((status, body["error"]["code"].as_str()), (StatusCode::FORBIDDEN, Some("banned")));
|
|
app.get(&format!("/v1/forum/threads/{thread}"), Some(&spam)).await;
|
|
assert!(app.get("/v1/forum/me", Some(&spam)).await["member"]["banned_until"].is_string());
|
|
let (status, _) =
|
|
app.call("POST", "/v1/forum/members/orangyal/ban", Some(&moderator), json!({ "reason": "teszt" })).await;
|
|
assert_eq!(status, StatusCode::FORBIDDEN);
|
|
let (status, _) =
|
|
app.call("POST", "/v1/forum/members/csendesviz/ban", Some(&anna), json!({ "reason": "teszt" })).await;
|
|
assert_eq!(status, StatusCode::FORBIDDEN);
|
|
// For good, then lifted.
|
|
let (_, body) = app
|
|
.call("POST", "/v1/forum/members/gyogyito/ban", Some(&moderator), json!({ "reason": "ismételt hirdetés" }))
|
|
.await;
|
|
assert_eq!(body["banned_until"], "infinity");
|
|
let (status, _) = app.call("DELETE", "/v1/forum/members/gyogyito/ban", Some(&moderator), Value::Null).await;
|
|
assert_eq!(status, StatusCode::NO_CONTENT);
|
|
app.reply(&spam, thread, "Bocsánat.", None).await;
|
|
|
|
// Lock and remove a thread; others see only the reason.
|
|
let (status, _) =
|
|
app.call("PATCH", &format!("/v1/forum/threads/{thread}"), Some(&moderator), json!({ "locked": true })).await;
|
|
assert_eq!(status, StatusCode::NO_CONTENT);
|
|
let (status, _) = app
|
|
.call("POST", &format!("/v1/forum/threads/{thread}/posts"), Some(&anna), json!({ "body": "Lezárva?" }))
|
|
.await;
|
|
assert_eq!(status, StatusCode::FORBIDDEN);
|
|
let (status, _) = app
|
|
.call("DELETE", &format!("/v1/forum/threads/{thread}"), Some(&moderator), json!({ "reason": "vita elfajult" }))
|
|
.await;
|
|
assert_eq!(status, StatusCode::NO_CONTENT);
|
|
let seen = app.get(&format!("/v1/forum/threads/{thread}"), Some(&anna)).await;
|
|
assert_eq!(seen["thread"]["deleted"]["reason"], "vita elfajult");
|
|
assert!(seen["posts"].as_array().unwrap().is_empty());
|
|
assert!(app.get("/v1/forum/topics/belso-utak", Some(&anna)).await["threads"].as_array().unwrap().is_empty());
|
|
|
|
// Every step is in the log, which only moderators read.
|
|
let (status, _) = app.call("GET", "/v1/forum/mod/log", Some(&anna), Value::Null).await;
|
|
assert_eq!(status, StatusCode::FORBIDDEN);
|
|
let log = app.get("/v1/forum/mod/log", Some(&moderator)).await;
|
|
let actions: Vec<&str> = log["entries"].as_array().unwrap().iter().map(|e| e["action"].as_str().unwrap()).collect();
|
|
assert_eq!(actions, vec!["delete_thread", "lock", "unban", "ban", "ban", "restore_post", "delete_post"]);
|
|
assert_eq!(log["entries"][6]["actor"], "Őrangyal");
|
|
assert_eq!(log["entries"][6]["target"], "Gyógyító");
|
|
}
|
|
|
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
|
async fn newcomer_limits_and_a_purchase(pool: PgPool) {
|
|
let app = TestApp::new(pool);
|
|
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
|
|
for i in 0..3 {
|
|
app.thread(&anna, "torzsasztal", &format!("Kérdés {i}")).await;
|
|
}
|
|
let (status, body) = app
|
|
.call(
|
|
"POST",
|
|
"/v1/forum/threads",
|
|
Some(&anna),
|
|
json!({ "topic": "torzsasztal", "title": "Negyedik", "body": "x" }),
|
|
)
|
|
.await;
|
|
assert_eq!((status, body["error"]["code"].as_str()), (StatusCode::TOO_MANY_REQUESTS, Some("limited")));
|
|
// A purchase lifts the newcomer limits (but gives no rank).
|
|
sqlx::query("INSERT INTO package_orders (id, user_id, package, source, price_huf) VALUES ($1, $2, 'egyeni', 'stripe', 4900)")
|
|
.bind(Uuid::now_v7())
|
|
.bind(anna.id)
|
|
.execute(&app.pool)
|
|
.await
|
|
.unwrap();
|
|
app.thread(&anna, "torzsasztal", "Negyedik").await;
|
|
assert_eq!(app.get("/v1/forum/me", Some(&anna)).await["member"]["rank"], "vandor");
|
|
}
|
|
|
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
|
async fn profiles_share_signs_never_degrees(pool: PgPool) {
|
|
let app = TestApp::new(pool);
|
|
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
|
|
let result = json!({
|
|
"points": [
|
|
{"id": "sun", "sign": "pisces", "longitude": 345.2},
|
|
{"id": "moon", "sign": "cancer", "longitude": 101.7},
|
|
{"id": "venus", "sign": "aries", "longitude": 12.0},
|
|
{"id": "mean_node", "sign": "leo", "longitude": 130.0}
|
|
],
|
|
"angles": {"ascendant": {"sign": "virgo", "longitude": 160.4}},
|
|
"time": {"time_known": true}
|
|
});
|
|
sqlx::query(
|
|
"INSERT INTO charts (id, owner_id, label, is_primary, kind, birth_data, result, chart_hash) \
|
|
VALUES ($1, $2, 'Én', true, 'own', '{}', $3, 'x')",
|
|
)
|
|
.bind(Uuid::now_v7())
|
|
.bind(anna.id)
|
|
.bind(&result)
|
|
.execute(&app.pool)
|
|
.await
|
|
.unwrap();
|
|
|
|
let profile = app.get("/v1/forum/members/Csendesvíz", None).await;
|
|
assert!(profile["member"]["author"]["signs"].is_null(), "nothing shared by default");
|
|
let me = app.get("/v1/forum/me", Some(&anna)).await;
|
|
assert_eq!(me["chart"]["big3"], json!({"sun": "pisces", "moon": "cancer", "ascendant": "virgo"}));
|
|
|
|
let (status, _) = app
|
|
.call(
|
|
"PUT",
|
|
"/v1/forum/me",
|
|
Some(&anna),
|
|
json!({ "nickname": "Csendesvíz", "chart_share": "planets", "bio": "Szia <3" }),
|
|
)
|
|
.await;
|
|
assert_eq!(status, StatusCode::OK);
|
|
let profile = app.get("/v1/forum/members/Csendesvíz", None).await;
|
|
assert_eq!(
|
|
profile["member"]["author"]["signs"],
|
|
json!({"sun": "pisces", "moon": "cancer", "venus": "aries", "ascendant": "virgo"})
|
|
);
|
|
assert_eq!(profile["member"]["bio"], "Szia ❤️");
|
|
assert!(!profile.to_string().contains("longitude") && !profile.to_string().contains("345"));
|
|
let (status, _) = app
|
|
.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": "Csendesvíz", "bio": "www.gyogyitas.hu" }))
|
|
.await;
|
|
assert_eq!(status, StatusCode::BAD_REQUEST);
|
|
|
|
// Online now, unless invisible.
|
|
assert_eq!(profile["member"]["author"]["online"], true);
|
|
app.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": "Csendesvíz", "invisible": true })).await;
|
|
let profile = app.get("/v1/forum/members/Csendesvíz", None).await;
|
|
assert_eq!(profile["member"]["author"]["online"], false);
|
|
assert!(profile["member"]["last_seen"].is_null());
|
|
}
|
|
|
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
|
async fn reports_reach_moderators(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", "Holdfény", &["user"]).await;
|
|
let cili = app.user("cili@example.com", &["user"]).await; // no nickname: may still report
|
|
let moderator = app.member("mod@example.com", "Őrangyal", &["user", "moderator"]).await;
|
|
let thread = app.thread(&anna, "belso-utak", "Energiák").await;
|
|
let post = app.reply(&bea, thread, "Energetikai gyógyítás, írj!", None).await["id"].as_i64().unwrap();
|
|
|
|
let report = |user: &User, body: Value| {
|
|
let uri = format!("/v1/forum/posts/{post}/report");
|
|
let user = User { id: user.id, token: user.token.clone() };
|
|
let app = &app;
|
|
async move { app.call("POST", &uri, Some(&user), body).await }
|
|
};
|
|
assert_eq!(
|
|
app.call("POST", &format!("/v1/forum/posts/{post}/report"), None, json!({"kind": "ad"})).await.0,
|
|
StatusCode::UNAUTHORIZED
|
|
);
|
|
assert_eq!(report(&bea, json!({"kind": "ad"})).await.0, StatusCode::BAD_REQUEST, "not one's own");
|
|
assert_eq!(report(&anna, json!({"kind": "other"})).await.0, StatusCode::BAD_REQUEST, "'other' needs a note");
|
|
assert_eq!(report(&anna, json!({"kind": "nonsense"})).await.0, StatusCode::BAD_REQUEST);
|
|
let (status, body) = report(&anna, json!({"kind": "ad", "note": "jóslást árul"})).await;
|
|
assert_eq!((status, body["crisis"].as_bool()), (StatusCode::CREATED, Some(false)));
|
|
assert_eq!(report(&anna, json!({"kind": "ad"})).await.0, StatusCode::CREATED, "a repeat changes nothing");
|
|
let (_, body) = report(&cili, json!({"kind": "crisis"})).await;
|
|
assert_eq!(body["crisis"], true);
|
|
|
|
// Only moderators see them; the crisis one first; the menu shows the count.
|
|
assert_eq!(app.call("GET", "/v1/forum/mod/reports", Some(&anna), Value::Null).await.0, StatusCode::FORBIDDEN);
|
|
let list = app.get("/v1/forum/mod/reports", Some(&moderator)).await;
|
|
let reports = list["reports"].as_array().unwrap();
|
|
assert_eq!(reports.len(), 2);
|
|
assert_eq!(reports[0]["kind"], "crisis");
|
|
assert_eq!(reports[1]["reporter"], "Csendesvíz");
|
|
assert_eq!(reports[1]["target"]["body"], "Energetikai gyógyítás, írj!");
|
|
assert_eq!(reports[1]["open_reports_of_target"], 2);
|
|
assert_eq!(app.get("/v1/forum/nav", Some(&moderator)).await["reports"], 2);
|
|
assert!(app.get("/v1/forum/nav", Some(&anna)).await["reports"].is_null());
|
|
|
|
// Removing the post resolves every open report of it, and it is logged.
|
|
let (status, _) = app
|
|
.call(
|
|
"DELETE",
|
|
&format!("/v1/forum/posts/{post}"),
|
|
Some(&moderator),
|
|
json!({ "reason": "szolgáltatás hirdetése" }),
|
|
)
|
|
.await;
|
|
assert_eq!(status, StatusCode::NO_CONTENT);
|
|
let list = app.get("/v1/forum/mod/reports", Some(&moderator)).await;
|
|
assert!(list["reports"].as_array().unwrap().iter().all(|r| r["status"] == "resolved"));
|
|
// Both reporters hear the decision, once each.
|
|
let told = app.mails("forum_report_result").await;
|
|
let mut to: Vec<&str> = told.iter().map(|(t, _)| t.as_str()).collect();
|
|
to.sort_unstable();
|
|
assert_eq!(to, vec!["anna@example.com", "cili@example.com"]);
|
|
assert!(told.iter().all(|(_, p)| p["outcome"] == "removed"));
|
|
assert_eq!(app.get("/v1/forum/nav", Some(&moderator)).await["reports"], 0);
|
|
|
|
// A report can also be dismissed.
|
|
let other = app.reply(&bea, thread, "Bocsánat.", None).await["id"].as_i64().unwrap();
|
|
app.call("POST", &format!("/v1/forum/posts/{other}/report"), Some(&anna), json!({"kind": "rude"})).await;
|
|
let id = app.get("/v1/forum/mod/reports", Some(&moderator)).await["reports"][0]["id"].as_i64().unwrap();
|
|
let (status, _) = app
|
|
.call("POST", &format!("/v1/forum/mod/reports/{id}"), Some(&moderator), json!({ "action": "dismiss" }))
|
|
.await;
|
|
assert_eq!(status, StatusCode::NO_CONTENT);
|
|
let told = app.mails("forum_report_result").await;
|
|
assert_eq!((told[2].0.as_str(), told[2].1["outcome"].as_str()), ("anna@example.com", Some("no_violation")));
|
|
let log = app.get("/v1/forum/mod/log", Some(&moderator)).await;
|
|
assert_eq!(log["entries"][0]["action"], "dismiss_report");
|
|
assert_eq!(log["entries"][0]["target"], "Holdfény");
|
|
}
|
|
|
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
|
async fn private_messages_start_with_a_request(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", "Holdfény", &["user"]).await;
|
|
let cili = app.member("cili@example.com", "Zöldág", &["user"]).await;
|
|
let request = |from: &User, to: &str, intro: &str| {
|
|
let user = User { id: from.id, token: from.token.clone() };
|
|
let body = json!({ "to": to, "intro": intro });
|
|
let app = &app;
|
|
async move { app.call("POST", "/v1/forum/conversations", Some(&user), body).await }
|
|
};
|
|
|
|
// A newcomer may not start one; a seasoned member who wrote in public may.
|
|
let (status, _) = request(&anna, "Holdfény", "Szia, olvastam a hozzászólásodat.").await;
|
|
assert_eq!(status, StatusCode::FORBIDDEN);
|
|
let profile = app.get("/v1/forum/members/Holdfény", Some(&anna)).await;
|
|
assert_eq!(profile["relation"]["can_request"], false);
|
|
app.thread(&anna, "torzsasztal", "Sziasztok").await;
|
|
app.season(&anna, 5, 10).await;
|
|
assert_eq!(app.get("/v1/forum/members/Holdfény", Some(&anna)).await["relation"]["can_request"], true);
|
|
assert_eq!(request(&anna, "Holdfény", "Nézd: www.pelda.hu").await.0, StatusCode::BAD_REQUEST);
|
|
assert_eq!(request(&anna, "Csendesvíz", "Szia, én vagyok.").await.0, StatusCode::BAD_REQUEST);
|
|
let (status, body) = request(&anna, "holdfeny", "Szia, olvastam a hozzászólásodat :)").await;
|
|
assert_eq!(status, StatusCode::CREATED, "{body}");
|
|
let id = body["id"].as_i64().unwrap();
|
|
let (_, body) = request(&anna, "Holdfény", "Még egyszer").await;
|
|
assert_eq!(body["error"]["code"], "request_pending");
|
|
|
|
// Bea sees the request (and the badge); no messages before accepting.
|
|
assert_eq!(app.get("/v1/forum/nav", Some(&bea)).await["messages"], 1);
|
|
let list = app.get("/v1/forum/conversations", Some(&bea)).await;
|
|
assert_eq!(list["conversations"][0]["state"], "incoming");
|
|
assert_eq!(list["conversations"][0]["intro"], "Szia, olvastam a hozzászólásodat 🙂");
|
|
let (status, _) =
|
|
app.call("POST", &format!("/v1/forum/conversations/{id}/messages"), Some(&anna), json!({"body": "Hahó"})).await;
|
|
assert_eq!(status, StatusCode::FORBIDDEN);
|
|
let (status, _) = app.call("POST", &format!("/v1/forum/conversations/{id}/accept"), Some(&anna), Value::Null).await;
|
|
assert_eq!(status, StatusCode::BAD_REQUEST, "only the recipient accepts");
|
|
let (status, _) = app.call("POST", &format!("/v1/forum/conversations/{id}/accept"), Some(&bea), Value::Null).await;
|
|
assert_eq!(status, StatusCode::NO_CONTENT);
|
|
|
|
// Messages both ways; unread counts; no read receipts.
|
|
let (status, msg) = app
|
|
.call("POST", &format!("/v1/forum/conversations/{id}/messages"), Some(&anna), json!({"body": "Hahó <3"}))
|
|
.await;
|
|
assert_eq!(status, StatusCode::CREATED);
|
|
assert_eq!(msg["body"], "Hahó ❤️");
|
|
assert_eq!(app.get("/v1/forum/nav", Some(&bea)).await["messages"], 1);
|
|
let shown = app.get(&format!("/v1/forum/conversations/{id}"), Some(&bea)).await;
|
|
assert_eq!(shown["conversation"]["state"], "accepted");
|
|
assert_eq!(shown["messages"][0]["mine"], false);
|
|
app.call("POST", &format!("/v1/forum/conversations/{id}/read"), Some(&bea), json!({"message_id": msg["id"]})).await;
|
|
assert_eq!(app.get("/v1/forum/nav", Some(&bea)).await["messages"], 0);
|
|
let reply = app
|
|
.call("POST", &format!("/v1/forum/conversations/{id}/messages"), Some(&bea), json!({"body": "Szia!"}))
|
|
.await
|
|
.1;
|
|
// Nobody else sees the conversation.
|
|
let (status, _) = app.call("GET", &format!("/v1/forum/conversations/{id}"), Some(&cili), Value::Null).await;
|
|
assert_eq!(status, StatusCode::NOT_FOUND);
|
|
|
|
// A reported message is what moderators see, with the messages before it.
|
|
let moderator = app.member("mod@example.com", "Őrangyal", &["moderator"]).await;
|
|
let (status, _) = app
|
|
.call("POST", &format!("/v1/forum/messages/{}/report", reply["id"]), Some(&cili), json!({"kind": "rude"}))
|
|
.await;
|
|
assert_eq!(status, StatusCode::NOT_FOUND, "only a participant may report it");
|
|
let (status, _) = app
|
|
.call("POST", &format!("/v1/forum/messages/{}/report", reply["id"]), Some(&anna), json!({"kind": "rude"}))
|
|
.await;
|
|
assert_eq!(status, StatusCode::CREATED);
|
|
let reports = app.get("/v1/forum/mod/reports", Some(&moderator)).await;
|
|
let context = reports["reports"][0]["target"]["messages"].as_array().unwrap().clone();
|
|
assert_eq!(context.len(), 2);
|
|
assert_eq!(context[1]["reported"], true);
|
|
assert_eq!(context[0]["sender"]["nickname"], "Csendesvíz");
|
|
|
|
// A decline is silent: Cili's request just stays "sent" for her.
|
|
app.thread(&cili, "torzsasztal", "Én is itt vagyok").await;
|
|
app.season(&cili, 5, 10).await;
|
|
let (_, body) = request(&cili, "Holdfény", "Szia, beszélgetnénk?").await;
|
|
let second = body["id"].as_i64().unwrap();
|
|
app.call("POST", &format!("/v1/forum/conversations/{second}/decline"), Some(&bea), Value::Null).await;
|
|
let list = app.get("/v1/forum/conversations", Some(&cili)).await;
|
|
assert_eq!(list["conversations"][0]["state"], "outgoing");
|
|
assert!(
|
|
app.get("/v1/forum/conversations", Some(&bea)).await["conversations"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.all(|c| c["id"] != second)
|
|
);
|
|
let (_, body) = request(&cili, "Holdfény", "Újra én").await;
|
|
assert_eq!(body["error"]["code"], "request_pending");
|
|
|
|
// Blocking stops the conversation; unblocking is the blocker's.
|
|
let (status, _) = app.call("POST", &format!("/v1/forum/conversations/{id}/block"), Some(&bea), Value::Null).await;
|
|
assert_eq!(status, StatusCode::NO_CONTENT);
|
|
let (status, _) =
|
|
app.call("POST", &format!("/v1/forum/conversations/{id}/messages"), Some(&anna), json!({"body": "?"})).await;
|
|
assert_eq!(status, StatusCode::FORBIDDEN);
|
|
assert_eq!(
|
|
app.get(&format!("/v1/forum/conversations/{id}"), Some(&anna)).await["conversation"]["state"],
|
|
"outgoing"
|
|
);
|
|
assert_eq!(
|
|
app.get(&format!("/v1/forum/conversations/{id}"), Some(&bea)).await["conversation"]["state"],
|
|
"blocked_by_me"
|
|
);
|
|
let (status, _) =
|
|
app.call("DELETE", &format!("/v1/forum/conversations/{id}/block"), Some(&anna), Value::Null).await;
|
|
assert_eq!(status, StatusCode::BAD_REQUEST);
|
|
let (status, _) = app.call("DELETE", &format!("/v1/forum/conversations/{id}/block"), Some(&bea), Value::Null).await;
|
|
assert_eq!(status, StatusCode::NO_CONTENT);
|
|
}
|
|
|
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
|
async fn instant_mails_and_unsubscribe(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", "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"}));
|
|
let (status, _) = app
|
|
.call(
|
|
"PUT",
|
|
"/v1/forum/me",
|
|
Some(&anna),
|
|
json!({ "nickname": "Csendesvíz", "email": { "replies": "instant" } }),
|
|
)
|
|
.await;
|
|
assert_eq!(status, StatusCode::OK);
|
|
let (status, _) = app
|
|
.call(
|
|
"PUT",
|
|
"/v1/forum/me",
|
|
Some(&anna),
|
|
json!({ "nickname": "Csendesvíz", "email": { "followed": "instant" } }),
|
|
)
|
|
.await;
|
|
assert_eq!(status, StatusCode::BAD_REQUEST);
|
|
let thread = app.thread(&anna, "belso-utak", "Reggeli csend").await;
|
|
let offline = |who: &str| {
|
|
let pool = app.pool.clone();
|
|
let who = who.to_string();
|
|
async move {
|
|
sqlx::query(
|
|
"UPDATE forum.members m SET last_seen_at = now() - interval '10 minutes' \
|
|
FROM users u WHERE u.id = m.user_id AND u.email = $1",
|
|
)
|
|
.bind(who)
|
|
.execute(&pool)
|
|
.await
|
|
.unwrap();
|
|
}
|
|
};
|
|
let mails = |template: &str| {
|
|
let pool = app.pool.clone();
|
|
let template = template.to_string();
|
|
async move {
|
|
sqlx::query_as::<_, (String, Value)>(
|
|
"SELECT to_email, payload FROM email_outbox WHERE template = $1 ORDER BY created_at",
|
|
)
|
|
.bind(template)
|
|
.fetch_all(&pool)
|
|
.await
|
|
.unwrap()
|
|
}
|
|
};
|
|
|
|
// Online: no e-mail (the badge is enough).
|
|
app.reply(&bea, thread, "Én hajnalban ülök le.", None).await;
|
|
assert!(mails("forum_reply").await.is_empty());
|
|
// Away: one e-mail, then no more for this thread within the hour.
|
|
offline("anna@example.com").await;
|
|
let post = app.reply(&bea, thread, "Négyig be, hatig ki :)", None).await;
|
|
app.reply(&cili, thread, "Gyertyát gyújtok.", None).await;
|
|
let sent = mails("forum_reply").await;
|
|
assert_eq!(sent.len(), 1);
|
|
assert_eq!(sent[0].0, "anna@example.com");
|
|
assert_eq!(sent[0].1["author"], "Holdfény");
|
|
assert_eq!(sent[0].1["nickname"], "Csendesvíz");
|
|
assert_eq!(sent[0].1["excerpt"], "Négyig be, hatig ki 🙂");
|
|
assert_eq!(sent[0].1["url"], format!("https://sorsfonalak.test/forum/szal/{thread}-reggeli-csend#h{}", post["id"]));
|
|
// Bea answered under her own post too, but asked only for the daily digest.
|
|
offline("bea@example.com").await;
|
|
app.reply(&cili, thread, "Szép gondolat.", post["id"].as_i64()).await;
|
|
assert!(mails("forum_reply").await.iter().all(|(to, _)| to != "bea@example.com"));
|
|
|
|
// A request to Bea (instant messages by default), while she is away.
|
|
app.season(&anna, 5, 10).await;
|
|
offline("bea@example.com").await;
|
|
let (status, _) = app
|
|
.call(
|
|
"POST",
|
|
"/v1/forum/conversations",
|
|
Some(&anna),
|
|
json!({ "to": "Holdfény", "intro": "Szia, beszélgetnénk?" }),
|
|
)
|
|
.await;
|
|
assert_eq!(status, StatusCode::CREATED);
|
|
let sent = mails("forum_message").await;
|
|
assert_eq!((sent.len(), sent[0].0.as_str()), (1, "bea@example.com"));
|
|
assert_eq!(sent[0].1["kind"], "request");
|
|
assert_eq!(sent[0].1["excerpt"], "Szia, beszélgetnénk?");
|
|
|
|
// One click turns every forum e-mail off.
|
|
let token: String = sqlx::query_scalar("SELECT email_token FROM forum.members WHERE user_id = $1")
|
|
.bind(anna.id)
|
|
.fetch_one(&app.pool)
|
|
.await
|
|
.unwrap();
|
|
assert!(
|
|
sent[0].1["unsubscribe_post_url"]
|
|
.as_str()
|
|
.unwrap()
|
|
.starts_with("https://sorsfonalak.test/api/v1/forum/unsubscribe?token=")
|
|
);
|
|
let (status, _) = app.call("POST", "/v1/forum/unsubscribe?token=nope", None, Value::Null).await;
|
|
assert_eq!(status, StatusCode::NOT_FOUND);
|
|
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"}));
|
|
}
|
|
|
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
|
async fn live_doorbell_over_websocket(pool: PgPool) {
|
|
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
|
|
|
let state = Arc::new(AppState {
|
|
db: pool.clone(),
|
|
flood_secs: 0,
|
|
base_url: "https://sorsfonalak.test".into(),
|
|
hub: crate::live::Hub::default(),
|
|
});
|
|
tokio::spawn(crate::live::listen(pool.clone(), state.hub.clone()));
|
|
let router = routes::router(state.clone());
|
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
|
let addr = listener.local_addr().unwrap();
|
|
let served = router.clone();
|
|
tokio::spawn(async move { axum::serve(listener, served).await.unwrap() });
|
|
let app = TestApp { router, pool };
|
|
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
|
|
let bea = app.member("bea@example.com", "Holdfény", &["user"]).await;
|
|
let thread = app.thread(&anna, "belso-utak", "Reggeli csend").await;
|
|
// Give the database listener a moment to start.
|
|
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
|
|
|
|
let request = |token: &str, origin: Option<&str>| {
|
|
let mut req = format!("ws://{addr}/v1/forum/ws").into_client_request().unwrap();
|
|
req.headers_mut().insert("authorization", format!("Bearer {token}").parse().unwrap());
|
|
if let Some(o) = origin {
|
|
req.headers_mut().insert("origin", o.parse().unwrap());
|
|
}
|
|
req
|
|
};
|
|
// Another site may not open it with the visitor's credentials.
|
|
let refused = tokio_tungstenite::connect_async(request(&anna.token, Some("https://evil.example"))).await;
|
|
assert!(refused.is_err());
|
|
let (mut ws, _) =
|
|
tokio_tungstenite::connect_async(request(&anna.token, Some("https://sorsfonalak.test"))).await.unwrap();
|
|
|
|
// Bea replies in Anna's thread: Anna hears of the thread and of her menu.
|
|
app.reply(&bea, thread, "Én hajnalban ülök le.", None).await;
|
|
let mut heard = Vec::new();
|
|
while heard.len() < 2 {
|
|
let next = tokio::time::timeout(std::time::Duration::from_secs(5), futures_next(&mut ws)).await;
|
|
match next {
|
|
Ok(Some(text)) => heard.push(text),
|
|
_ => break,
|
|
}
|
|
}
|
|
assert_eq!(heard, vec![format!(r#"{{"id":{thread},"t":"thread"}}"#), r#"{"t":"nav"}"#.to_string()]);
|
|
|
|
// Anna types in the thread: Bea, there too, sees it; Anna does not hear of herself.
|
|
use futures_util::SinkExt;
|
|
let (mut bea_ws, _) =
|
|
tokio_tungstenite::connect_async(request(&bea.token, Some("https://sorsfonalak.test"))).await.unwrap();
|
|
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
|
|
let typing = format!(r#"{{"typing":"thread","id":{thread}}}"#);
|
|
ws.send(tokio_tungstenite::tungstenite::Message::Text(typing.into())).await.unwrap();
|
|
let seen = tokio::time::timeout(std::time::Duration::from_secs(5), futures_next(&mut bea_ws)).await.unwrap();
|
|
assert_eq!(seen, Some(format!(r#"{{"id":{thread},"kind":"thread","t":"typing","who":"Csendesvíz"}}"#)));
|
|
let echo = tokio::time::timeout(std::time::Duration::from_millis(500), futures_next(&mut ws)).await;
|
|
assert!(echo.is_err(), "no echo of one's own typing");
|
|
}
|
|
|
|
/// The next text message of a test WebSocket.
|
|
async fn futures_next(
|
|
ws: &mut tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>,
|
|
) -> Option<String> {
|
|
use futures_util::StreamExt;
|
|
use tokio_tungstenite::tungstenite::Message;
|
|
loop {
|
|
match ws.next().await? {
|
|
Ok(Message::Text(t)) => return Some(t.to_string()),
|
|
Ok(_) => continue,
|
|
Err(_) => return None,
|
|
}
|
|
}
|
|
}
|