nekrochan/src/web/actions/edit_posts.rs

77 řádky
2.0 KiB
Rust

use actix_web::{post, web::Data, HttpRequest, HttpResponse};
use sqlx::query;
use std::{collections::HashMap, fmt::Write};
use crate::{
ctx::Ctx,
db::models::Post,
error::NekrochanError,
markup::markup,
qsform::QsForm,
web::{tcx::TemplateCtx, template_response},
};
use super::{get_posts_from_ids, ActionTemplate};
#[post("/actions/edit-posts")]
pub async fn edit_posts(
ctx: Data<Ctx>,
req: HttpRequest,
QsForm(edits): QsForm<HashMap<String, String>>,
) -> Result<HttpResponse, NekrochanError> {
let tcx = TemplateCtx::new(&ctx, &req).await?;
if !(tcx.perms.owner() || tcx.perms.edit_posts()) {
return Err(NekrochanError::InsufficientPermissionError);
}
let ids = edits.keys().map(|s| s.to_owned()).collect::<Vec<String>>();
let posts = get_posts_from_ids(&ctx, &ids)
.await
.into_iter()
.map(|post| (format!("{}/{}", post.board, post.id), post))
.collect::<HashMap<String, Post>>();
let mut response = String::new();
let mut posts_edited = 0;
for (key, content_nomarkup) in edits {
let post = &posts[&key];
let content_nomarkup = content_nomarkup.trim();
let (content, quoted_posts) = markup(
&ctx,
&tcx.perms,
Some(post.board.clone()),
post.thread,
content_nomarkup,
)
.await?;
post.update_content(&ctx, content, content_nomarkup.into())
.await?;
query(&format!(
"UPDATE posts_{} SET quotes = array_remove(quotes, $1) WHERE $1 = ANY(quotes)",
post.board
))
.bind(post.id)
.execute(ctx.db())
.await?;
for quoted_post in quoted_posts {
quoted_post.update_quotes(&ctx, post.id).await?;
}
posts_edited += 1;
}
if posts_edited != 0 {
writeln!(&mut response, "[Úspěch] Upraveny příspěvky: {posts_edited}").ok();
}
let template = ActionTemplate { tcx, response };
template_response(&template)
}