Forum: e-mail notifications with a daily digest
Members choose per kind: replies to them (daily digest, instant or off), new posts in followed threads (daily or off), private messages and requests (instant or off). The forum service queues the instant e-mails (none while online, at most one per thread an hour); the worker's new forum task makes the evening digest of what is unread. Every forum e-mail greets by the nickname and has a one-click unsubscribe (RFC 8058). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -35,10 +35,13 @@ pub struct Member {
|
||||
pub nickname_changed_at: OffsetDateTime,
|
||||
pub banned_until: Option<OffsetDateTime>,
|
||||
pub ban_reason: Option<String>,
|
||||
pub email_replies: String,
|
||||
pub email_followed: String,
|
||||
pub email_messages: String,
|
||||
}
|
||||
|
||||
pub const MEMBER_COLUMNS: &str = "user_id, nickname, avatar, bio, chart_share, invisible, points, post_count, \
|
||||
created_at, nickname_changed_at, banned_until, ban_reason";
|
||||
created_at, nickname_changed_at, banned_until, ban_reason, email_replies, email_followed, email_messages";
|
||||
|
||||
impl Member {
|
||||
pub fn rank(&self, now: OffsetDateTime) -> Rank {
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
//! Instant forum e-mails (a reply to the member, a private message or a
|
||||
//! request), queued in `email_outbox` for the worker to send. The daily
|
||||
//! digest is the worker's own job (its `forum` task).
|
||||
//!
|
||||
//! Nobody gets an instant e-mail while online (they see the badge), and at
|
||||
//! most one per thread an hour, one per conversation in half an hour. A
|
||||
//! failure here is logged and never fails the post itself.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::AppState;
|
||||
use crate::text;
|
||||
|
||||
/// The one-click unsubscribe links of a member's forum e-mails.
|
||||
fn unsubscribe_links(base: &str, token: &str) -> (String, String) {
|
||||
(format!("{base}/forum/leiratkozas?token={token}"), format!("{base}/api/v1/forum/unsubscribe?token={token}"))
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct Recipient {
|
||||
user_id: Uuid,
|
||||
email: String,
|
||||
locale: String,
|
||||
nickname: String,
|
||||
email_token: String,
|
||||
}
|
||||
|
||||
async fn queue(db: &PgPool, base: &str, to: &Recipient, template: &str, mut payload: Value) -> Result<(), sqlx::Error> {
|
||||
let (unsubscribe_url, unsubscribe_post_url) = unsubscribe_links(base, &to.email_token);
|
||||
payload["nickname"] = json!(to.nickname);
|
||||
payload["unsubscribe_url"] = json!(unsubscribe_url);
|
||||
payload["unsubscribe_post_url"] = json!(unsubscribe_post_url);
|
||||
sqlx::query(
|
||||
"INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload) VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(to.user_id)
|
||||
.bind(&to.email)
|
||||
.bind(template)
|
||||
.bind(&to.locale)
|
||||
.bind(payload)
|
||||
.execute(db)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Not online now (the last request more than five minutes ago).
|
||||
const OFFLINE: &str = "(m.last_seen_at IS NULL OR m.last_seen_at < now() - interval '5 minutes')";
|
||||
|
||||
/// A reply: to the thread's author and to the author of the post answered,
|
||||
/// if they asked for instant e-mails.
|
||||
pub async fn after_reply(
|
||||
state: &AppState,
|
||||
thread_id: i64,
|
||||
post_id: i64,
|
||||
replier: Uuid,
|
||||
parent: Option<i64>,
|
||||
body: &str,
|
||||
) {
|
||||
if let Err(e) = reply_mails(state, thread_id, post_id, replier, parent, body).await {
|
||||
tracing::error!(error = %e, thread = thread_id, "queueing the reply e-mails");
|
||||
}
|
||||
}
|
||||
|
||||
async fn reply_mails(
|
||||
state: &AppState,
|
||||
thread_id: i64,
|
||||
post_id: i64,
|
||||
replier: Uuid,
|
||||
parent: Option<i64>,
|
||||
body: &str,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
let recipients: Vec<Recipient> = sqlx::query_as(&format!(
|
||||
"SELECT m.user_id, u.email, u.locale, m.nickname, m.email_token \
|
||||
FROM forum.members m JOIN users u ON u.id = m.user_id \
|
||||
WHERE m.email_replies = 'instant' AND m.user_id <> $1 AND {OFFLINE} \
|
||||
AND m.user_id IN (SELECT author_id FROM forum.threads WHERE id = $2 \
|
||||
UNION SELECT author_id FROM forum.posts WHERE id = $3) \
|
||||
AND NOT EXISTS (SELECT 1 FROM email_outbox e \
|
||||
WHERE e.user_id = m.user_id AND e.template = 'forum_reply' \
|
||||
AND e.payload->>'thread_id' = $2::text AND e.created_at > now() - interval '1 hour')"
|
||||
))
|
||||
.bind(replier)
|
||||
.bind(thread_id)
|
||||
.bind(parent)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
if recipients.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let (title, author): (String, Option<String>) = sqlx::query_as(
|
||||
"SELECT th.title, (SELECT nickname FROM forum.members WHERE user_id = $2) \
|
||||
FROM forum.threads th WHERE th.id = $1",
|
||||
)
|
||||
.bind(thread_id)
|
||||
.bind(replier)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
let url = format!("{}/forum/szal/{thread_id}-{}#h{post_id}", state.base_url, text::slug(&title));
|
||||
for to in &recipients {
|
||||
let payload = json!({
|
||||
"url": url,
|
||||
"author": author,
|
||||
"thread_title": title,
|
||||
"thread_id": thread_id.to_string(),
|
||||
"excerpt": body.chars().take(300).collect::<String>(),
|
||||
});
|
||||
queue(&state.db, &state.base_url, to, "forum_reply", payload).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A private message or a request: to the other member, if they asked for it.
|
||||
pub async fn after_message(state: &AppState, conversation: i64, sender: Uuid, request: bool, intro: Option<&str>) {
|
||||
if let Err(e) = message_mail(state, conversation, sender, request, intro).await {
|
||||
tracing::error!(error = %e, conversation, "queueing the message e-mail");
|
||||
}
|
||||
}
|
||||
|
||||
async fn message_mail(
|
||||
state: &AppState,
|
||||
conversation: i64,
|
||||
sender: Uuid,
|
||||
request: bool,
|
||||
intro: Option<&str>,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
let to: Option<Recipient> = sqlx::query_as(&format!(
|
||||
"SELECT m.user_id, u.email, u.locale, m.nickname, m.email_token \
|
||||
FROM forum.conversations c \
|
||||
JOIN forum.members m ON m.user_id = CASE WHEN c.user_a = $2 THEN c.user_b ELSE c.user_a END \
|
||||
JOIN users u ON u.id = m.user_id \
|
||||
WHERE c.id = $1 AND m.email_messages = 'instant' AND {OFFLINE} \
|
||||
AND NOT EXISTS (SELECT 1 FROM email_outbox e \
|
||||
WHERE e.user_id = m.user_id AND e.template = 'forum_message' \
|
||||
AND e.payload->>'conversation_id' = $1::text \
|
||||
AND e.created_at > now() - interval '30 minutes')"
|
||||
))
|
||||
.bind(conversation)
|
||||
.bind(sender)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let Some(to) = to else { return Ok(()) };
|
||||
let from: Option<String> = sqlx::query_scalar("SELECT nickname FROM forum.members WHERE user_id = $1")
|
||||
.bind(sender)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let payload = json!({
|
||||
"url": format!("{}/forum/uzenetek/{conversation}", state.base_url),
|
||||
"from": from,
|
||||
"kind": if request { "request" } else { "message" },
|
||||
"excerpt": intro,
|
||||
"conversation_id": conversation.to_string(),
|
||||
});
|
||||
queue(&state.db, &state.base_url, &to, "forum_message", payload).await
|
||||
}
|
||||
@@ -5,13 +5,15 @@
|
||||
//! the database and the login: a session of the backend (`sf_session` cookie
|
||||
//! or `Authorization: Bearer`) is valid here too.
|
||||
//!
|
||||
//! Configuration: `DATABASE_URL`; `BIND_ADDR` (default `0.0.0.0:8083`),
|
||||
//! Configuration: `DATABASE_URL`, `PUBLIC_BASE_URL` (the site, for e-mail
|
||||
//! links; default `http://localhost:3001`); `BIND_ADDR` (default `0.0.0.0:8083`),
|
||||
//! `LOG_FORMAT`, `RUST_LOG`, `LOG_DIR`. Database migrations run at startup.
|
||||
//!
|
||||
//! `forum healthcheck` performs a local health check (for Docker).
|
||||
|
||||
mod auth;
|
||||
mod error;
|
||||
mod mail;
|
||||
mod rank;
|
||||
mod routes;
|
||||
#[cfg(test)]
|
||||
@@ -29,11 +31,13 @@ pub struct AppState {
|
||||
pub db: PgPool,
|
||||
/// Seconds a member waits between two posts (0 in the tests).
|
||||
pub flood_secs: i32,
|
||||
/// The site's address, for the links in e-mails (`PUBLIC_BASE_URL`).
|
||||
pub base_url: String,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new(db: PgPool) -> Self {
|
||||
Self { db, flood_secs: 5 }
|
||||
pub fn new(db: PgPool, base_url: String) -> Self {
|
||||
Self { db, flood_secs: 5, base_url: base_url.trim_end_matches('/').to_string() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,7 +51,8 @@ async fn main() -> anyhow::Result<()> {
|
||||
let url = std::env::var("DATABASE_URL").context("DATABASE_URL is not set")?;
|
||||
let pool = db::connect(&url).await.context("connecting to the database")?;
|
||||
db::migrate(&pool).await.context("running database migrations")?;
|
||||
let app = routes::router(Arc::new(AppState::new(pool)));
|
||||
let base_url = std::env::var("PUBLIC_BASE_URL").unwrap_or_else(|_| "http://localhost:3001".into());
|
||||
let app = routes::router(Arc::new(AppState::new(pool, base_url)));
|
||||
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
|
||||
tracing::info!(%addr, "listening");
|
||||
axum::serve(listener, app).with_graceful_shutdown(service_kit::shutdown_signal()).await?;
|
||||
|
||||
@@ -48,6 +48,11 @@ pub async fn me(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||
if u.year() >= 9999 { "infinity".to_string() } else { rfc3339(u) }
|
||||
}),
|
||||
"ban_reason": m.ban_reason.as_ref().filter(|_| m.banned(now)),
|
||||
"email": {
|
||||
"replies": m.email_replies,
|
||||
"followed": m.email_followed,
|
||||
"messages": m.email_messages,
|
||||
},
|
||||
})
|
||||
});
|
||||
let signs = shared_signs(&state.db, &[user.id]).await?.remove(&user.id);
|
||||
@@ -66,6 +71,27 @@ pub struct SaveMe {
|
||||
chart_share: Option<String>,
|
||||
#[serde(default)]
|
||||
invisible: Option<bool>,
|
||||
/// E-mail notifications: `{"replies": "off|daily|instant", "followed": "off|daily", "messages": "off|instant"}`.
|
||||
#[serde(default)]
|
||||
email: Option<EmailSettings>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct EmailSettings {
|
||||
#[serde(default)]
|
||||
replies: Option<String>,
|
||||
#[serde(default)]
|
||||
followed: Option<String>,
|
||||
#[serde(default)]
|
||||
messages: Option<String>,
|
||||
}
|
||||
|
||||
fn one_of(value: Option<&str>, allowed: &[&str]) -> ApiResult<Option<String>> {
|
||||
match value {
|
||||
None => Ok(None),
|
||||
Some(v) if allowed.contains(&v) => Ok(Some(v.to_string())),
|
||||
Some(_) => Err(ApiError::bad("Ismeretlen értesítési beállítás.")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether someone else has (or recently had) this folded nickname.
|
||||
@@ -101,6 +127,10 @@ pub async fn save_me(
|
||||
Some(level @ ("none" | "sun" | "big3" | "planets")) => Some(level.to_string()),
|
||||
Some(_) => return Err(ApiError::bad("Ismeretlen megosztási szint.")),
|
||||
};
|
||||
let email = req.email.as_ref();
|
||||
let email_replies = one_of(email.and_then(|e| e.replies.as_deref()), &["off", "daily", "instant"])?;
|
||||
let email_followed = one_of(email.and_then(|e| e.followed.as_deref()), &["off", "daily"])?;
|
||||
let email_messages = one_of(email.and_then(|e| e.messages.as_deref()), &["off", "instant"])?;
|
||||
if nickname_taken(&state.db, &key, user.id).await? {
|
||||
return Err(taken());
|
||||
}
|
||||
@@ -175,6 +205,17 @@ pub async fn save_me(
|
||||
Err(sqlx::Error::Database(e)) if e.is_unique_violation() => return Err(taken()),
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
sqlx::query(
|
||||
"UPDATE forum.members SET email_replies = COALESCE($2, email_replies), \
|
||||
email_followed = COALESCE($3, email_followed), email_messages = COALESCE($4, email_messages) \
|
||||
WHERE user_id = $1",
|
||||
)
|
||||
.bind(user.id)
|
||||
.bind(email_replies)
|
||||
.bind(email_followed)
|
||||
.bind(email_messages)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
let viewer = Viewer { member: auth::load_member(&state.db, user.id).await?, ..viewer };
|
||||
me(State(state), viewer).await
|
||||
@@ -202,6 +243,30 @@ pub async fn nickname_check(
|
||||
Ok(Json(json!({ "ok": true, "nickname": nickname })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct TokenQuery {
|
||||
token: String,
|
||||
}
|
||||
|
||||
/// One click from a forum e-mail (its footer link, or the mail client's
|
||||
/// unsubscribe button, RFC 8058): every forum e-mail off, no login needed.
|
||||
pub async fn unsubscribe(
|
||||
State(state): St,
|
||||
WithRejection(Query(q), _): WithRejection<Query<TokenQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let done = sqlx::query(
|
||||
"UPDATE forum.members SET email_replies = 'off', email_followed = 'off', email_messages = 'off' \
|
||||
WHERE email_token = $1",
|
||||
)
|
||||
.bind(q.token.trim())
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
if done.rows_affected() == 0 {
|
||||
return Err(ApiError::NotFound("token"));
|
||||
}
|
||||
Ok(Json(json!({ "unsubscribed": true })))
|
||||
}
|
||||
|
||||
/// The page is open: keeps the online dot (the viewer extractor does the work).
|
||||
pub async fn presence(_viewer: Viewer) -> StatusCode {
|
||||
StatusCode::NO_CONTENT
|
||||
|
||||
@@ -224,6 +224,7 @@ pub async fn request(
|
||||
}
|
||||
};
|
||||
tx.commit().await?;
|
||||
crate::mail::after_message(&state, id, me.user_id, true, Some(&intro)).await;
|
||||
Ok((StatusCode::CREATED, Json(json!({ "id": id }))))
|
||||
}
|
||||
|
||||
@@ -461,6 +462,7 @@ pub async fn send(
|
||||
.await?;
|
||||
mark(&mut *tx, id, me, message_id).await?;
|
||||
tx.commit().await?;
|
||||
crate::mail::after_message(&state, id, me, false, None).await;
|
||||
Ok((
|
||||
StatusCode::CREATED,
|
||||
Json(json!({ "id": message_id, "mine": true, "body": body, "created_at": rfc3339(created_at) })),
|
||||
|
||||
@@ -65,6 +65,7 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.route("/v1/forum/me", get(members::me).put(members::save_me))
|
||||
.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/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))
|
||||
|
||||
@@ -420,6 +420,7 @@ pub async fn reply(
|
||||
.await?;
|
||||
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;
|
||||
let post = posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0);
|
||||
Ok((StatusCode::CREATED, Json(post)))
|
||||
}
|
||||
|
||||
+112
-1
@@ -30,7 +30,7 @@ struct User {
|
||||
|
||||
impl TestApp {
|
||||
fn new(pool: PgPool) -> Self {
|
||||
let state = AppState { db: pool.clone(), flood_secs: 0 };
|
||||
let state = AppState { db: pool.clone(), flood_secs: 0, base_url: "https://sorsfonalak.test".into() };
|
||||
Self { router: routes::router(Arc::new(state)), pool }
|
||||
}
|
||||
|
||||
@@ -704,3 +704,114 @@ async fn private_messages_start_with_a_request(pool: PgPool) {
|
||||
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"}));
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import { useEffect, useState } from "react";
|
||||
import { AVATAR_COLOURS, AVATAR_GLYPHS, Avatar, GLYPH_NAMES } from "@/components/forum/Avatar";
|
||||
import { signsText } from "@/components/forum/AuthorLine";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { type ChartShare, type ForumMe, banText, memberHref } from "@/lib/forum";
|
||||
import { type ChartShare, type EmailSettings, type ForumMe, banText, memberHref } from "@/lib/forum";
|
||||
|
||||
const SHARE_LEVELS: { value: ChartShare; label: string }[] = [
|
||||
{ value: "none", label: "Semmit" },
|
||||
@@ -24,6 +24,9 @@ export function ProfileForm({ me, back }: { me: ForumMe; back: string | null })
|
||||
const [bio, setBio] = useState(member?.bio ?? "");
|
||||
const [share, setShare] = useState<ChartShare>(member?.chart_share ?? "none");
|
||||
const [invisible, setInvisible] = useState(member?.invisible ?? false);
|
||||
const [email, setEmail] = useState<EmailSettings>(
|
||||
member?.email ?? { replies: "daily", followed: "off", messages: "instant" },
|
||||
);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [saved, setSaved] = useState(false);
|
||||
@@ -51,7 +54,7 @@ export function ProfileForm({ me, back }: { me: ForumMe; back: string | null })
|
||||
try {
|
||||
const res = await api<ForumMe>("/forum/me", {
|
||||
method: "PUT",
|
||||
body: { nickname, avatar: avatar || null, bio, chart_share: share, invisible },
|
||||
body: { nickname, avatar: avatar || null, bio, chart_share: share, invisible, email },
|
||||
});
|
||||
if (back) {
|
||||
router.push(back);
|
||||
@@ -179,6 +182,47 @@ export function ProfileForm({ me, back }: { me: ForumMe; back: string | null })
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<fieldset className="fnew-set">
|
||||
<legend>Értesítések e-mailben</legend>
|
||||
<div className="fprof-mail">
|
||||
<label htmlFor="fprof-mail-replies">Ha valaki válaszol nekem (a szálamban vagy a hozzászólásomra)</label>
|
||||
<select
|
||||
id="fprof-mail-replies"
|
||||
className="inp"
|
||||
value={email.replies}
|
||||
onChange={(e) => setEmail({ ...email, replies: e.target.value as EmailSettings["replies"] })}
|
||||
>
|
||||
<option value="daily">Napi összesítőben, este</option>
|
||||
<option value="instant">Azonnal (szálanként óránként legfeljebb egy levél)</option>
|
||||
<option value="off">Ne küldjetek</option>
|
||||
</select>
|
||||
<label htmlFor="fprof-mail-followed">Új hozzászólás a követett szálaimban</label>
|
||||
<select
|
||||
id="fprof-mail-followed"
|
||||
className="inp"
|
||||
value={email.followed}
|
||||
onChange={(e) => setEmail({ ...email, followed: e.target.value as EmailSettings["followed"] })}
|
||||
>
|
||||
<option value="off">Ne küldjetek</option>
|
||||
<option value="daily">Napi összesítőben, este</option>
|
||||
</select>
|
||||
<label htmlFor="fprof-mail-messages">Privát üzenet vagy beszélgetési kérés</label>
|
||||
<select
|
||||
id="fprof-mail-messages"
|
||||
className="inp"
|
||||
value={email.messages}
|
||||
onChange={(e) => setEmail({ ...email, messages: e.target.value as EmailSettings["messages"] })}
|
||||
>
|
||||
<option value="instant">Azonnal</option>
|
||||
<option value="off">Ne küldjetek</option>
|
||||
</select>
|
||||
</div>
|
||||
<span className="hint">
|
||||
Ha éppen itt vagy a fórumon, nem küldünk levelet: a menü jelzi az újdonságot. A privát üzenetek szövege nem
|
||||
kerül bele a levélbe.
|
||||
</span>
|
||||
</fieldset>
|
||||
|
||||
{member && (
|
||||
<div className="fprof-rank">
|
||||
<span className="eyebrow">Rangod</span>
|
||||
|
||||
@@ -498,3 +498,8 @@ body:has(.forum[data-theme="light"]) .site-footer { background: #0d1220; }
|
||||
.fchat-msg .frep { width: min(420px, 86vw); }
|
||||
.fchat-compose { display: flex; flex-direction: column; gap: 6px; padding-top: 12px; border-top: 1px solid var(--line); }
|
||||
@media (min-width: 760px) { .forum-nav .fn-item { padding: 0 12px; } }
|
||||
|
||||
/* --- e-mail settings --- */
|
||||
.fprof-mail { display: grid; gap: 6px; }
|
||||
.fprof-mail label { font-size: 14px; font-weight: 500; margin-top: 8px; }
|
||||
.fprof-mail label:first-child { margin-top: 0; }
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
|
||||
export function ForumUnsubscribe({ token }: { token: string | null }) {
|
||||
const [state, setState] = useState<"idle" | "busy" | "done">("idle");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
if (!token)
|
||||
return <p className="msg msg-error">Hiányzik a leiratkozó link vége. Nyisd meg újra a levélben lévő linket.</p>;
|
||||
|
||||
async function unsubscribe() {
|
||||
setState("busy");
|
||||
setError(null);
|
||||
try {
|
||||
await api(`/forum/unsubscribe?token=${encodeURIComponent(token ?? "")}`, { method: "POST" });
|
||||
setState("done");
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
setState("idle");
|
||||
}
|
||||
}
|
||||
|
||||
if (state === "done") {
|
||||
return (
|
||||
<p className="fh-banner">
|
||||
<span>
|
||||
Kész, a fórum nem küld több levelet. Ha meggondolod magad, a{" "}
|
||||
<Link href="/forum/beallitasok">fórumprofilodnál</Link> újra bekapcsolhatod.
|
||||
</span>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<button type="button" className="btn btn-primary" disabled={state === "busy"} onClick={unsubscribe}>
|
||||
{state === "busy" ? "Leiratkozás…" : "Leiratkozom a fórum leveleiről"}
|
||||
</button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { ForumUnsubscribe } from "./ForumUnsubscribe";
|
||||
|
||||
export const metadata = { title: "Leiratkozás a fórum leveleiről", robots: { index: false } };
|
||||
|
||||
type Props = { searchParams: Promise<{ token?: string | string[] }> };
|
||||
|
||||
/** From the footer of a forum e-mail: every forum e-mail off, no login needed. */
|
||||
export default async function ForumUnsubscribePage({ searchParams }: Props) {
|
||||
const raw = (await searchParams).token;
|
||||
const token = Array.isArray(raw) ? raw[0] : raw;
|
||||
return (
|
||||
<div className="fh fprof">
|
||||
<h1 className="fpage-title">Leiratkozás</h1>
|
||||
<p className="muted">
|
||||
Nem kérsz több levelet a fórumról: se válaszértesítést, se napi összesítőt, se üzenetértesítést.
|
||||
</p>
|
||||
<ForumUnsubscribe token={token ?? null} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -119,6 +119,12 @@ export interface ThreadPage {
|
||||
};
|
||||
}
|
||||
|
||||
export interface EmailSettings {
|
||||
replies: "off" | "daily" | "instant";
|
||||
followed: "off" | "daily";
|
||||
messages: "off" | "instant";
|
||||
}
|
||||
|
||||
export interface ForumMe {
|
||||
viewer: ForumViewer;
|
||||
member: {
|
||||
@@ -136,6 +142,7 @@ export interface ForumMe {
|
||||
nickname_change_after: string | null;
|
||||
banned_until: string | null;
|
||||
ban_reason: string | null;
|
||||
email: EmailSettings;
|
||||
} | null;
|
||||
chart: Record<Exclude<ChartShare, "none">, Record<string, string> | null> | null;
|
||||
}
|
||||
|
||||
@@ -16,13 +16,17 @@ pub struct Tasks {
|
||||
pub analyses: bool,
|
||||
/// Issuing the invoices of the payments in Billingo.
|
||||
pub invoices: bool,
|
||||
/// Telegram notices about purchases.
|
||||
/// Telegram notices about purchases and forum reports.
|
||||
pub notify: bool,
|
||||
/// The forum's daily e-mail digest.
|
||||
pub forum: bool,
|
||||
}
|
||||
|
||||
impl Tasks {
|
||||
pub const ALL: Tasks = Tasks { email: true, cleanup: true, analyses: true, invoices: true, notify: true };
|
||||
const NONE: Tasks = Tasks { email: false, cleanup: false, analyses: false, invoices: false, notify: false };
|
||||
pub const ALL: Tasks =
|
||||
Tasks { email: true, cleanup: true, analyses: true, invoices: true, notify: true, forum: true };
|
||||
const NONE: Tasks =
|
||||
Tasks { email: false, cleanup: false, analyses: false, invoices: false, notify: false, forum: false };
|
||||
|
||||
pub fn parse(raw: &str) -> anyhow::Result<Self> {
|
||||
let mut tasks = Self::NONE;
|
||||
@@ -33,8 +37,11 @@ impl Tasks {
|
||||
"analyses" => tasks.analyses = true,
|
||||
"invoices" => tasks.invoices = true,
|
||||
"notify" => tasks.notify = true,
|
||||
"forum" => tasks.forum = true,
|
||||
other => {
|
||||
anyhow::bail!("unknown task '{other}' in WORKER_TASKS (email, cleanup, analyses, invoices, notify)")
|
||||
anyhow::bail!(
|
||||
"unknown task '{other}' in WORKER_TASKS (email, cleanup, analyses, invoices, notify, forum)"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
//! 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.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::json;
|
||||
use sqlx::PgPool;
|
||||
use tokio::sync::watch;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Members handled in one round.
|
||||
const BATCH: i64 = 200;
|
||||
/// Threads listed in one digest.
|
||||
const MAX_THREADS: i64 = 10;
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct Due {
|
||||
user_id: Uuid,
|
||||
email: String,
|
||||
locale: String,
|
||||
nickname: String,
|
||||
email_token: String,
|
||||
replies: bool,
|
||||
followed: bool,
|
||||
since: time::OffsetDateTime,
|
||||
}
|
||||
|
||||
/// The evening window, by Hungarian time.
|
||||
async fn evening(db: &PgPool) -> Result<bool, sqlx::Error> {
|
||||
let hour: i32 =
|
||||
sqlx::query_scalar("SELECT extract(hour FROM now() AT TIME ZONE 'Europe/Budapest')::int").fetch_one(db).await?;
|
||||
Ok((18..22).contains(&hour))
|
||||
}
|
||||
|
||||
/// Makes the digests that are due; returns how many e-mails were queued.
|
||||
/// `any_time`: also outside the evening window (tests).
|
||||
pub async fn run_once(db: &PgPool, base_url: &str, any_time: bool) -> Result<usize, sqlx::Error> {
|
||||
if !any_time && !evening(db).await? {
|
||||
return Ok(0);
|
||||
}
|
||||
let base = base_url.trim_end_matches('/');
|
||||
let mut tx = db.begin().await?;
|
||||
let due: Vec<Due> = sqlx::query_as(
|
||||
"SELECT m.user_id, u.email, u.locale, m.nickname, m.email_token, \
|
||||
m.email_replies = 'daily' AS replies, m.email_followed = 'daily' AS followed, \
|
||||
greatest(COALESCE(m.digest_sent_at, m.created_at), now() - interval '2 days') AS since \
|
||||
FROM forum.members m JOIN users u ON u.id = m.user_id \
|
||||
WHERE (m.email_replies = 'daily' OR m.email_followed = 'daily') \
|
||||
AND (m.digest_sent_at IS NULL OR m.digest_sent_at < now() - interval '20 hours') \
|
||||
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 m in due {
|
||||
let threads: Vec<(String, i64)> = sqlx::query_as(
|
||||
"SELECT th.title, count(*) FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id \
|
||||
WHERE p.deleted_at IS NULL AND th.deleted_at IS NULL AND p.author_id IS DISTINCT FROM $1 \
|
||||
AND p.created_at > $2 \
|
||||
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) \
|
||||
AND (($3 AND (th.author_id = $1 \
|
||||
OR p.parent_id IN (SELECT id FROM forum.posts WHERE author_id = $1))) \
|
||||
OR ($4 AND th.id IN (SELECT thread_id FROM forum.follows WHERE user_id = $1))) \
|
||||
GROUP BY th.id, th.title ORDER BY max(p.id) DESC LIMIT $5",
|
||||
)
|
||||
.bind(m.user_id)
|
||||
.bind(m.since)
|
||||
.bind(m.replies)
|
||||
.bind(m.followed)
|
||||
.bind(MAX_THREADS)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
if !threads.is_empty() {
|
||||
let total: i64 = threads.iter().map(|(_, n)| n).sum();
|
||||
let lines: Vec<String> =
|
||||
threads.iter().map(|(title, n)| format!("„{title}” – {n} új hozzászólás")).collect();
|
||||
let payload = json!({
|
||||
"url": format!("{base}/forum/kovetett"),
|
||||
"nickname": m.nickname,
|
||||
"lines": lines,
|
||||
"total": total,
|
||||
"unsubscribe_url": format!("{base}/forum/leiratkozas?token={}", m.email_token),
|
||||
"unsubscribe_post_url": format!("{base}/api/v1/forum/unsubscribe?token={}", m.email_token),
|
||||
});
|
||||
sqlx::query(
|
||||
"INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload) \
|
||||
VALUES ($1, $2, $3, 'forum_digest', $4, $5)",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(m.user_id)
|
||||
.bind(&m.email)
|
||||
.bind(&m.locale)
|
||||
.bind(payload)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
queued += 1;
|
||||
}
|
||||
sqlx::query("UPDATE forum.members SET digest_sent_at = now() WHERE user_id = $1")
|
||||
.bind(m.user_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
if queued > 0 {
|
||||
tracing::info!(queued, "forum digests queued");
|
||||
}
|
||||
Ok(queued)
|
||||
}
|
||||
|
||||
pub async fn run(db: PgPool, base_url: String, stop: watch::Receiver<bool>) {
|
||||
loop {
|
||||
if let Err(e) = run_once(&db, &base_url, false).await {
|
||||
tracing::error!(error = %e, "forum digests");
|
||||
}
|
||||
tokio::select! {
|
||||
() = tokio::time::sleep(Duration::from_secs(10 * 60)) => {}
|
||||
() = crate::stopped(stop.clone()) => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
async fn member(db: &PgPool, email: &str, nickname: &str, replies: &str, followed: &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, email_replies, email_followed, created_at) \
|
||||
VALUES ($1, $2, lower($2), 'hold-ejkek', $3, $4, now() - interval '3 days')",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(nickname)
|
||||
.bind(replies)
|
||||
.bind(followed)
|
||||
.execute(db)
|
||||
.await
|
||||
.unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
async fn post(db: &PgPool, thread: i64, author: Uuid, parent: Option<i64>) -> i64 {
|
||||
sqlx::query_scalar(
|
||||
"INSERT INTO forum.posts (thread_id, author_id, parent_id, body) VALUES ($1, $2, $3, 'x') RETURNING id",
|
||||
)
|
||||
.bind(thread)
|
||||
.bind(author)
|
||||
.bind(parent)
|
||||
.fetch_one(db)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn one_digest_a_day_with_what_is_unread(pool: PgPool) {
|
||||
let anna = member(&pool, "anna@example.com", "Anna", "daily", "off").await;
|
||||
let bea = member(&pool, "bea@example.com", "Bea", "off", "daily").await;
|
||||
let cili = member(&pool, "cili@example.com", "Cili", "instant", "off").await;
|
||||
let thread: i64 = sqlx::query_scalar(
|
||||
"INSERT INTO forum.threads (topic_id, author_id, title) VALUES (2, $1, 'Reggeli csend') RETURNING id",
|
||||
)
|
||||
.bind(anna)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
post(&pool, thread, anna, None).await;
|
||||
sqlx::query("INSERT INTO forum.follows (user_id, thread_id) VALUES ($1, $2), ($3, $2)")
|
||||
.bind(anna)
|
||||
.bind(thread)
|
||||
.bind(bea)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
post(&pool, thread, cili, None).await;
|
||||
post(&pool, thread, cili, None).await;
|
||||
|
||||
assert_eq!(run_once(&pool, "https://sorsfonalak.hu/", true).await.unwrap(), 2);
|
||||
let mails: Vec<(String, serde_json::Value)> = sqlx::query_as(
|
||||
"SELECT to_email, payload FROM email_outbox WHERE template = 'forum_digest' ORDER BY to_email",
|
||||
)
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(mails.len(), 2, "Cili asked for instant e-mails, not the digest");
|
||||
assert_eq!(mails[0].0, "anna@example.com");
|
||||
assert_eq!(mails[0].1["lines"][0], "„Reggeli csend” – 2 új hozzászólás");
|
||||
assert_eq!(mails[0].1["url"], "https://sorsfonalak.hu/forum/kovetett");
|
||||
assert!(email_templates::render("forum_digest", "hu", &mails[0].1).is_ok());
|
||||
|
||||
// Once a day only; and nothing unread, nothing sent.
|
||||
post(&pool, thread, cili, None).await;
|
||||
assert_eq!(run_once(&pool, "https://sorsfonalak.hu", true).await.unwrap(), 0);
|
||||
sqlx::query("UPDATE forum.members SET digest_sent_at = now() - interval '1 day'").execute(&pool).await.unwrap();
|
||||
let last: i64 = sqlx::query_scalar("SELECT max(id) FROM forum.posts").fetch_one(&pool).await.unwrap();
|
||||
sqlx::query("INSERT INTO forum.reads (user_id, thread_id, last_post_id) VALUES ($1, $2, $3), ($4, $2, $3)")
|
||||
.bind(anna)
|
||||
.bind(thread)
|
||||
.bind(last)
|
||||
.bind(bea)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(run_once(&pool, "https://sorsfonalak.hu", true).await.unwrap(), 0);
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ mod cleanup;
|
||||
mod compare;
|
||||
mod config;
|
||||
mod email;
|
||||
mod forum_digest;
|
||||
mod invoices;
|
||||
mod notify;
|
||||
mod ses;
|
||||
@@ -105,6 +106,7 @@ async fn main() -> anyhow::Result<()> {
|
||||
analyses = tasks.analyses,
|
||||
invoices = tasks.invoices,
|
||||
notify = tasks.notify,
|
||||
forum = tasks.forum,
|
||||
"worker tasks"
|
||||
);
|
||||
match &config.smtp_url {
|
||||
@@ -167,6 +169,15 @@ async fn main() -> anyhow::Result<()> {
|
||||
_ => tracing::info!("TELEGRAM_BOT_TOKEN or TELEGRAM_CHAT_ID is not set: no purchase notices"),
|
||||
}
|
||||
|
||||
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()));
|
||||
}
|
||||
None => tracing::warn!("PUBLIC_BASE_URL is not set: no forum digests (their links need it)"),
|
||||
}
|
||||
|
||||
let app = Router::new().route("/healthz", get(healthz)).with_state(pool);
|
||||
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
|
||||
tracing::info!(%addr, "worker running");
|
||||
|
||||
@@ -288,11 +288,15 @@ async fn cleanup_removes_only_expired_data(db: PgPool) {
|
||||
fn worker_tasks_are_chosen_by_name() {
|
||||
use crate::config::Tasks;
|
||||
let mail = Tasks::parse("email, cleanup").unwrap();
|
||||
assert_eq!(mail, Tasks { email: true, cleanup: true, analyses: false, invoices: false, notify: false });
|
||||
assert_eq!(
|
||||
mail,
|
||||
Tasks { email: true, cleanup: true, analyses: false, invoices: false, notify: false, forum: false }
|
||||
);
|
||||
assert_eq!(
|
||||
Tasks::parse("analyses").unwrap(),
|
||||
Tasks { email: false, cleanup: false, analyses: true, invoices: false, notify: false }
|
||||
Tasks { email: false, cleanup: false, analyses: true, invoices: false, notify: false, forum: false }
|
||||
);
|
||||
assert!(Tasks::parse("email,forum").unwrap().forum);
|
||||
assert!(Tasks::parse("email,invoices").unwrap().invoices);
|
||||
assert!(Tasks::parse("email,cleanup,invoices,notify").unwrap().notify);
|
||||
assert!(Tasks::parse("emails").is_err());
|
||||
|
||||
Reference in New Issue
Block a user