Files
sorsfonalak/services/forum/src/routes/avatars.rs
T
fecoandClaude Opus 5.5 46a2b6781e
CI / test (push) Successful in 3m9s
CI / build (push) Skipped
CI / deploy (push) Skipped
Forum: every member may upload an own avatar and ask for a conversation
- Own avatars: no longer from the Kereső rank; before the first nickname
  save the settings page says the upload comes right after it (that is why
  even an admin did not see it).
- Conversation requests: any member from the first day (a newcomers'
  limit may come back later in may_request).
- The terms (8.1, 8.4) and the docs follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 17:56:28 +00:00

200 lines
7.8 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Own avatars: any member may upload a picture instead of a starter avatar. It is cut to a square, made small (256 pixels), stripped
//! of its metadata (EXIF: camera, place) and kept in the object storage; the
//! forum serves it. A moderator can put the starter avatar back.
use std::io::Cursor;
use axum::Json;
use axum::body::Bytes;
use axum::extract::{Path, State};
use axum::http::{StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum_extra::extract::WithRejection;
use image::codecs::jpeg::JpegEncoder;
use image::imageops::FilterType;
use image::metadata::Orientation;
use image::{DynamicImage, ImageDecoder, ImageFormat, ImageReader, Limits};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use uuid::Uuid;
use super::St;
use super::moderation::{self, Action};
use crate::auth::Viewer;
use crate::error::{ApiError, ApiResult};
use crate::text;
/// The largest upload accepted, in bytes.
pub const MAX_UPLOAD: usize = 8 * 1024 * 1024;
/// The stored picture's side, in pixels.
const SIDE: u32 = 256;
const MIN_SIDE: u32 = 64;
/// The objects' folder in the bucket.
const FOLDER: &str = "forum-avatars";
pub const PREFIX: &str = "upload:";
/// A JPEG, PNG or WebP picture as an upright square JPEG of [`SIDE`] pixels.
/// The error is a message for the member.
pub fn normalize(bytes: &[u8]) -> Result<Vec<u8>, String> {
let unreadable = || "A képet nem sikerült beolvasni. JPEG, PNG vagy WebP képet tölts fel.".to_string();
let mut reader = ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|_| unreadable())?;
if !matches!(reader.format(), Some(ImageFormat::Jpeg | ImageFormat::Png | ImageFormat::WebP)) {
return Err(unreadable());
}
let mut limits = Limits::default();
limits.max_image_width = Some(12_000);
limits.max_image_height = Some(12_000);
reader.limits(limits);
let mut decoder = reader.into_decoder().map_err(|_| unreadable())?;
let orientation = decoder.orientation().unwrap_or(Orientation::NoTransforms);
let mut img = DynamicImage::from_decoder(decoder).map_err(|_| unreadable())?;
img.apply_orientation(orientation);
let side = img.width().min(img.height());
if side < MIN_SIDE {
return Err(format!("A kép túl kicsi: legalább {MIN_SIDE}×{MIN_SIDE} pixeles legyen."));
}
// The middle square, then small.
let square = img.crop_imm((img.width() - side) / 2, (img.height() - side) / 2, side, side);
let small = square.resize_exact(SIDE, SIDE, FilterType::Lanczos3);
let rgb = if small.color().has_alpha() {
// JPEG has no transparency: a transparent part turns white.
let rgba = small.to_rgba8();
image::RgbImage::from_fn(SIDE, SIDE, |x, y| {
let [r, g, b, a] = rgba.get_pixel(x, y).0;
let mix = |c: u8| ((u16::from(c) * u16::from(a) + 255 * (255 - u16::from(a))) / 255) as u8;
image::Rgb([mix(r), mix(g), mix(b)])
})
} else {
small.to_rgb8()
};
let mut jpeg = Vec::new();
JpegEncoder::new_with_quality(&mut jpeg, 85).encode_image(&rgb).map_err(|e| e.to_string())?;
Ok(jpeg)
}
/// The stored file of an `upload:` avatar, if it is one.
pub fn uploaded_file(avatar: &str) -> Option<&str> {
avatar.strip_prefix(PREFIX)
}
fn valid_file(file: &str) -> bool {
file.len() <= 80
&& file.ends_with(".jpg")
&& file.trim_end_matches(".jpg").chars().all(|c| c.is_ascii_hexdigit() || c == '-')
}
/// Removes a stored avatar (best effort: a leftover file is only storage).
pub async fn forget(state: &crate::AppState, avatar: &str) {
if let (Some(file), Some(storage)) = (uploaded_file(avatar), &state.storage)
&& let Err(e) = storage.delete(&format!("{FOLDER}/{file}")).await
{
tracing::warn!(error = %e, "removing an old avatar");
}
}
/// `PUT /v1/forum/me/avatar`: the picture's bytes as the body.
pub async fn upload(State(state): St, viewer: Viewer, body: Bytes) -> ApiResult<Json<Value>> {
let member = viewer.require_writer()?.clone();
let Some(storage) = &state.storage else {
return Err(ApiError::Forbidden("A képfeltöltés most nem érhető el.".into()));
};
if body.len() > MAX_UPLOAD {
return Err(ApiError::bad("A kép legfeljebb 8 MB lehet."));
}
let bytes = body.to_vec();
let jpeg = tokio::task::spawn_blocking(move || normalize(&bytes))
.await
.map_err(|e| ApiError::Internal(e.to_string()))?
.map_err(ApiError::BadRequest)?;
let hash: String = Sha256::digest(&jpeg).iter().take(6).map(|b| format!("{b:02x}")).collect();
let file = format!("{}-{hash}.jpg", member.user_id.simple());
storage
.put(&format!("{FOLDER}/{file}"), jpeg, "image/jpeg")
.await
.map_err(|e| ApiError::Internal(format!("storing an avatar: {e}")))?;
let avatar = format!("{PREFIX}{file}");
sqlx::query("UPDATE forum.members SET avatar = $2 WHERE user_id = $1")
.bind(member.user_id)
.bind(&avatar)
.execute(&state.db)
.await?;
if member.avatar != avatar {
forget(&state, &member.avatar).await;
}
Ok(Json(json!({ "avatar": avatar })))
}
/// `GET /v1/forum/avatars/{file}`: a stored avatar (its name changes with
/// its content, so it is cached for good).
pub async fn serve(
State(state): St,
WithRejection(Path(file), _): WithRejection<Path<String>, ApiError>,
) -> ApiResult<Response> {
if !valid_file(&file) {
return Err(ApiError::NotFound("avatar"));
}
let storage = state.storage.as_ref().ok_or(ApiError::NotFound("avatar"))?;
let object = storage
.get(&format!("{FOLDER}/{file}"))
.await
.map_err(|e| ApiError::Internal(format!("reading an avatar: {e}")))?
.ok_or(ApiError::NotFound("avatar"))?;
Ok((
[(header::CONTENT_TYPE, "image/jpeg"), (header::CACHE_CONTROL, "public, max-age=31536000, immutable")],
object.bytes,
)
.into_response())
}
/// A moderator puts back the starter avatar (an unfit picture).
pub async fn reset(
State(state): St,
viewer: Viewer,
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
) -> ApiResult<StatusCode> {
let moderator = viewer.require_moderator()?;
let key = text::nickname_key(&nickname);
let found: Option<(Uuid, String)> =
sqlx::query_as("SELECT user_id, avatar FROM forum.members WHERE nickname_key = $1")
.bind(&key)
.fetch_optional(&state.db)
.await?;
let (user, avatar) = found.ok_or(ApiError::NotFound("member"))?;
if uploaded_file(&avatar).is_none() {
return Ok(StatusCode::NO_CONTENT);
}
let mut tx = state.db.begin().await?;
sqlx::query("UPDATE forum.members SET avatar = $2 WHERE user_id = $1")
.bind(user)
.bind(text::default_avatar(&key))
.execute(&mut *tx)
.await?;
moderation::record(&mut *tx, moderator.id, Action::ResetAvatar, Some(user), None, None, None, None).await?;
tx.commit().await?;
forget(&state, &avatar).await;
Ok(StatusCode::NO_CONTENT)
}
#[cfg(test)]
mod tests {
use super::*;
fn png(width: u32, height: u32) -> Vec<u8> {
let img =
DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(width, height, image::Rgba([200, 100, 50, 255])));
let mut out = Vec::new();
img.write_to(&mut Cursor::new(&mut out), ImageFormat::Png).unwrap();
out
}
#[test]
fn makes_a_small_square_jpeg() {
let jpeg = normalize(&png(900, 400)).unwrap();
let back = image::load_from_memory(&jpeg).unwrap();
assert_eq!((back.width(), back.height()), (SIDE, SIDE));
assert!(normalize(&png(40, 40)).unwrap_err().contains("túl kicsi"));
assert!(normalize(b"GIF89a\x01\x00\x01\x00\x00\x00\x00;").is_err());
assert!(valid_file("0190aa-3f2a1b.jpg") && !valid_file("../x.jpg") && !valid_file("a.png"));
}
}