Every day from 07:00 Chiang Mai time the app mails the journal's last entry number and its hash to the addresses set on the Notifications page (src/anchor.rs, migration 0012: settings, journal_anchors), when anything was added since the last anchor that went out. A day without news is noted without a mail; a failed send is tried again after an hour; a transaction-level advisory lock keeps two runs from both sending. "Send the anchor now" sends at once. Each mail says whether the chain checked whole (in capitals when it did not) and links to /journal/anchor, which compares a kept entry number and hash with the journal now: the same hash, another one, or no such entry. Changing the recipients is itself a journal entry. Every anchor mail is in the notifications log. Tests: the daily rule (before seven, once a day, an hour after a failure), recipients checked and journaled, one mail per recipient with the head hash, unchanged days, by hand, the check page's three answers, and a chain broken around the app said in the mail. 126 unit, 67 integration.
297 lines
8.3 KiB
Rust
297 lines
8.3 KiB
Rust
//! The Notifications page (phase 8): how the app reaches people, a test
|
|
//! mail to see that it does, and the log of what went out.
|
|
|
|
use std::sync::Arc;
|
|
|
|
use axum::extract::{Query, State};
|
|
use axum::http::StatusCode;
|
|
use axum::response::{IntoResponse, Redirect};
|
|
use axum::{Extension, Form};
|
|
use minijinja::context;
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use super::{AppState, Res, page};
|
|
use crate::anchor;
|
|
use crate::config::MailSecurity;
|
|
use crate::dates;
|
|
use crate::forms::Fields;
|
|
use crate::mail::{self, Entry, Outgoing};
|
|
use crate::session::User;
|
|
|
|
#[derive(Debug, Default, Deserialize)]
|
|
pub struct NotificationsQuery {
|
|
/// The log line of a test just sent, to show how it went.
|
|
#[serde(default)]
|
|
sent: Option<i64>,
|
|
/// What "Send the anchor now" did.
|
|
#[serde(default)]
|
|
anchor: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
struct AnchorLine {
|
|
day: String,
|
|
seq: i64,
|
|
hash: String,
|
|
whole: bool,
|
|
status: String,
|
|
recipients: String,
|
|
how: String,
|
|
at: String,
|
|
}
|
|
|
|
/// What the anchor form shows again after a post.
|
|
#[derive(Debug, Default)]
|
|
struct AnchorForm {
|
|
to: Option<String>,
|
|
error: String,
|
|
done: String,
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
struct Line {
|
|
id: i64,
|
|
channel: String,
|
|
purpose: String,
|
|
recipient: String,
|
|
subject: String,
|
|
status: String,
|
|
detail: String,
|
|
actor: String,
|
|
at: String,
|
|
}
|
|
|
|
fn line(l: mail::Logged) -> Line {
|
|
Line {
|
|
id: l.id,
|
|
at: dates::fmt_datetime(l.created_at),
|
|
channel: l.channel,
|
|
purpose: l.purpose,
|
|
recipient: l.recipient,
|
|
subject: l.subject,
|
|
status: l.status,
|
|
detail: l.detail,
|
|
actor: l.actor,
|
|
}
|
|
}
|
|
|
|
/// The mail settings as the page states them, without the password.
|
|
#[derive(Debug, Serialize)]
|
|
struct MailShown {
|
|
from: String,
|
|
server: String,
|
|
security: &'static str,
|
|
reply_to: Option<String>,
|
|
}
|
|
|
|
async fn show(
|
|
st: &AppState,
|
|
user: &User,
|
|
sent: Option<i64>,
|
|
address: &str,
|
|
error: &str,
|
|
af: AnchorForm,
|
|
) -> Res {
|
|
let mail = st.cfg.mail.as_ref().map(|m| MailShown {
|
|
from: m.from.clone(),
|
|
server: format!("{}:{}", m.host, m.port),
|
|
security: match m.security {
|
|
MailSecurity::Tls => "TLS",
|
|
MailSecurity::StartTls => "STARTTLS",
|
|
MailSecurity::None => "no TLS (a test server on this machine)",
|
|
},
|
|
reply_to: m.reply_to.clone(),
|
|
});
|
|
let result = match sent {
|
|
Some(id) => mail::get(&st.db, id).await?.map(line),
|
|
None => None,
|
|
};
|
|
let address = if address.is_empty() {
|
|
mail::last_test_address(&st.db, &user.login)
|
|
.await?
|
|
.unwrap_or_default()
|
|
} else {
|
|
address.to_string()
|
|
};
|
|
let log: Vec<Line> = mail::recent(&st.db, 30)
|
|
.await?
|
|
.into_iter()
|
|
.map(line)
|
|
.collect();
|
|
let status = if error.is_empty() && af.error.is_empty() {
|
|
StatusCode::OK
|
|
} else {
|
|
StatusCode::UNPROCESSABLE_ENTITY
|
|
};
|
|
let anchor_to = match af.to {
|
|
Some(t) => t,
|
|
None => anchor::recipients(&st.db).await?.join(", "),
|
|
};
|
|
let anchors: Vec<AnchorLine> = anchor::recent(&st.db, 7)
|
|
.await?
|
|
.into_iter()
|
|
.map(|a| AnchorLine {
|
|
day: dates::fmt_date(a.day),
|
|
at: dates::fmt_datetime(a.at),
|
|
seq: a.seq,
|
|
hash: a.hash,
|
|
whole: a.whole,
|
|
status: a.status,
|
|
recipients: a.recipients,
|
|
how: a.how,
|
|
})
|
|
.collect();
|
|
Ok(page(
|
|
st,
|
|
user,
|
|
"notifications.html",
|
|
"Notifications",
|
|
"notifications",
|
|
status,
|
|
context! {
|
|
mail, result, address, error, log, anchor_to, anchors,
|
|
anchor_error => af.error,
|
|
anchor_done => af.done,
|
|
anchor_hour => anchor::HOUR,
|
|
},
|
|
))
|
|
}
|
|
|
|
pub async fn notifications(
|
|
State(st): State<Arc<AppState>>,
|
|
Extension(user): Extension<User>,
|
|
Query(q): Query<NotificationsQuery>,
|
|
) -> Res {
|
|
let done = match q.anchor.as_deref() {
|
|
Some("sent") => "The anchor went out. The recipients' copies are in the log below.",
|
|
Some("failed") => "The anchor did not reach every recipient: see the log below.",
|
|
Some("nothing") => "Nothing was sent: the journal is still empty.",
|
|
Some("saved") => "Saved. The change is in the journal.",
|
|
_ => "",
|
|
};
|
|
let af = AnchorForm {
|
|
done: done.to_string(),
|
|
..AnchorForm::default()
|
|
};
|
|
show(&st, &user, q.sent, "", "", af).await
|
|
}
|
|
|
|
/// Saves where the daily anchor goes.
|
|
pub async fn anchor_to(
|
|
State(st): State<Arc<AppState>>,
|
|
Extension(user): Extension<User>,
|
|
Form(f): Form<Fields>,
|
|
) -> Res {
|
|
let raw = crate::forms::get(&f, "anchor_to");
|
|
let to = anchor::split(&raw);
|
|
let bad: Vec<&String> = to.iter().filter(|a| !mail::valid_address(a)).collect();
|
|
if !bad.is_empty() || to.len() > 10 {
|
|
let error = if to.len() > 10 {
|
|
"Ten addresses at most.".to_string()
|
|
} else {
|
|
format!(
|
|
"Not an email address: {}.",
|
|
bad.iter()
|
|
.map(|s| s.as_str())
|
|
.collect::<Vec<_>>()
|
|
.join(", ")
|
|
)
|
|
};
|
|
let af = AnchorForm {
|
|
to: Some(raw.trim().to_string()),
|
|
error,
|
|
..AnchorForm::default()
|
|
};
|
|
return show(&st, &user, None, "", "", af).await;
|
|
}
|
|
anchor::set_recipients(&st.db, &to, &user.login).await?;
|
|
Ok(Redirect::to("/notifications?anchor=saved#anchor").into_response())
|
|
}
|
|
|
|
/// Sends the anchor at once, whatever the day's run did.
|
|
pub async fn anchor_now(State(st): State<Arc<AppState>>, Extension(user): Extension<User>) -> Res {
|
|
let out = anchor::send(&st.cfg, &st.db, false, &user.login, chrono::Utc::now()).await?;
|
|
let said = match out {
|
|
anchor::Outcome::Sent { failed: 0, .. } => "sent",
|
|
anchor::Outcome::Sent { .. } => "failed",
|
|
anchor::Outcome::Unchanged => "sent",
|
|
anchor::Outcome::Nothing("the journal is empty") => "nothing",
|
|
anchor::Outcome::Nothing(why) => {
|
|
let af = AnchorForm {
|
|
error: format!("Nothing was sent: {why}."),
|
|
..AnchorForm::default()
|
|
};
|
|
return show(&st, &user, None, "", "", af).await;
|
|
}
|
|
};
|
|
Ok(Redirect::to(&format!("/notifications?anchor={said}#anchor")).into_response())
|
|
}
|
|
|
|
/// Sends a test mail to the address given, logs how it went and shows it.
|
|
pub async fn test_email(
|
|
State(st): State<Arc<AppState>>,
|
|
Extension(user): Extension<User>,
|
|
Form(f): Form<Fields>,
|
|
) -> Res {
|
|
let to = crate::forms::get(&f, "to").trim().to_string();
|
|
let Some(cfg) = st.cfg.mail.as_ref() else {
|
|
return show(
|
|
&st,
|
|
&user,
|
|
None,
|
|
&to,
|
|
"Mail is not set up on this server.",
|
|
AnchorForm::default(),
|
|
)
|
|
.await;
|
|
};
|
|
if !mail::valid_address(&to) {
|
|
return show(
|
|
&st,
|
|
&user,
|
|
None,
|
|
&to,
|
|
"Enter one email address, such as alex@buildfor.life.",
|
|
AnchorForm::default(),
|
|
)
|
|
.await;
|
|
}
|
|
let subject = "Test from Lanna Desk";
|
|
let text = format!(
|
|
"This is a test of the notifications of Lanna Desk's back office ({url}).\n\n\
|
|
{who} sent it on {at}, Chiang Mai time. If it reached you, mail from the \
|
|
back office reaches this address.\n\n\
|
|
Lanna Desk\n",
|
|
url = st.cfg.public_url,
|
|
who = user.login,
|
|
at = dates::fmt_datetime(chrono::Utc::now()),
|
|
);
|
|
let hello = mail::hello_name(&st.cfg.public_url);
|
|
let result = mail::send(
|
|
cfg,
|
|
&hello,
|
|
&Outgoing {
|
|
to: &to,
|
|
subject,
|
|
text: &text,
|
|
},
|
|
)
|
|
.await;
|
|
if let Err(e) = &result {
|
|
tracing::warn!("test mail to {to} failed: {e:#}");
|
|
}
|
|
let id = mail::log(
|
|
&st.db,
|
|
&Entry {
|
|
channel: "email",
|
|
purpose: "test",
|
|
recipient: &to,
|
|
subject,
|
|
result: &result,
|
|
actor: &user.login,
|
|
},
|
|
)
|
|
.await?;
|
|
Ok(Redirect::to(&format!("/notifications?sent={id}#result")).into_response())
|
|
}
|