//! `/admin/mail`: the state of the SMTP settings, the mail outbox with its states, the retry and abandon //! actions, and a test mail to the administrator's own address. //! //! The outbox never shows a body: the store holds it sealed, and the list selects only the header columns. //! Retrying a failed row sends it again at once; abandoning a row that is not yet sent blanks its body, as //! the worker does when it gives up. use im_core::model::AuditAction; use serde::Deserialize; use serde_json::json; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; use topcoat::router::error::{SeeOther, not_found}; use topcoat::router::{page, route}; use topcoat::view::{View, component, view}; use crate::audit::{Actor, record}; use crate::auth::{require_admin, require_admin_csrf}; use crate::i18n::Lang; use crate::i18n::admin::{A, text}; use crate::mail::{self, Mail, Recipient}; use crate::pages::admin::{ PAGE_SIZE, Tab, action_button, changed, done, error_text, flash_messages, frame_info, notice_text, refused, tabs, }; use crate::pages::path_param; use crate::state::AppState; use crate::views::{ViewerInfo, page_lang, shell}; /// The query of the mail page: the flash codes, the state filter, and the cursor of the next page. #[derive(Deserialize, Default)] struct MailQuery { #[serde(default)] notice: String, #[serde(default)] error: String, /// `pending`, `sent`, `failed` or `abandoned`. Anything else shows every state. #[serde(default)] state: String, /// The id of the last row of the previous page. #[serde(default)] after: String, } /// The form of the mail actions: only the CSRF token. #[derive(Deserialize, Default)] struct CsrfForm { #[serde(default)] csrf: String, } /// The SMTP settings as the page shows them. The password is never shown, only whether a login is set. struct SmtpInfo { host: String, sender: String, login: String, } /// The states the filter links offer. const STATES: [&str; 4] = ["pending", "sent", "failed", "abandoned"]; /// `GET /admin/mail`. #[page("/admin/mail")] async fn mail_page(cx: &Cx, Form(query): Form) -> Result { let viewer = require_admin(cx).await?; let state = app_context::(cx); let (lang, info) = frame_info(cx, &viewer); let filter = STATES .contains(&query.state.as_str()) .then(|| query.state.clone()); let after = (!query.after.is_empty()).then(|| query.after.clone()); let mut rows = state .store .outbox_page(filter.as_deref(), after.as_deref(), PAGE_SIZE + 1) .await?; let next = if rows.len() > PAGE_SIZE as usize { rows.truncate(PAGE_SIZE as usize); rows.last().map(|row| row.id.clone()) } else { None }; let counts = state.store.outbox_counts().await?; let smtp = state.config.smtp.enabled().then(|| SmtpInfo { host: format!("{}:{}", state.config.smtp.host, state.config.smtp.port), sender: format!( "{} <{}>", state.config.smtp.from_name, state.config.smtp.from ), login: if state.config.smtp.username.is_empty() { String::from("-") } else { state.config.smtp.username.clone() }, }); Ok(mail_view( cx, lang, info, viewer.session.csrf_token.clone(), smtp, counts, filter.unwrap_or_default(), rows, next, notice_text(lang, &query.notice).map(str::to_owned), error_text(lang, &query.error).map(str::to_owned), )) } /// `POST /admin/mail/test`: queues a test mail to the administrator's own address. #[route(POST "/admin/mail/test")] async fn send_test(cx: &Cx, Form(form): Form) -> Result { let viewer = require_admin_csrf(cx, &form.csrf).await?; let state = app_context::(cx); let lang = page_lang(cx, Some(&viewer)); let Ok(to) = Recipient::new(Some(&viewer.user.name), &viewer.user.email) else { return Ok(refused("/admin/mail", "email")); }; let mail = Mail::Test { subject: text(lang, A::TestMailSubject), body: text(lang, A::TestMailBody), }; mail::queue(&state.store, &state.key, &to, lang, &mail).await?; record( cx, Actor::User(&viewer.user.id), AuditAction::MailTestQueued, None, json!({}), ) .await; changed(&state.live); Ok(done("/admin/mail", "test-queued")) } /// `POST /admin/mail/{id}/retry`: a failed row is sent again now. #[route(POST "/admin/mail/{id}/retry")] async fn retry_mail(cx: &Cx, Form(form): Form) -> Result { let viewer = require_admin_csrf(cx, &form.csrf).await?; let id = outbox_id(cx)?; let state = app_context::(cx); if !state.store.retry_mail(&id).await? { return Ok(refused("/admin/mail", "mail-retry")); } record( cx, Actor::User(&viewer.user.id), AuditAction::MailRetried, Some(("mail", &id)), json!({}), ) .await; changed(&state.live); Ok(done("/admin/mail", "mail-retried")) } /// `POST /admin/mail/{id}/abandon`: a row that is not yet sent is given up, and its body is removed. #[route(POST "/admin/mail/{id}/abandon")] async fn abandon_mail(cx: &Cx, Form(form): Form) -> Result { let viewer = require_admin_csrf(cx, &form.csrf).await?; let id = outbox_id(cx)?; let state = app_context::(cx); if !state.store.abandon_mail(&id).await? { return Ok(refused("/admin/mail", "mail-abandon")); } record( cx, Actor::User(&viewer.user.id), AuditAction::MailAbandoned, Some(("mail", &id)), json!({}), ) .await; changed(&state.live); Ok(done("/admin/mail", "mail-abandoned")) } /// The outbox id in the path. Ids are ULIDs: 26 letters and digits. Anything else is a 404. fn outbox_id(cx: &Cx) -> Result { match path_param(cx, "id") { Some(id) if id.len() == 26 && id.bytes().all(|b| b.is_ascii_alphanumeric()) => Ok(id), _ => Err(not_found().into()), } } /// The mail page: SMTP status, the state counts, the filter links, the outbox, and the test button. #[allow(clippy::too_many_arguments)] fn mail_view( cx: &Cx, lang: Lang, info: ViewerInfo, csrf: String, smtp: Option, counts: Vec<(String, i64)>, filter: String, rows: Vec, next: Option, success: Option, problem: Option, ) -> impl View { let next_href = next.map(|after| { if filter.is_empty() { format!("/admin/mail?after={after}") } else { format!("/admin/mail?state={filter}&after={after}") } }); view! { cx => shell(title: text(lang, A::MailTitle), lang: lang, viewer: Some(info), tabs(lang: lang, current: Tab::Mail)

(text(lang, A::MailTitle))

(text(lang, A::MailIntro))

flash_messages(success: success, problem: problem)

(text(lang, A::SmtpStatus))

if let Some(smtp) = smtp {
(text(lang, A::SmtpHost))
(smtp.host.clone())
(text(lang, A::SmtpSender))
(smtp.sender.clone())
(text(lang, A::SmtpLogin))
(smtp.login.clone())
} else {

(text(lang, A::SmtpNotConfigured))

} action_button(action: "/admin/mail/test".to_owned(), csrf: csrf.clone(), label: text(lang, A::SendTest), class: "button ghost", on: "")

(text(lang, A::OutboxTitle))

(text(lang, A::OutboxFilter))": " (text(lang, A::AllStates)) for (state, count) in counts { (state_label(lang, &state))" ("(count)")" }

if rows.is_empty() {

(text(lang, A::NoMail))

} else {
    for row in rows { mail_item(lang: lang, csrf: csrf.clone(), row: row) }
} if let Some(href) = next_href {

(text(lang, A::NextPage))

}
) } } /// The text of an outbox state. Unknown states are shown as they are stored. fn state_label(lang: Lang, state: &str) -> String { match state { "pending" => text(lang, A::StatePending).to_owned(), "sent" => text(lang, A::StateSent).to_owned(), "failed" => text(lang, A::StateFailed).to_owned(), "abandoned" => text(lang, A::StateAbandoned).to_owned(), other => other.to_owned(), } } /// One outbox row: its recipient, subject, state, attempts, and the actions the state allows. #[component] async fn mail_item( lang: Lang, csrf: String, row: im_core::store::admin::OutboxRow, ) -> Result { let state = state_label(lang, &row.state); let retry = format!("/admin/mail/{}/retry", row.id); let abandon = format!("/admin/mail/{}/abandon", row.id); let can_retry = row.state == "failed"; let can_abandon = row.state == "pending" || row.state == "failed"; Ok(view! {
  • (row.subject.clone())
    (row.to_addr.clone()) " · "(row.kind.clone()) " · "(state) " · "(text(lang, A::Attempts))": "(row.attempts) " · "(text(lang, A::NextAttempt))": "(row.next_attempt_at.clone()) " · "(text(lang, A::Created))": "(row.created_at.clone())
    if let Some(error) = row.last_error.clone() {
    (text(lang, A::LastError))": "(error)
    }
    if can_retry { action_button(action: retry, csrf: csrf.clone(), label: text(lang, A::Retry), class: "button ghost", on: "") } if can_abandon { action_button(action: abandon, csrf: csrf.clone(), label: text(lang, A::Abandon), class: "button danger", on: "") }
  • }) }