Tento commit je obsažen v:
sneedmaster 2023-12-11 16:59:32 +01:00
rodič 1be169b62c
revize 51512a19e4
38 změnil soubory, kde provedl 125 přidání a 135 odebrání

Zobrazit soubor

@ -18,7 +18,7 @@ impl Account {
.await?; .await?;
ctx.cache() ctx.cache()
.json_set(format!("accounts:{}", username), ".", &account) .json_set(format!("accounts:{username}"), ".", &account)
.await?; .await?;
Ok(account) Ok(account)
@ -27,7 +27,7 @@ impl Account {
pub async fn read(ctx: &Ctx, username: String) -> Result<Option<Self>, NekrochanError> { pub async fn read(ctx: &Ctx, username: String) -> Result<Option<Self>, NekrochanError> {
let account: Option<String> = ctx let account: Option<String> = ctx
.cache() .cache()
.json_get(format!("accounts:{}", username), ".") .json_get(format!("accounts:{username}"), ".")
.await?; .await?;
let account = match account { let account = match account {

Zobrazit soubor

@ -77,7 +77,7 @@ impl Ban {
let mut ban_map = HashMap::new(); let mut ban_map = HashMap::new();
for ban in bans.into_iter() { for ban in bans {
let board = ban.board.clone(); let board = ban.board.clone();
ban_map.insert(board, ban); ban_map.insert(board, ban);

Zobrazit soubor

@ -81,7 +81,7 @@ impl Board {
} }
pub async fn read(ctx: &Ctx, id: String) -> Result<Option<Self>, NekrochanError> { pub async fn read(ctx: &Ctx, id: String) -> Result<Option<Self>, NekrochanError> {
let board: Option<String> = ctx.cache().json_get(format!("boards:{}", id), ".").await?; let board: Option<String> = ctx.cache().json_get(format!("boards:{id}"), ".").await?;
let board = match board { let board = match board {
Some(json) => Some(serde_json::from_str(&json)?), Some(json) => Some(serde_json::from_str(&json)?),
@ -95,7 +95,7 @@ impl Board {
let mut boards = Vec::new(); let mut boards = Vec::new();
let ids: Vec<String> = ctx.cache().lrange("board_ids", 0, -1).await?; let ids: Vec<String> = ctx.cache().lrange("board_ids", 0, -1).await?;
for id in ids.into_iter() { for id in ids {
if let Some(board) = Self::read(ctx, id).await? { if let Some(board) = Self::read(ctx, id).await? {
boards.push(board); boards.push(board);
} }
@ -108,7 +108,7 @@ impl Board {
let mut boards = HashMap::new(); let mut boards = HashMap::new();
let ids: Vec<String> = ctx.cache().lrange("board_ids", 0, -1).await?; let ids: Vec<String> = ctx.cache().lrange("board_ids", 0, -1).await?;
for id in ids.into_iter() { for id in ids {
if let Some(board) = Self::read(ctx, id.clone()).await? { if let Some(board) = Self::read(ctx, id.clone()).await? {
boards.insert(id, board); boards.insert(id, board);
} }
@ -210,7 +210,7 @@ impl Board {
pub fn random_banner(&self) -> Option<File> { pub fn random_banner(&self) -> Option<File> {
self.banners self.banners
.choose(&mut thread_rng()) .choose(&mut thread_rng())
.map(|banner| banner.to_owned()) .map(std::clone::Clone::clone)
} }
pub fn thread_captcha(&self) -> Option<(String, String)> { pub fn thread_captcha(&self) -> Option<(String, String)> {

Zobrazit soubor

@ -13,7 +13,7 @@ pub async fn init_cache(ctx: &Ctx) -> Result<(), Error> {
.fetch_all(ctx.db()) .fetch_all(ctx.db())
.await?; .await?;
for account in accounts.iter() { for account in &accounts {
ctx.cache() ctx.cache()
.json_set(format!("accounts:{}", account.username), ".", &account) .json_set(format!("accounts:{}", account.username), ".", &account)
.await?; .await?;
@ -21,7 +21,7 @@ pub async fn init_cache(ctx: &Ctx) -> Result<(), Error> {
let boards: Vec<Board> = query_as("SELECT * FROM boards").fetch_all(ctx.db()).await?; let boards: Vec<Board> = query_as("SELECT * FROM boards").fetch_all(ctx.db()).await?;
for board in boards.iter() { for board in &boards {
ctx.cache() ctx.cache()
.json_set(format!("boards:{}", board.id), ".", board) .json_set(format!("boards:{}", board.id), ".", board)
.await?; .await?;
@ -39,7 +39,7 @@ pub async fn init_cache(ctx: &Ctx) -> Result<(), Error> {
ctx.cache().set("total_threads", 0).await?; ctx.cache().set("total_threads", 0).await?;
for board in boards.iter() { for board in &boards {
let (thread_count,): (i64,) = query_as(&format!( let (thread_count,): (i64,) = query_as(&format!(
"SELECT COUNT(id) FROM posts_{} WHERE thread IS NULL", "SELECT COUNT(id) FROM posts_{} WHERE thread IS NULL",
board.id board.id
@ -53,10 +53,10 @@ pub async fn init_cache(ctx: &Ctx) -> Result<(), Error> {
.await?; .await?;
} }
for board in boards.iter() { for board in &boards {
let posts = Post::read_all(ctx, board.id.clone()).await?; let posts = Post::read_all(ctx, board.id.clone()).await?;
for post in posts.into_iter() { for post in posts {
let ip_key = format!("by_ip:{}", post.ip); let ip_key = format!("by_ip:{}", post.ip);
let content_key = format!("by_content:{}", digest(post.content_nomarkup)); let content_key = format!("by_content:{}", digest(post.content_nomarkup));

Zobrazit soubor

@ -72,7 +72,7 @@ impl Post {
.await?; .await?;
} }
let ip_key = format!("by_ip:{}", ip); let ip_key = format!("by_ip:{ip}");
let content_key = format!("by_content:{}", digest(post.content_nomarkup.as_bytes())); let content_key = format!("by_content:{}", digest(post.content_nomarkup.as_bytes()));
let member = format!("{}/{}", board.id, post.id); let member = format!("{}/{}", board.id, post.id);
let score = post.created.timestamp_micros(); let score = post.created.timestamp_micros();
@ -143,10 +143,9 @@ impl Post {
pub async fn read_board_catalog(ctx: &Ctx, board: String) -> Result<Vec<Self>, NekrochanError> { pub async fn read_board_catalog(ctx: &Ctx, board: String) -> Result<Vec<Self>, NekrochanError> {
let posts = query_as(&format!( let posts = query_as(&format!(
r#"SELECT * FROM posts_{} r#"SELECT * FROM posts_{board}
WHERE thread IS NULL WHERE thread IS NULL
ORDER BY sticky DESC, bumped DESC"#, ORDER BY sticky DESC, bumped DESC"#
board
)) ))
.fetch_all(ctx.db()) .fetch_all(ctx.db())
.await?; .await?;
@ -234,7 +233,7 @@ impl Post {
} }
pub async fn read_all(ctx: &Ctx, board: String) -> Result<Vec<Self>, NekrochanError> { pub async fn read_all(ctx: &Ctx, board: String) -> Result<Vec<Self>, NekrochanError> {
let posts = query_as(&format!("SELECT * FROM posts_{}", board)) let posts = query_as(&format!("SELECT * FROM posts_{board}"))
.fetch_all(ctx.db()) .fetch_all(ctx.db())
.await?; .await?;
@ -333,7 +332,7 @@ impl Post {
.fetch_all(ctx.db()) .fetch_all(ctx.db())
.await?; .await?;
for post in to_be_deleted.iter() { for post in &to_be_deleted {
let id = post.id; let id = post.id;
let url = post.post_url(); let url = post.post_url();
@ -443,7 +442,7 @@ async fn delete_old_threads(ctx: &Ctx, board: &Board) -> Result<(), NekrochanErr
.fetch_all(ctx.db()) .fetch_all(ctx.db())
.await?; .await?;
for thread in old_threads.iter() { for thread in &old_threads {
thread.delete(ctx).await?; thread.delete(ctx).await?;
} }

Zobrazit soubor

@ -148,12 +148,12 @@ impl From<sqlx::Error> for NekrochanError {
None => false, None => false,
}; };
if !overboard_err { if overboard_err {
Self::OverboardError
} else {
error!("{e:#?}"); error!("{e:#?}");
Self::InternalError Self::InternalError
} else {
Self::OverboardError
} }
} }
} }

Zobrazit soubor

@ -164,9 +164,8 @@ async fn process_image(
)); ));
} }
let thumb_name = match thumb_name { let Some(thumb_name) = thumb_name else {
Some(thumb_name) => thumb_name, return Ok((width, height));
None => return Ok((width, height)),
}; };
let thumb_w = if width > cfg.files.thumb_size { let thumb_w = if width > cfg.files.thumb_size {
@ -255,9 +254,8 @@ async fn process_video(
)); ));
} }
let thumb_name = match thumb_name { let Some(thumb_name) = thumb_name else {
Some(thumb_name) => thumb_name, return Ok((width, height));
None => return Ok((width, height)),
}; };
let thumb_size = cfg.files.thumb_size; let thumb_size = cfg.files.thumb_size;
@ -302,14 +300,14 @@ pub async fn cleanup_files(ctx: &Ctx) -> Result<(), Error> {
let boards = Board::read_all(ctx).await?; let boards = Board::read_all(ctx).await?;
for board in boards.into_iter() { for board in boards {
for file in board.banners.0 { for file in board.banners.0 {
keep.insert(format!("{}.{}", file.timestamp, file.format)); keep.insert(format!("{}.{}", file.timestamp, file.format));
} }
let posts = Post::read_all(ctx, board.id.clone()).await?; let posts = Post::read_all(ctx, board.id.clone()).await?;
for post in posts.into_iter() { for post in posts {
for file in post.files.0 { for file in post.files.0 {
keep.insert(format!("{}.{}", file.timestamp, file.format)); keep.insert(format!("{}.{}", file.timestamp, file.format));

Zobrazit soubor

@ -119,7 +119,7 @@ pub fn add_yous(
format!( format!(
"{}{}", "{}{}",
quote, quote,
if yous.contains(&format!("{}/{}", board, id)) { if yous.contains(&format!("{board}/{id}")) {
" <span class=\"small\">(Ty)</span>" " <span class=\"small\">(Ty)</span>"
} else { } else {
"" ""

Zobrazit soubor

@ -147,7 +147,7 @@ where
error_message, error_message,
}; };
let res = template_response(template)?; let res = template_response(&template)?;
let res = ServiceResponse::new(req, res).map_into_right_body(); let res = ServiceResponse::new(req, res).map_into_right_body();
Ok(ErrorHandlerResponse::Response(res)) Ok(ErrorHandlerResponse::Response(res))

Zobrazit soubor

@ -35,9 +35,8 @@ pub fn parse_name(
anon_name: &str, anon_name: &str,
name: &str, name: &str,
) -> Result<(String, Option<String>, Option<String>), NekrochanError> { ) -> Result<(String, Option<String>, Option<String>), NekrochanError> {
let captures = match NAME_REGEX.captures(name)? { let Some(captures) = NAME_REGEX.captures(name)? else {
Some(captures) => captures, return Ok((anon_name.to_owned(), None, None));
None => return Ok((anon_name.to_owned(), None, None)),
}; };
let name = match captures.get(1) { let name = match captures.get(1) {
@ -77,21 +76,13 @@ pub fn parse_name(
return Ok((name, tripcode, None)); return Ok((name, tripcode, None));
} }
fn capcode_fallback(owner: bool) -> Option<String> {
if owner {
Some("Admin".into())
} else {
Some("Uklízeč".into())
}
}
let capcode = match captures.get(5) { let capcode = match captures.get(5) {
Some(_) => match captures.get(6) { Some(_) => match captures.get(6) {
Some(capcode) => { Some(capcode) => {
let capcode: String = capcode.as_str().trim().into(); let capcode: String = capcode.as_str().trim().into();
if capcode.is_empty() { if capcode.is_empty() {
capcode_fallback(perms.owner()) Some(capcode_fallback(perms.owner()))
} else { } else {
if capcode.len() > 32 { if capcode.len() > 32 {
return Err(NekrochanError::CapcodeFormatError); return Err(NekrochanError::CapcodeFormatError);
@ -100,7 +91,7 @@ pub fn parse_name(
Some(capcode) Some(capcode)
} }
} }
None => capcode_fallback(perms.owner()), None => Some(capcode_fallback(perms.owner())),
}, },
None => None, None => None,
}; };
@ -108,6 +99,14 @@ pub fn parse_name(
Ok((name, tripcode, capcode)) Ok((name, tripcode, capcode))
} }
fn capcode_fallback(owner: bool) -> String {
if owner {
"Admin".into()
} else {
"Uklízeč".into()
}
}
pub async fn markup( pub async fn markup(
ctx: &Ctx, ctx: &Ctx,
board: &String, board: &String,
@ -119,15 +118,15 @@ pub async fn markup(
let text = QUOTE_REGEX.replace_all(&text, |captures: &Captures| { let text = QUOTE_REGEX.replace_all(&text, |captures: &Captures| {
let id_raw = &captures[1]; let id_raw = &captures[1];
let id = match id_raw.parse() {
Ok(id) => id, let Ok(id) = id_raw.parse() else {
Err(_) => return format!("<span class=\"dead-quote\">&gt;&gt;{id_raw}</span>"), return format!("<span class=\"dead-quote\">&gt;&gt;{id_raw}</span>");
}; };
let post = quoted_posts.get(&id); let post = quoted_posts.get(&id);
match post { if let Some(post) = post {
Some(post) => format!( format!(
"<a class=\"quote\" href=\"{}\">&gt;&gt;{}</a>{}", "<a class=\"quote\" href=\"{}\">&gt;&gt;{}</a>{}",
post.post_url(), post.post_url(),
post.id, post.id,
@ -136,8 +135,9 @@ pub async fn markup(
} else { } else {
"" ""
} }
), )
None => format!("<span class=\"dead-quote\">&gt;&gt;{id}</span>"), } else {
format!("<span class=\"dead-quote\">&gt;&gt;{id}</span>")
} }
}); });
@ -184,10 +184,7 @@ async fn get_quoted_posts(
for quote in QUOTE_REGEX.captures_iter(text) { for quote in QUOTE_REGEX.captures_iter(text) {
let id_raw = &quote.unwrap()[1]; let id_raw = &quote.unwrap()[1];
let id = match id_raw.parse() { let Ok(id) = id_raw.parse() else { continue };
Ok(id) => id,
Err(_) => continue,
};
quoted_ids.push(id); quoted_ids.push(id);
} }
@ -198,13 +195,12 @@ async fn get_quoted_posts(
let in_list = quoted_ids let in_list = quoted_ids
.iter() .iter()
.map(|id| id.to_string()) .map(std::string::ToString::to_string)
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(","); .join(",");
let quoted_posts = query_as(&format!( let quoted_posts = query_as(&format!(
"SELECT * FROM posts_{} WHERE id IN ({})", "SELECT * FROM posts_{board} WHERE id IN ({in_list})"
board, in_list
)) ))
.fetch_all(ctx.db()) .fetch_all(ctx.db())
.await? .await?

Zobrazit soubor

@ -133,7 +133,9 @@ pub async fn create_post(
let email_raw = form.email.trim(); let email_raw = form.email.trim();
let email = if !email_raw.is_empty() { let email = if email_raw.is_empty() {
None
} else {
if email_raw.len() > 256 { if email_raw.len() > 256 {
return Err(NekrochanError::EmailFormatError); return Err(NekrochanError::EmailFormatError);
} }
@ -147,8 +149,6 @@ pub async fn create_post(
} }
Some(email_raw.into()) Some(email_raw.into())
} else {
None
}; };
let content_nomarkup = form.content.0.trim().to_owned(); let content_nomarkup = form.content.0.trim().to_owned();
@ -177,7 +177,7 @@ pub async fn create_post(
let mut files = Vec::new(); let mut files = Vec::new();
for file in form.files.into_iter() { for file in form.files {
if file.size == 0 { if file.size == 0 {
continue; continue;
} }
@ -219,10 +219,10 @@ pub async fn create_post(
) )
.await?; .await?;
let ts = thread let ts = thread.as_ref().map_or_else(
.as_ref() || post.created.timestamp_micros(),
.map(|thread| thread.created.timestamp_micros()) |thread| thread.created.timestamp_micros(),
.unwrap_or_else(|| post.created.timestamp_micros()); );
let hash_input = format!("{}:{}:{}", ip, ts, ctx.cfg.secrets.user_id); let hash_input = format!("{}:{}:{}", ip, ts, ctx.cfg.secrets.user_id);
let user_hash = digest(hash_input); let user_hash = digest(hash_input);

Zobrazit soubor

@ -4,8 +4,8 @@ use super::tcx::TemplateCtx;
use crate::{ctx::Ctx, db::models::Post}; use crate::{ctx::Ctx, db::models::Post};
pub mod create_post; pub mod create_post;
pub mod staff_post_actions;
pub mod report_posts; pub mod report_posts;
pub mod staff_post_actions;
pub mod user_post_actions; pub mod user_post_actions;
#[derive(Template)] #[derive(Template)]
@ -18,8 +18,8 @@ pub struct ActionTemplate {
pub async fn get_posts_from_ids(ctx: &Ctx, ids: Vec<String>) -> Vec<Post> { pub async fn get_posts_from_ids(ctx: &Ctx, ids: Vec<String>) -> Vec<Post> {
let mut posts = Vec::new(); let mut posts = Vec::new();
for id in ids.into_iter() { for id in ids {
if let Some((board, id)) = parse_id(id) { if let Some((board, id)) = parse_id(&id) {
if let Ok(Some(post)) = Post::read(ctx, board, id).await { if let Ok(Some(post)) = Post::read(ctx, board, id).await {
posts.push(post); posts.push(post);
} }
@ -29,7 +29,7 @@ pub async fn get_posts_from_ids(ctx: &Ctx, ids: Vec<String>) -> Vec<Post> {
posts posts
} }
fn parse_id(id: String) -> Option<(String, i32)> { fn parse_id(id: &str) -> Option<(String, i32)> {
let (board, id) = id.split_once('/')?; let (board, id) = id.split_once('/')?;
let board = board.to_owned(); let board = board.to_owned();
let id = id.parse().ok()?; let id = id.parse().ok()?;

Zobrazit soubor

@ -46,7 +46,7 @@ pub async fn report_posts(
let reason = form.report_reason.trim(); let reason = form.report_reason.trim();
for post in posts.iter() { for post in &posts {
let board = &boards[&post.board]; let board = &boards[&post.board];
if bans.contains_key(&Some(board.id.clone())) if bans.contains_key(&Some(board.id.clone()))
@ -60,7 +60,7 @@ pub async fn report_posts(
writeln!( writeln!(
&mut response, &mut response,
"[Chyba] {}", "[Chyba] {}",
NekrochanError::BoardLockError(board.id.to_owned()) NekrochanError::BoardLockError(board.id.clone())
) )
.ok(); .ok();
@ -102,5 +102,5 @@ pub async fn report_posts(
let template = ActionTemplate { tcx, response }; let template = ActionTemplate { tcx, response };
template_response(template) template_response(&template)
} }

Zobrazit soubor

@ -55,7 +55,7 @@ pub async fn staff_post_actions(
let mut locks_toggled = 0; let mut locks_toggled = 0;
let mut bans_issued = 0; let mut bans_issued = 0;
for post in posts.iter() { for post in &posts {
if (form.remove_posts.is_some() if (form.remove_posts.is_some()
|| form.remove_files.is_some() || form.remove_files.is_some()
|| form.toggle_spoiler.is_some() || form.toggle_spoiler.is_some()
@ -100,7 +100,7 @@ pub async fn staff_post_actions(
let mut already_banned = HashSet::new(); let mut already_banned = HashSet::new();
for post in posts.into_iter() { for post in posts {
if let (Some(_), Some(ban_reason), Some(ban_duration), Some(ban_range)) = ( if let (Some(_), Some(ban_reason), Some(ban_duration), Some(ban_range)) = (
form.ban_user.clone(), form.ban_user.clone(),
form.ban_reason.clone(), form.ban_reason.clone(),
@ -126,14 +126,12 @@ pub async fn staff_post_actions(
let prefix = if post.ip.is_ipv4() { let prefix = if post.ip.is_ipv4() {
match ban_range.as_str() { match ban_range.as_str() {
"ip" => 32,
"lan" => 24, "lan" => 24,
"isp" => 16, "isp" => 16,
_ => 32, _ => 32,
} }
} else { } else {
match ban_range.as_str() { match ban_range.as_str() {
"ip" => 128,
"lan" => 48, "lan" => 48,
"isp" => 24, "isp" => 24,
_ => 128, _ => 128,
@ -144,10 +142,10 @@ pub async fn staff_post_actions(
let reason = ban_reason.trim().into(); let reason = ban_reason.trim().into();
let appealable = form.unappealable_ban.is_none(); let appealable = form.unappealable_ban.is_none();
let expires = if ban_duration != 0 { let expires = if ban_duration == 0 {
Some(Utc::now() + Duration::days(ban_duration))
} else {
None None
} else {
Some(Utc::now() + Duration::days(ban_duration))
}; };
Ban::create(&ctx, account, board, ip_range, reason, appealable, expires).await?; Ban::create(&ctx, account, board, ip_range, reason, appealable, expires).await?;
@ -215,5 +213,5 @@ pub async fn staff_post_actions(
let template = ActionTemplate { tcx, response }; let template = ActionTemplate { tcx, response };
template_response(template) template_response(&template)
} }

Zobrazit soubor

@ -52,7 +52,7 @@ pub async fn user_post_actions(
let mut files_removed = 0; let mut files_removed = 0;
let mut spoilers_toggled = 0; let mut spoilers_toggled = 0;
for post in posts.iter() { for post in &posts {
let board = &boards[&post.board]; let board = &boards[&post.board];
if bans.contains_key(&Some(board.id.clone())) if bans.contains_key(&Some(board.id.clone()))
@ -66,7 +66,7 @@ pub async fn user_post_actions(
writeln!( writeln!(
&mut response, &mut response,
"[Chyba] {}", "[Chyba] {}",
NekrochanError::BoardLockError(board.id.to_owned()) NekrochanError::BoardLockError(board.id.clone())
) )
.ok(); .ok();
@ -131,5 +131,5 @@ pub async fn user_post_actions(
let template = ActionTemplate { tcx, response }; let template = ActionTemplate { tcx, response };
template_response(template) template_response(&template)
} }

Zobrazit soubor

@ -49,17 +49,17 @@ pub async fn board(
.cache() .cache()
.get(format!("board_threads:{}", board.id)) .get(format!("board_threads:{}", board.id))
.await?; .await?;
let page = query.map(|q| q.page).unwrap_or(1); let page = query.map_or(1, |q| q.page);
let pages = paginate(board.config.0.page_size, count); let pages = paginate(board.config.0.page_size, count);
check_page(page, pages, board.config.0.page_count)?; check_page(page, pages, board.config.0.page_count)?;
let mut threads = Vec::new(); let mut threads = Vec::new();
for thread in Post::read_board_page(&ctx, &board, page).await?.into_iter() { for thread in Post::read_board_page(&ctx, &board, page).await? {
let replies = thread.read_replies(&ctx).await?; let replies = thread.read_replies(&ctx).await?;
threads.push((thread, replies)) threads.push((thread, replies));
} }
let template = BoardTemplate { let template = BoardTemplate {
@ -70,5 +70,5 @@ pub async fn board(
pages, pages,
}; };
template_response(template) template_response(&template)
} }

Zobrazit soubor

@ -42,5 +42,5 @@ pub async fn board_catalog(
threads, threads,
}; };
template_response(template) template_response(&template)
} }

Zobrazit soubor

@ -20,5 +20,5 @@ pub async fn index(ctx: Data<Ctx>, req: HttpRequest) -> Result<HttpResponse, Nek
let template = IndexTemplate { tcx, posts, files }; let template = IndexTemplate { tcx, posts, files };
template_response(template) template_response(&template)
} }

Zobrazit soubor

@ -26,7 +26,7 @@ pub async fn login_get(ctx: Data<Ctx>, req: HttpRequest) -> Result<HttpResponse,
let tcx = TemplateCtx::new(&ctx, &req).await?; let tcx = TemplateCtx::new(&ctx, &req).await?;
let template = LogInTemplate { tcx }; let template = LogInTemplate { tcx };
template_response(template) template_response(&template)
} }
#[derive(Deserialize)] #[derive(Deserialize)]

Zobrazit soubor

@ -30,10 +30,10 @@ pub async fn ban_response(
) -> Result<HttpResponse, NekrochanError> { ) -> Result<HttpResponse, NekrochanError> {
let tcx = TemplateCtx::new(ctx, req).await?; let tcx = TemplateCtx::new(ctx, req).await?;
template_response(BannedTemplate { tcx, ban }) template_response(&BannedTemplate { tcx, ban })
} }
pub fn template_response<T>(template: T) -> Result<HttpResponse, NekrochanError> pub fn template_response<T>(template: &T) -> Result<HttpResponse, NekrochanError>
where where
T: Template, T: Template,
{ {

Zobrazit soubor

@ -42,17 +42,17 @@ pub async fn overboard(
let tcx = TemplateCtx::new(&ctx, &req).await?; let tcx = TemplateCtx::new(&ctx, &req).await?;
let count = ctx.cache().get("total_threads").await?; let count = ctx.cache().get("total_threads").await?;
let page = query.map(|q| q.page).unwrap_or(1); let page = query.map_or(1, |q| q.page);
let pages = paginate(15, count); let pages = paginate(15, count);
check_page(page, pages, None)?; check_page(page, pages, None)?;
let mut threads = Vec::new(); let mut threads = Vec::new();
for thread in Post::read_overboard_page(&ctx, page).await?.into_iter() { for thread in Post::read_overboard_page(&ctx, page).await? {
let replies = thread.read_replies(&ctx).await?; let replies = thread.read_replies(&ctx).await?;
threads.push((thread, replies)) threads.push((thread, replies));
} }
let template = OverboardTemplate { let template = OverboardTemplate {
@ -63,5 +63,5 @@ pub async fn overboard(
pages, pages,
}; };
template_response(template) template_response(&template)
} }

Zobrazit soubor

@ -26,5 +26,5 @@ pub async fn overboard_catalog(
let template = OverboardCatalogTemplate { tcx, threads }; let template = OverboardCatalogTemplate { tcx, threads };
template_response(template) template_response(&template)
} }

Zobrazit soubor

@ -24,5 +24,5 @@ pub async fn account(ctx: Data<Ctx>, req: HttpRequest) -> Result<HttpResponse, N
let account = account_from_auth(&ctx, &req).await?; let account = account_from_auth(&ctx, &req).await?;
let template = AccountTemplate { tcx, account }; let template = AccountTemplate { tcx, account };
template_response(template) template_response(&template)
} }

Zobrazit soubor

@ -22,5 +22,5 @@ pub async fn accounts(ctx: Data<Ctx>, req: HttpRequest) -> Result<HttpResponse,
let accounts = Account::read_all(&ctx).await?; let accounts = Account::read_all(&ctx).await?;
let template = AccountsTemplate { tcx, accounts }; let template = AccountsTemplate { tcx, accounts };
template_response(template) template_response(&template)
} }

Zobrazit soubor

@ -39,10 +39,10 @@ pub async fn add_banners(
cfg.files.videos = false; cfg.files.videos = false;
for banner in added_banners.into_iter() { for banner in added_banners {
let file = File::new(&cfg, banner, false, false).await?; let file = File::new(&cfg, banner, false, false).await?;
new_banners.push(file) new_banners.push(file);
} }
board.update_banners(&ctx, new_banners).await?; board.update_banners(&ctx, new_banners).await?;

Zobrazit soubor

@ -24,7 +24,7 @@ pub async fn remove_accounts(
return Err(NekrochanError::InsufficientPermissionError); return Err(NekrochanError::InsufficientPermissionError);
} }
for account in form.accounts.into_iter() { for account in form.accounts {
if let Some(account) = Account::read(&ctx, account).await? { if let Some(account) = Account::read(&ctx, account).await? {
if account.owner { if account.owner {
return Err(NekrochanError::OwnerDeletionError); return Err(NekrochanError::OwnerDeletionError);

Zobrazit soubor

@ -23,7 +23,7 @@ pub async fn remove_bans(
return Err(NekrochanError::InsufficientPermissionError); return Err(NekrochanError::InsufficientPermissionError);
} }
for ban in form.bans.into_iter() { for ban in form.bans {
if let Some(ban) = Ban::read_by_id(&ctx, ban).await? { if let Some(ban) = Ban::read_by_id(&ctx, ban).await? {
ban.delete(&ctx).await?; ban.delete(&ctx).await?;
} }

Zobrazit soubor

@ -23,7 +23,7 @@ pub async fn remove_boards(
return Err(NekrochanError::InsufficientPermissionError); return Err(NekrochanError::InsufficientPermissionError);
} }
for board in form.boards.into_iter() { for board in form.boards {
if let Some(board) = Board::read(&ctx, board).await? { if let Some(board) = Board::read(&ctx, board).await? {
board.delete(&ctx).await?; board.delete(&ctx).await?;
} }

Zobrazit soubor

@ -42,7 +42,7 @@ pub async fn update_boards(
return Err(NekrochanError::DescriptionFormatError); return Err(NekrochanError::DescriptionFormatError);
} }
for board in form.boards.into_iter() { for board in form.boards {
if let Some(board) = Board::read(&ctx, board).await? { if let Some(board) = Board::read(&ctx, board).await? {
board.update_name(&ctx, name.clone()).await?; board.update_name(&ctx, name.clone()).await?;
board.update_description(&ctx, description.clone()).await?; board.update_description(&ctx, description.clone()).await?;

Zobrazit soubor

@ -44,51 +44,51 @@ pub async fn update_permissions(
let mut permissions = BitFlags::empty(); let mut permissions = BitFlags::empty();
if form.edit_posts.is_some() { if form.edit_posts.is_some() {
permissions |= Permissions::EditPosts permissions |= Permissions::EditPosts;
} }
if form.manage_posts.is_some() { if form.manage_posts.is_some() {
permissions |= Permissions::ManagePosts permissions |= Permissions::ManagePosts;
} }
if form.capcodes.is_some() { if form.capcodes.is_some() {
permissions |= Permissions::Capcodes permissions |= Permissions::Capcodes;
} }
if form.staff_log.is_some() { if form.staff_log.is_some() {
permissions |= Permissions::StaffLog permissions |= Permissions::StaffLog;
} }
if form.reports.is_some() { if form.reports.is_some() {
permissions |= Permissions::Reports permissions |= Permissions::Reports;
} }
if form.bans.is_some() { if form.bans.is_some() {
permissions |= Permissions::Bans permissions |= Permissions::Bans;
} }
if form.board_banners.is_some() { if form.board_banners.is_some() {
permissions |= Permissions::BoardBanners permissions |= Permissions::BoardBanners;
} }
if form.board_config.is_some() { if form.board_config.is_some() {
permissions |= Permissions::BoardConfig permissions |= Permissions::BoardConfig;
} }
if form.bypass_bans.is_some() { if form.bypass_bans.is_some() {
permissions |= Permissions::BypassBans permissions |= Permissions::BypassBans;
} }
if form.bypass_board_lock.is_some() { if form.bypass_board_lock.is_some() {
permissions |= Permissions::BypassBoardLock permissions |= Permissions::BypassBoardLock;
} }
if form.bypass_thread_lock.is_some() { if form.bypass_thread_lock.is_some() {
permissions |= Permissions::BypassThreadLock permissions |= Permissions::BypassThreadLock;
} }
if form.bypass_captcha.is_some() { if form.bypass_captcha.is_some() {
permissions |= Permissions::BypassCaptcha permissions |= Permissions::BypassCaptcha;
} }
updated_account updated_account

Zobrazit soubor

@ -42,5 +42,5 @@ pub async fn banners(
let template = BannersTemplate { tcx, board }; let template = BannersTemplate { tcx, board };
template_response(template) template_response(&template)
} }

Zobrazit soubor

@ -31,5 +31,5 @@ pub async fn bans(ctx: Data<Ctx>, req: HttpRequest) -> Result<HttpResponse, Nekr
let bans = Ban::read_all(&ctx).await?; let bans = Ban::read_all(&ctx).await?;
let template = BansTemplate { tcx, bans }; let template = BansTemplate { tcx, bans };
template_response(template) template_response(&template)
} }

Zobrazit soubor

@ -42,5 +42,5 @@ pub async fn board_config(
let template = BannersTemplate { tcx, board }; let template = BannersTemplate { tcx, board };
template_response(template) template_response(&template)
} }

Zobrazit soubor

@ -34,5 +34,5 @@ pub async fn boards(ctx: Data<Ctx>, req: HttpRequest) -> Result<HttpResponse, Ne
let boards = Board::read_all(&ctx).await?; let boards = Board::read_all(&ctx).await?;
let template = BoardsTemplate { tcx, boards }; let template = BoardsTemplate { tcx, boards };
template_response(template) template_response(&template)
} }

Zobrazit soubor

@ -38,5 +38,5 @@ pub async fn permissions(
let template = PermissionsTemplate { tcx, account }; let template = PermissionsTemplate { tcx, account };
template_response(template) template_response(&template)
} }

Zobrazit soubor

@ -19,5 +19,5 @@ async fn reports(ctx: Data<Ctx>, req: HttpRequest) -> Result<HttpResponse, Nekro
let tcx = TemplateCtx::new(&ctx, &req).await?; let tcx = TemplateCtx::new(&ctx, &req).await?;
let template = ReportsTemplate { tcx }; let template = ReportsTemplate { tcx };
template_response(template) template_response(&template)
} }

Zobrazit soubor

@ -24,7 +24,7 @@ pub struct TemplateCtx {
impl TemplateCtx { impl TemplateCtx {
pub async fn new(ctx: &Ctx, req: &HttpRequest) -> Result<TemplateCtx, NekrochanError> { pub async fn new(ctx: &Ctx, req: &HttpRequest) -> Result<TemplateCtx, NekrochanError> {
let cfg = ctx.cfg.to_owned(); let cfg = ctx.cfg.clone();
let boards = ctx.cache().lrange("board_ids", 0, -1).await?; let boards = ctx.cache().lrange("board_ids", 0, -1).await?;
let account = account_from_auth_opt(ctx, req).await?; let account = account_from_auth_opt(ctx, req).await?;
@ -103,11 +103,10 @@ pub fn ip_from_req(req: &HttpRequest) -> Result<(IpAddr, String), NekrochanError
// .map_err(|_| NekrochanError::HeaderError("X-Real-IP"))? // .map_err(|_| NekrochanError::HeaderError("X-Real-IP"))?
// .parse::<IpAddr>()?; // .parse::<IpAddr>()?;
let country = req let country = req.headers().get("X-Country-Code").map_or_else(
.headers() || "xx".into(),
.get("X-Country-Code") |hdr| hdr.to_str().unwrap_or("xx").to_ascii_lowercase(),
.map(|hdr| hdr.to_str().unwrap_or("xx").to_ascii_lowercase()) );
.unwrap_or_else(|| "xx".into());
Ok((ip, country)) Ok((ip, country))
} }

Zobrazit soubor

@ -55,5 +55,5 @@ pub async fn thread(
replies, replies,
}; };
template_response(template) template_response(&template)
} }