1use askama::Template;
4use axum::{
5 Extension, Form,
6 extract::Path,
7 response::{IntoResponse, Response},
8};
9use forms::SCRIPT_EDIT;
10use server::command::script::DeleteScript;
11use uuid::Uuid;
12
13use crate::pages::{
14 HtmlTemplate,
15 forms::edit::{Edit, Edited},
16};
17use crate::{jwt_auth::JWTAuthMiddleware, parse::parse_uuid, response::WebError};
18
19pub const SUBMIT_PATH: &str = "/api/script/edit/submit";
20
21const EDIT: Edit = Edit {
22 form: &SCRIPT_EDIT,
23 noun: "Script",
24 action: SUBMIT_PATH,
25 page: "/script/edit/{id}",
26 remedy: "",
27};
28
29#[derive(Template)]
30#[template(path = "pages/script/edit.html")]
31struct ScriptEditPage {
32 id: Uuid,
33 form: String,
34 notice: Option<String>,
35}
36
37fn parse_script_id(raw: &str) -> Result<Uuid, WebError> {
38 parse_uuid(raw, "script ID")
39}
40
41#[must_use]
43pub fn updated_message(id: Uuid) -> String {
44 format!("{}: {id}", t!("Script updated"))
45}
46
47pub async fn script_edit_page(
48 Extension(jwt_auth): Extension<JWTAuthMiddleware>,
49 Path(id): Path<String>,
50) -> Result<impl IntoResponse, WebError> {
51 let id = parse_script_id(&id)?;
52 let (form, notice) = EDIT
53 .loaded_noticed(jwt_auth.user.id, &id.to_string())
54 .await?;
55 Ok(HtmlTemplate(ScriptEditPage { id, form, notice }))
56}
57
58pub async fn script_edit_submit(
59 Extension(jwt_auth): Extension<JWTAuthMiddleware>,
60 Form(pairs): Form<Vec<(String, String)>>,
61) -> Result<Response, WebError> {
62 Ok(match EDIT.submit(jwt_auth.user.id, pairs).await? {
63 Edited::Saved { id, .. } => {
64 EDIT.saved_response(jwt_auth.user.id, id, updated_message(id))
65 .await?
66 }
67 Edited::Invalid(response) => response,
68 })
69}
70
71pub async fn delete_script(
72 Extension(jwt_auth): Extension<JWTAuthMiddleware>,
73 Path(id): Path<String>,
74) -> Result<impl IntoResponse, WebError> {
75 let id = parse_script_id(&id)?;
76 DeleteScript::new()
77 .user_id(jwt_auth.user.id)
78 .script_id(id)
79 .run()
80 .await?;
81 Ok(format!("{}: {id}", t!("Script deleted")))
82}
83
84#[cfg(test)]
85#[path = "edit_tests.rs"]
86mod tests;