simplify code

This commit is contained in:
Felix Ableitner 2024-12-18 11:24:30 +01:00
parent 460ccc8e5a
commit 5f0619534e
4 changed files with 26 additions and 32 deletions

View file

@ -11,7 +11,7 @@ killall -s1 lemmy_server || true
popd popd
pnpm i pnpm i
pnpm api-test || true pnpm api-test-image || true
killall -s1 lemmy_server || true killall -s1 lemmy_server || true
killall -s1 pict-rs || true killall -s1 pict-rs || true

View file

@ -3,7 +3,7 @@ use actix_web::{self, web::*, HttpRequest};
use lemmy_api_common::{ use lemmy_api_common::{
context::LemmyContext, context::LemmyContext,
image::UploadImageResponse, image::UploadImageResponse,
request::{PictrsFile, PictrsResponse}, request::PictrsResponse,
LemmyErrorType, LemmyErrorType,
SuccessResponse, SuccessResponse,
}; };
@ -18,7 +18,12 @@ use lemmy_db_views::structs::LocalUserView;
use lemmy_utils::error::LemmyResult; use lemmy_utils::error::LemmyResult;
use reqwest::Body; use reqwest::Body;
use std::time::Duration; use std::time::Duration;
use url::Url; use UploadType::*;
pub enum UploadType {
Avatar,
Other,
}
pub async fn upload_image( pub async fn upload_image(
req: HttpRequest, req: HttpRequest,
@ -30,45 +35,28 @@ pub async fn upload_image(
return Err(LemmyErrorType::ImageUploadDisabled.into()); return Err(LemmyErrorType::ImageUploadDisabled.into());
} }
let image = do_upload_image(req, body, UploadType::Other, &local_user_view, &context).await?; Ok(Json(
do_upload_image(req, body, Other, &local_user_view, &context).await?,
let image_url = image.image_url(&context.settings().get_protocol_and_hostname())?; ))
Ok(Json(UploadImageResponse {
image_url,
filename: image.file,
delete_token: image.delete_token,
}))
} }
pub async fn upload_avatar( pub async fn upload_user_avatar(
req: HttpRequest, req: HttpRequest,
body: Payload, body: Payload,
local_user_view: LocalUserView, local_user_view: LocalUserView,
context: Data<LemmyContext>, context: Data<LemmyContext>,
) -> LemmyResult<Json<SuccessResponse>> { ) -> LemmyResult<Json<SuccessResponse>> {
let image = do_upload_image(req, body, UploadType::Avatar, &local_user_view, &context).await?; let image = do_upload_image(req, body, Avatar, &local_user_view, &context).await?;
delete_old_image(&local_user_view.person.avatar, &context).await?; delete_old_image(&local_user_view.person.avatar, &context).await?;
let avatar = format!(
"{}/api/v4/image/{}",
context.settings().get_protocol_and_hostname(),
image.file
);
let avatar = Some(Some(Url::parse(&avatar)?.into()));
let person_form = PersonUpdateForm { let person_form = PersonUpdateForm {
avatar, avatar: Some(Some(image.image_url.into())),
..Default::default() ..Default::default()
}; };
Person::update(&mut context.pool(), local_user_view.person.id, &person_form).await?; Person::update(&mut context.pool(), local_user_view.person.id, &person_form).await?;
Ok(Json(SuccessResponse::default())) Ok(Json(SuccessResponse::default()))
} }
pub enum UploadType {
Avatar,
Other,
}
pub async fn do_upload_image( pub async fn do_upload_image(
req: HttpRequest, req: HttpRequest,
@ -76,14 +64,14 @@ pub async fn do_upload_image(
upload_type: UploadType, upload_type: UploadType,
local_user_view: &LocalUserView, local_user_view: &LocalUserView,
context: &Data<LemmyContext>, context: &Data<LemmyContext>,
) -> LemmyResult<PictrsFile> { ) -> LemmyResult<UploadImageResponse> {
let pictrs_config = context.settings().pictrs()?; let pictrs_config = context.settings().pictrs()?;
let image_url = format!("{}image", pictrs_config.url); let image_url = format!("{}image", pictrs_config.url);
let mut client_req = adapt_request(&req, image_url); let mut client_req = adapt_request(&req, image_url);
client_req = match upload_type { client_req = match upload_type {
UploadType::Avatar => { Avatar => {
let max_size = context.settings().pictrs()?.max_avatar_size.to_string(); let max_size = context.settings().pictrs()?.max_avatar_size.to_string();
client_req.query(&[ client_req.query(&[
("resize", max_size.as_ref()), ("resize", max_size.as_ref()),
@ -92,7 +80,7 @@ pub async fn do_upload_image(
]) ])
} }
// TODO: same as above but using `max_banner_size` // TODO: same as above but using `max_banner_size`
// UploadType::Banner => {} // Banner => {}
_ => client_req, _ => client_req,
}; };
if let Some(addr) = req.head().peer_addr { if let Some(addr) = req.head().peer_addr {
@ -128,5 +116,10 @@ pub async fn do_upload_image(
.pop() .pop()
.ok_or(LemmyErrorType::InvalidImageUpload)?; .ok_or(LemmyErrorType::InvalidImageUpload)?;
Ok(image) let url = image.image_url(&context.settings().get_protocol_and_hostname())?;
Ok(UploadImageResponse {
image_url: url,
filename: image.file,
delete_token: image.delete_token,
})
} }

View file

@ -114,6 +114,7 @@ pub struct PictrsConfig {
/// TODO: Unfortunately pictrs can only resize images to fit in a*a square, no rectangle. /// TODO: Unfortunately pictrs can only resize images to fit in a*a square, no rectangle.
/// Otherwise we have to use crop, or use max_width/max_height which throws error /// Otherwise we have to use crop, or use max_width/max_height which throws error
/// if image is larger. /// if image is larger.
/// TODO: whats a sensible default here?
#[default(512)] #[default(512)]
pub max_banner_size: u32, pub max_banner_size: u32,

View file

@ -162,7 +162,7 @@ use lemmy_routes::images::{
delete_image, delete_image,
download::{get_image, image_proxy}, download::{get_image, image_proxy},
pictrs_health, pictrs_health,
upload::{upload_avatar, upload_image}, upload::{upload_image, upload_user_avatar},
}; };
use lemmy_utils::rate_limit::RateLimitCell; use lemmy_utils::rate_limit::RateLimitCell;
@ -319,7 +319,7 @@ pub fn config(cfg: &mut ServiceConfig, rate_limit: &RateLimitCell) {
.route("/unread_count", get().to(unread_count)) .route("/unread_count", get().to(unread_count))
.route("/list_logins", get().to(list_logins)) .route("/list_logins", get().to(list_logins))
.route("/validate_auth", get().to(validate_auth)) .route("/validate_auth", get().to(validate_auth))
.route("/avatar", post().to(upload_avatar)) .route("/avatar", post().to(upload_user_avatar))
.service( .service(
scope("/block") scope("/block")
.route("/person", post().to(user_block_person)) .route("/person", post().to(user_block_person))