Skip to main content

rpc/forms/
noticed.rs

1//! Submit with the duplicate-name notice of a created or renamed account.
2
3use forms::{ACCOUNT_EDIT, Form, FormValues};
4use server::command::account_name::account_name_notice;
5use server::user::User;
6use uuid::Uuid;
7
8use super::script_edit_load::load_script_edit;
9use super::{Failure, Handler, Submitted, load, submit};
10
11const NO_SOURCE: &str =
12    "this script was uploaded as bytecode and has no source; saving it stores the source you enter";
13
14/// [`load`] and the notice a script stored without source carries.
15///
16/// # Errors
17/// The load's failure.
18pub async fn load_noticed(
19    user_id: Uuid,
20    form: &Form,
21    id: &str,
22) -> Result<(FormValues, Option<String>), Failure> {
23    if Handler::of(form)? != Handler::ScriptEdit {
24        return Ok((load(user_id, form, id).await?, None));
25    }
26    let (values, sourceless) = load_script_edit(user_id, id).await?;
27    Ok((values, sourceless.then(|| NO_SOURCE.to_string())))
28}
29
30/// The name an `account-edit` submit would rename, read before it changes.
31async fn stored_name(user_id: Uuid, form: &Form, values: &FormValues) -> Option<String> {
32    if form.name != ACCOUNT_EDIT.name {
33        return None;
34    }
35    let id = Uuid::parse_str(values.text("id")?.trim()).ok()?;
36    let stored = User { id: user_id }.account_snapshot(id).await.ok()??;
37    stored
38        .tags
39        .into_iter()
40        .find(|tag| tag.is_named("name"))
41        .map(|tag| tag.normalized().1.to_string())
42}
43
44fn renamed(before: Option<&str>, values: &FormValues) -> bool {
45    let submitted = values.text("name").map(str::trim);
46    matches!((before, submitted), (Some(old), Some(new)) if old != new)
47}
48
49/// [`submit`] and the notice a created account, or an edited one whose name
50/// changed, carries when it shares its name with a sibling.
51///
52/// # Errors
53/// The submit's failure; a notice that cannot be read is logged and omitted,
54/// since the submit has already committed.
55pub async fn submit_noticed(
56    user_id: Uuid,
57    form: &Form,
58    values: &FormValues,
59) -> Result<(Submitted, Option<String>), Failure> {
60    let before = stored_name(user_id, form, values).await;
61    let submitted = submit(user_id, form, values).await?;
62    let wanted = match Handler::of(form)? {
63        Handler::AccountCreate => true,
64        Handler::AccountEdit => renamed(before.as_deref(), values),
65        _ => false,
66    };
67    let notice = match wanted {
68        true => account_name_notice(user_id, submitted.id)
69            .await
70            .unwrap_or_else(|err| {
71                tracing::error!("duplicate-name notice of a saved account failed: {err:?}");
72                None
73            }),
74        false => None,
75    };
76    Ok((submitted, notice))
77}