forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

mail.rs299 lines, 10.5 KiBHistoryRawDownload
1//! `/admin/mail`: the state of the SMTP settings, the mail outbox with its states, the retry and abandon
2//! actions, and a test mail to the administrator's own address.
3//!
4//! The outbox never shows a body: the store holds it sealed, and the list selects only the header columns.
5//! Retrying a failed row sends it again at once; abandoning a row that is not yet sent blanks its body, as
6//! the worker does when it gives up.
7
8use im_core::model::AuditAction;
9use serde::Deserialize;
10use serde_json::json;
11use topcoat::Result;
12use topcoat::context::{Cx, app_context};
13use topcoat::router::content::Form;
14use topcoat::router::error::{SeeOther, not_found};
15use topcoat::router::{page, route};
16use topcoat::view::{View, component, view};
17
18use crate::audit::{Actor, record};
19use crate::auth::{require_admin, require_admin_csrf};
20use crate::i18n::Lang;
21use crate::i18n::admin::{A, text};
22use crate::mail::{self, Mail, Recipient};
23use crate::pages::admin::{
24 PAGE_SIZE, Tab, action_button, changed, done, error_text, flash_messages, frame_info,
25 notice_text, refused, tabs,
26};
27use crate::pages::path_param;
28use crate::state::AppState;
29use crate::views::{ViewerInfo, page_lang, shell};
30
31/// The query of the mail page: the flash codes, the state filter, and the cursor of the next page.
32#[derive(Deserialize, Default)]
33struct MailQuery {
34 #[serde(default)]
35 notice: String,
36 #[serde(default)]
37 error: String,
38 /// `pending`, `sent`, `failed` or `abandoned`. Anything else shows every state.
39 #[serde(default)]
40 state: String,
41 /// The id of the last row of the previous page.
42 #[serde(default)]
43 after: String,
44}
45
46/// The form of the mail actions: only the CSRF token.
47#[derive(Deserialize, Default)]
48struct CsrfForm {
49 #[serde(default)]
50 csrf: String,
51}
52
53/// The SMTP settings as the page shows them. The password is never shown, only whether a login is set.
54struct SmtpInfo {
55 host: String,
56 sender: String,
57 login: String,
58}
59
60/// The states the filter links offer.
61const STATES: [&str; 4] = ["pending", "sent", "failed", "abandoned"];
62
63/// `GET /admin/mail`.
64#[page("/admin/mail")]
65async fn mail_page(cx: &Cx, Form(query): Form<MailQuery>) -> Result<impl View> {
66 let viewer = require_admin(cx).await?;
67 let state = app_context::<AppState>(cx);
68 let (lang, info) = frame_info(cx, &viewer);
69 let filter = STATES
70 .contains(&query.state.as_str())
71 .then(|| query.state.clone());
72 let after = (!query.after.is_empty()).then(|| query.after.clone());
73 let mut rows = state
74 .store
75 .outbox_page(filter.as_deref(), after.as_deref(), PAGE_SIZE + 1)
76 .await?;
77 let next = if rows.len() > PAGE_SIZE as usize {
78 rows.truncate(PAGE_SIZE as usize);
79 rows.last().map(|row| row.id.clone())
80 } else {
81 None
82 };
83 let counts = state.store.outbox_counts().await?;
84 let smtp = state.config.smtp.enabled().then(|| SmtpInfo {
85 host: format!("{}:{}", state.config.smtp.host, state.config.smtp.port),
86 sender: format!(
87 "{} <{}>",
88 state.config.smtp.from_name, state.config.smtp.from
89 ),
90 login: if state.config.smtp.username.is_empty() {
91 String::from("-")
92 } else {
93 state.config.smtp.username.clone()
94 },
95 });
96 Ok(mail_view(
97 cx,
98 lang,
99 info,
100 viewer.session.csrf_token.clone(),
101 smtp,
102 counts,
103 filter.unwrap_or_default(),
104 rows,
105 next,
106 notice_text(lang, &query.notice).map(str::to_owned),
107 error_text(lang, &query.error).map(str::to_owned),
108 ))
109}
110
111/// `POST /admin/mail/test`: queues a test mail to the administrator's own address.
112#[route(POST "/admin/mail/test")]
113async fn send_test(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> {
114 let viewer = require_admin_csrf(cx, &form.csrf).await?;
115 let state = app_context::<AppState>(cx);
116 let lang = page_lang(cx, Some(&viewer));
117 let Ok(to) = Recipient::new(Some(&viewer.user.name), &viewer.user.email) else {
118 return Ok(refused("/admin/mail", "email"));
119 };
120 let mail = Mail::Test {
121 subject: text(lang, A::TestMailSubject),
122 body: text(lang, A::TestMailBody),
123 };
124 mail::queue(&state.store, &state.key, &to, lang, &mail).await?;
125 record(
126 cx,
127 Actor::User(&viewer.user.id),
128 AuditAction::MailTestQueued,
129 None,
130 json!({}),
131 )
132 .await;
133 changed(&state.live);
134 Ok(done("/admin/mail", "test-queued"))
135}
136
137/// `POST /admin/mail/{id}/retry`: a failed row is sent again now.
138#[route(POST "/admin/mail/{id}/retry")]
139async fn retry_mail(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> {
140 let viewer = require_admin_csrf(cx, &form.csrf).await?;
141 let id = outbox_id(cx)?;
142 let state = app_context::<AppState>(cx);
143 if !state.store.retry_mail(&id).await? {
144 return Ok(refused("/admin/mail", "mail-retry"));
145 }
146 record(
147 cx,
148 Actor::User(&viewer.user.id),
149 AuditAction::MailRetried,
150 Some(("mail", &id)),
151 json!({}),
152 )
153 .await;
154 changed(&state.live);
155 Ok(done("/admin/mail", "mail-retried"))
156}
157
158/// `POST /admin/mail/{id}/abandon`: a row that is not yet sent is given up, and its body is removed.
159#[route(POST "/admin/mail/{id}/abandon")]
160async fn abandon_mail(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> {
161 let viewer = require_admin_csrf(cx, &form.csrf).await?;
162 let id = outbox_id(cx)?;
163 let state = app_context::<AppState>(cx);
164 if !state.store.abandon_mail(&id).await? {
165 return Ok(refused("/admin/mail", "mail-abandon"));
166 }
167 record(
168 cx,
169 Actor::User(&viewer.user.id),
170 AuditAction::MailAbandoned,
171 Some(("mail", &id)),
172 json!({}),
173 )
174 .await;
175 changed(&state.live);
176 Ok(done("/admin/mail", "mail-abandoned"))
177}
178
179/// The outbox id in the path. Ids are ULIDs: 26 letters and digits. Anything else is a 404.
180fn outbox_id(cx: &Cx) -> Result<String> {
181 match path_param(cx, "id") {
182 Some(id) if id.len() == 26 && id.bytes().all(|b| b.is_ascii_alphanumeric()) => Ok(id),
183 _ => Err(not_found().into()),
184 }
185}
186
187/// The mail page: SMTP status, the state counts, the filter links, the outbox, and the test button.
188#[allow(clippy::too_many_arguments)]
189fn mail_view(
190 cx: &Cx,
191 lang: Lang,
192 info: ViewerInfo,
193 csrf: String,
194 smtp: Option<SmtpInfo>,
195 counts: Vec<(String, i64)>,
196 filter: String,
197 rows: Vec<im_core::store::admin::OutboxRow>,
198 next: Option<String>,
199 success: Option<String>,
200 problem: Option<String>,
201) -> impl View {
202 let next_href = next.map(|after| {
203 if filter.is_empty() {
204 format!("/admin/mail?after={after}")
205 } else {
206 format!("/admin/mail?state={filter}&after={after}")
207 }
208 });
209 view! { cx =>
210 shell(title: text(lang, A::MailTitle), lang: lang, viewer: Some(info),
211 tabs(lang: lang, current: Tab::Mail)
212 <section class="stack" data-live="/admin/events">
213 <h1>(text(lang, A::MailTitle))</h1>
214 <p class="muted">(text(lang, A::MailIntro))</p>
215 flash_messages(success: success, problem: problem)
216 <h2>(text(lang, A::SmtpStatus))</h2>
217 if let Some(smtp) = smtp {
218 <dl class="facts">
219 <dt>(text(lang, A::SmtpHost))</dt><dd>(smtp.host.clone())</dd>
220 <dt>(text(lang, A::SmtpSender))</dt><dd>(smtp.sender.clone())</dd>
221 <dt>(text(lang, A::SmtpLogin))</dt><dd>(smtp.login.clone())</dd>
222 </dl>
223 } else {
224 <p class="muted">(text(lang, A::SmtpNotConfigured))</p>
225 }
226 action_button(action: "/admin/mail/test".to_owned(), csrf: csrf.clone(), label: text(lang, A::SendTest), class: "button ghost", on: "")
227 <h2>(text(lang, A::OutboxTitle))</h2>
228 <p class="row">
229 <span class="muted">(text(lang, A::OutboxFilter))": "</span>
230 <a href="/admin/mail">(text(lang, A::AllStates))</a>
231 for (state, count) in counts {
232 <a href=(format!("/admin/mail?state={state}"))>(state_label(lang, &state))" ("(count)")"</a>
233 }
234 </p>
235 if rows.is_empty() {
236 <p class="muted">(text(lang, A::NoMail))</p>
237 } else {
238 <ul class="item-list">
239 for row in rows {
240 mail_item(lang: lang, csrf: csrf.clone(), row: row)
241 }
242 </ul>
243 }
244 if let Some(href) = next_href {
245 <p><a class="button ghost" href=(href)>(text(lang, A::NextPage))</a></p>
246 }
247 </section>
248 )
249 }
250}
251
252/// The text of an outbox state. Unknown states are shown as they are stored.
253fn state_label(lang: Lang, state: &str) -> String {
254 match state {
255 "pending" => text(lang, A::StatePending).to_owned(),
256 "sent" => text(lang, A::StateSent).to_owned(),
257 "failed" => text(lang, A::StateFailed).to_owned(),
258 "abandoned" => text(lang, A::StateAbandoned).to_owned(),
259 other => other.to_owned(),
260 }
261}
262
263/// One outbox row: its recipient, subject, state, attempts, and the actions the state allows.
264#[component]
265async fn mail_item(
266 lang: Lang,
267 csrf: String,
268 row: im_core::store::admin::OutboxRow,
269) -> Result<impl View> {
270 let state = state_label(lang, &row.state);
271 let retry = format!("/admin/mail/{}/retry", row.id);
272 let abandon = format!("/admin/mail/{}/abandon", row.id);
273 let can_retry = row.state == "failed";
274 let can_abandon = row.state == "pending" || row.state == "failed";
275 Ok(view! {
276 <li class="item">
277 <div class="item-main">
278 <strong>(row.subject.clone())</strong>
279 <div class="muted">
280 <span>(row.to_addr.clone())</span>
281 <span>" · "(row.kind.clone())</span>
282 <span>" · "(state)</span>
283 <span>" · "(text(lang, A::Attempts))": "(row.attempts)</span>
284 <span>" · "(text(lang, A::NextAttempt))": "(row.next_attempt_at.clone())</span>
285 <span>" · "(text(lang, A::Created))": "(row.created_at.clone())</span>
286 </div>
287 if let Some(error) = row.last_error.clone() {
288 <div class="hint">(text(lang, A::LastError))": "(error)</div>
289 }
290 </div>
291 if can_retry {
292 action_button(action: retry, csrf: csrf.clone(), label: text(lang, A::Retry), class: "button ghost", on: "")
293 }
294 if can_abandon {
295 action_button(action: abandon, csrf: csrf.clone(), label: text(lang, A::Abandon), class: "button danger", on: "")
296 }
297 </li>
298 })
299}