Forum photos, a one-row bottom menu, and the site's own question windows
Photos in posts and replies: a "Fotó" button in the new thread form and the reply boxes. The browser makes the picture small before uploading it (1600 pixels at most, WebP, JPEG where WebP cannot be made); the forum checks it is a still picture, strips its metadata and makes a square preview (forum-photos/ in the storage). Five a member a day, five a post; one taken off before sending is deleted and does not count. Under the post a row of square previews; a click opens a viewer paged with arrows, swipes and keys. Seen by whoever may read the thread (long public cache only for public topics). Unsent photos go after a day, those of removed posts after a year; removed with the account and listed in the data export. Terms and privacy notice updated. The forum's bottom menu keeps its five items in one row (the fifth wrapped to a second row). On iPhones, when the keyboard goes away without the usual tap (a photo picker opening over it), the page is put back in place instead of the menu floating mid-screen over an empty strip. The browser's own confirm() and prompt() windows (23 places: deleting, revoking, blocking, muting, moderators' reasons, admin actions) are replaced by a question window in the site's look, following the forum's light or dark theme, with named buttons and a text box for reasons. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -13,6 +13,7 @@ mod mentions;
|
||||
mod messages;
|
||||
mod moderation;
|
||||
mod mutes;
|
||||
mod photos;
|
||||
mod posts;
|
||||
mod replies;
|
||||
mod reports;
|
||||
@@ -42,6 +43,8 @@ pub type Body<T> = WithRejection<Json<T>, ApiError>;
|
||||
pub type IdPath = WithRejection<Path<i64>, ApiError>;
|
||||
pub type St = State<Arc<AppState>>;
|
||||
|
||||
pub use photos::cleanup as photo_cleanup;
|
||||
|
||||
pub fn router(state: Arc<AppState>) -> Router {
|
||||
Router::new()
|
||||
.route("/healthz", get(health))
|
||||
@@ -85,6 +88,11 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
put(avatars::upload).layer(axum::extract::DefaultBodyLimit::max(avatars::MAX_UPLOAD + 1024)),
|
||||
)
|
||||
.route("/v1/forum/avatars/{file}", get(avatars::serve))
|
||||
.route(
|
||||
"/v1/forum/photos",
|
||||
post(photos::upload).layer(axum::extract::DefaultBodyLimit::max(photos::MAX_UPLOAD + 1024)),
|
||||
)
|
||||
.route("/v1/forum/photos/{file}", get(photos::serve).delete(photos::discard))
|
||||
.route("/v1/forum/members/{nickname}/avatar-reset", post(avatars::reset))
|
||||
.route("/v1/forum/nickname-check", get(members::nickname_check))
|
||||
.route("/v1/forum/presence", post(members::presence))
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
//! Photos in posts. The browser makes the picture small (1600 pixels at
|
||||
//! most, WebP, or JPEG where it cannot make WebP) before it uploads it; the
|
||||
//! forum checks that it is a real still picture, strips its metadata (camera,
|
||||
//! place) and makes a square JPEG preview. A member uploads at most
|
||||
//! [`DAILY`] in a day; a photo uploaded first is attached when the post is
|
||||
//! sent ([`attach`]), and one left unattached goes after a day ([`cleanup`]).
|
||||
//! A photo is shown to whoever may read its post: from a public topic with a
|
||||
//! long public cache, otherwise privately.
|
||||
|
||||
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::{DynamicImage, ImageFormat, ImageReader, Limits};
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::St;
|
||||
use crate::AppState;
|
||||
use crate::auth::Viewer;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
|
||||
/// Photos a member may upload in a day (rolling 24 hours).
|
||||
pub const DAILY: i64 = 5;
|
||||
/// Photos under one post.
|
||||
pub const PER_POST: usize = 5;
|
||||
/// The largest upload accepted (already made small by the browser).
|
||||
pub const MAX_UPLOAD: usize = 4 * 1024 * 1024;
|
||||
/// The longest side accepted, in pixels.
|
||||
const MAX_SIDE: u32 = 2560;
|
||||
const MIN_SIDE: u32 = 32;
|
||||
/// The square preview's side.
|
||||
const THUMB: u32 = 360;
|
||||
const FOLDER: &str = "forum-photos";
|
||||
|
||||
/// A checked picture: the bytes to keep, their kind, and the decoded image.
|
||||
struct Checked {
|
||||
bytes: Vec<u8>,
|
||||
extension: &'static str,
|
||||
content_type: &'static str,
|
||||
image: DynamicImage,
|
||||
}
|
||||
|
||||
/// A WebP without its metadata chunks (EXIF, XMP, ICC profile); `None` for an
|
||||
/// animation or a broken container.
|
||||
fn strip_webp(bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
if bytes.len() < 12 || &bytes[0..4] != b"RIFF" || &bytes[8..12] != b"WEBP" {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
out.extend_from_slice(b"RIFF\0\0\0\0WEBP");
|
||||
let mut at = 12;
|
||||
while at + 8 <= bytes.len() {
|
||||
let fourcc = &bytes[at..at + 4];
|
||||
let size = u32::from_le_bytes(bytes[at + 4..at + 8].try_into().ok()?) as usize;
|
||||
let end = at.checked_add(8)?.checked_add(size)?;
|
||||
if end > bytes.len() {
|
||||
return None;
|
||||
}
|
||||
let padded = end + (size & 1);
|
||||
match fourcc {
|
||||
b"ANIM" | b"ANMF" => return None,
|
||||
b"EXIF" | b"XMP " | b"ICCP" => {}
|
||||
b"VP8X" => {
|
||||
let mut chunk = bytes[at..end].to_vec();
|
||||
// Flags: ICC (0x20), EXIF (0x08), XMP (0x04) off; animation (0x02) means no.
|
||||
if chunk.len() > 8 {
|
||||
if chunk[8] & 0x02 != 0 {
|
||||
return None;
|
||||
}
|
||||
chunk[8] &= !(0x20 | 0x08 | 0x04);
|
||||
}
|
||||
out.extend_from_slice(&chunk);
|
||||
}
|
||||
_ => out.extend_from_slice(&bytes[at..end]),
|
||||
}
|
||||
if padded > end && padded <= bytes.len() {
|
||||
out.push(0);
|
||||
}
|
||||
at = padded;
|
||||
}
|
||||
let riff = u32::try_from(out.len() - 8).ok()?;
|
||||
out[4..8].copy_from_slice(&riff.to_le_bytes());
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// A WebP or JPEG still picture of a sensible size, without its metadata.
|
||||
/// The error is a message for the member.
|
||||
fn check(bytes: &[u8]) -> Result<Checked, String> {
|
||||
let unreadable = || "A képet nem sikerült feldolgozni. JPEG, PNG vagy WebP képet válassz.".to_string();
|
||||
let reader = ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|_| unreadable())?;
|
||||
let format = reader.format();
|
||||
let mut reader = reader;
|
||||
let mut limits = Limits::default();
|
||||
limits.max_image_width = Some(MAX_SIDE);
|
||||
limits.max_image_height = Some(MAX_SIDE);
|
||||
reader.limits(limits);
|
||||
let image = reader.decode().map_err(|_| "A kép túl nagy vagy sérült.".to_string())?;
|
||||
if image.width() < MIN_SIDE || image.height() < MIN_SIDE {
|
||||
return Err("A kép túl kicsi.".into());
|
||||
}
|
||||
match format {
|
||||
Some(ImageFormat::WebP) => {
|
||||
let bytes = strip_webp(bytes).ok_or_else(|| "Mozgó képet nem lehet feltölteni.".to_string())?;
|
||||
Ok(Checked { bytes, extension: "webp", content_type: "image/webp", image })
|
||||
}
|
||||
// A JPEG (or a PNG from an older browser) is written again: no metadata survives.
|
||||
Some(ImageFormat::Jpeg | ImageFormat::Png) => {
|
||||
let rgb = image.to_rgb8();
|
||||
let mut out = Vec::new();
|
||||
JpegEncoder::new_with_quality(&mut out, 84).encode_image(&rgb).map_err(|_| unreadable())?;
|
||||
Ok(Checked {
|
||||
bytes: out,
|
||||
extension: "jpg",
|
||||
content_type: "image/jpeg",
|
||||
image: DynamicImage::ImageRgb8(rgb),
|
||||
})
|
||||
}
|
||||
_ => Err(unreadable()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The middle square, small, as JPEG.
|
||||
fn preview(image: &DynamicImage) -> Result<Vec<u8>, String> {
|
||||
let side = image.width().min(image.height());
|
||||
let square = image.crop_imm((image.width() - side) / 2, (image.height() - side) / 2, side, side);
|
||||
let small = square.resize_exact(THUMB, THUMB, FilterType::Triangle).to_rgb8();
|
||||
let mut out = Vec::new();
|
||||
JpegEncoder::new_with_quality(&mut out, 80).encode_image(&small).map_err(|e| e.to_string())?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn photo_json(id: Uuid, file: &str, thumb: &str, width: i32, height: i32) -> Value {
|
||||
json!({
|
||||
"id": id,
|
||||
"url": format!("/api/v1/forum/photos/{file}"),
|
||||
"thumb": format!("/api/v1/forum/photos/{thumb}"),
|
||||
"width": width,
|
||||
"height": height,
|
||||
})
|
||||
}
|
||||
|
||||
/// `POST /v1/forum/photos`: a picture (the body), resized by the browser.
|
||||
pub async fn upload(State(state): St, viewer: Viewer, body: Bytes) -> ApiResult<(StatusCode, 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()));
|
||||
};
|
||||
let today: i64 = sqlx::query_scalar(
|
||||
"SELECT count(*) FROM forum.photos WHERE owner_id = $1 AND created_at > now() - interval '1 day'",
|
||||
)
|
||||
.bind(member.user_id)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
if today >= DAILY {
|
||||
return Err(ApiError::Limited(format!("Naponta legfeljebb {DAILY} fotót tölthetsz fel. Holnap újra lehet.")));
|
||||
}
|
||||
if body.len() > MAX_UPLOAD {
|
||||
return Err(ApiError::bad("A kép túl nagy."));
|
||||
}
|
||||
let bytes = body.to_vec();
|
||||
let (checked, thumb) = tokio::task::spawn_blocking(move || {
|
||||
let checked = check(&bytes)?;
|
||||
let thumb = preview(&checked.image)?;
|
||||
Ok::<_, String>((checked, thumb))
|
||||
})
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(e.to_string()))?
|
||||
.map_err(ApiError::BadRequest)?;
|
||||
let id = Uuid::now_v7();
|
||||
let file = format!("{}.{}", id.simple(), checked.extension);
|
||||
let thumb_file = format!("{}-t.jpg", id.simple());
|
||||
storage
|
||||
.put(&format!("{FOLDER}/{file}"), checked.bytes.clone(), checked.content_type)
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("storing a photo: {e}")))?;
|
||||
storage
|
||||
.put(&format!("{FOLDER}/{thumb_file}"), thumb, "image/jpeg")
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("storing a photo preview: {e}")))?;
|
||||
let (width, height) = (checked.image.width() as i32, checked.image.height() as i32);
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.photos (id, owner_id, file, thumb, width, height, bytes) VALUES ($1, $2, $3, $4, $5, $6, $7)",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(member.user_id)
|
||||
.bind(&file)
|
||||
.bind(&thumb_file)
|
||||
.bind(width)
|
||||
.bind(height)
|
||||
.bind(checked.bytes.len() as i32)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
let mut out = photo_json(id, &file, &thumb_file, width, height);
|
||||
out["remaining"] = json!(DAILY - today - 1);
|
||||
Ok((StatusCode::CREATED, Json(out)))
|
||||
}
|
||||
|
||||
/// `DELETE /v1/forum/photos/{id}`: a photo taken off before the post was sent;
|
||||
/// it does not count in the day's five.
|
||||
pub async fn discard(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): WithRejection<Path<Uuid>, ApiError>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let member = viewer.require_writer()?.clone();
|
||||
let files: Option<(String, String)> = sqlx::query_as(
|
||||
"DELETE FROM forum.photos WHERE id = $1 AND owner_id = $2 AND post_id IS NULL RETURNING file, thumb",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(member.user_id)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let (file, thumb) = files.ok_or(ApiError::NotFound("photo"))?;
|
||||
if let Some(storage) = &state.storage {
|
||||
for name in [file, thumb] {
|
||||
if let Err(e) = storage.delete(&format!("{FOLDER}/{name}")).await {
|
||||
tracing::warn!(error = %e, "removing a discarded photo");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
/// Attaches the member's uploaded photos to their new post (in its transaction).
|
||||
pub async fn attach(tx: &mut sqlx::PgConnection, owner: Uuid, post: i64, photos: &[Uuid]) -> Result<(), ApiError> {
|
||||
if photos.len() > PER_POST {
|
||||
return Err(ApiError::bad(format!("Egy hozzászóláshoz legfeljebb {PER_POST} fotó tartozhat.")));
|
||||
}
|
||||
if photos.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
sqlx::query("UPDATE forum.photos SET post_id = $3 WHERE id = ANY($1) AND owner_id = $2 AND post_id IS NULL")
|
||||
.bind(photos)
|
||||
.bind(owner)
|
||||
.bind(post)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The photos of these posts, in upload order.
|
||||
pub async fn of_posts(db: &PgPool, posts: &[i64]) -> Result<std::collections::HashMap<i64, Vec<Value>>, sqlx::Error> {
|
||||
let mut out: std::collections::HashMap<i64, Vec<Value>> = Default::default();
|
||||
if posts.is_empty() {
|
||||
return Ok(out);
|
||||
}
|
||||
let rows: Vec<(i64, Uuid, String, String, i32, i32)> = sqlx::query_as(
|
||||
"SELECT post_id, id, file, thumb, width, height FROM forum.photos \
|
||||
WHERE post_id = ANY($1) ORDER BY created_at",
|
||||
)
|
||||
.bind(posts)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
for (post, id, file, thumb, width, height) in rows {
|
||||
out.entry(post).or_default().push(photo_json(id, &file, &thumb, width, height));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct Served {
|
||||
owner_id: Uuid,
|
||||
post_id: Option<i64>,
|
||||
}
|
||||
|
||||
/// `GET /v1/forum/photos/{file}`: a photo or its preview, to whoever may read its post.
|
||||
pub async fn serve(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(file), _): WithRejection<Path<String>, ApiError>,
|
||||
) -> ApiResult<Response> {
|
||||
let valid = file.len() <= 48 && file.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.'));
|
||||
if !valid {
|
||||
return Err(ApiError::NotFound("photo"));
|
||||
}
|
||||
let row: Served = sqlx::query_as("SELECT owner_id, post_id FROM forum.photos WHERE file = $1 OR thumb = $1")
|
||||
.bind(&file)
|
||||
.fetch_optional(&state.db)
|
||||
.await?
|
||||
.ok_or(ApiError::NotFound("photo"))?;
|
||||
// Who may see it: the uploader before it is sent; afterwards whoever may read the post.
|
||||
let public = match row.post_id {
|
||||
None if viewer.user_id() == Some(row.owner_id) => false,
|
||||
None => return Err(ApiError::NotFound("photo")),
|
||||
Some(post) => {
|
||||
let (thread, deleted): (i64, bool) =
|
||||
sqlx::query_as("SELECT thread_id, deleted_at IS NOT NULL FROM forum.posts WHERE id = $1")
|
||||
.bind(post)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
if deleted && !viewer.is_moderator() {
|
||||
return Err(ApiError::NotFound("photo"));
|
||||
}
|
||||
let thread = super::threads::readable_thread(&state.db, &viewer, thread)
|
||||
.await
|
||||
.map_err(|_| ApiError::NotFound("photo"))?;
|
||||
thread.deleted_at.is_none() && thread.visibility == "public" && !deleted
|
||||
}
|
||||
};
|
||||
let storage = state.storage.as_ref().ok_or(ApiError::NotFound("photo"))?;
|
||||
let object = storage
|
||||
.get(&format!("{FOLDER}/{file}"))
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("reading a photo: {e}")))?
|
||||
.ok_or(ApiError::NotFound("photo"))?;
|
||||
let content_type = if file.ends_with(".webp") { "image/webp" } else { "image/jpeg" };
|
||||
let cache = if public { "public, max-age=31536000, immutable" } else { "private, max-age=3600" };
|
||||
Ok(([(header::CONTENT_TYPE, content_type), (header::CACHE_CONTROL, cache)], object.bytes).into_response())
|
||||
}
|
||||
|
||||
/// Every hour: unattached photos older than a day, and the photos of posts
|
||||
/// removed more than a year ago, leave the storage and the table.
|
||||
pub async fn cleanup(state: &AppState) -> anyhow::Result<u64> {
|
||||
let Some(storage) = &state.storage else { return Ok(0) };
|
||||
let gone: Vec<(Uuid, String, String)> = sqlx::query_as(
|
||||
"SELECT ph.id, ph.file, ph.thumb FROM forum.photos ph LEFT JOIN forum.posts p ON p.id = ph.post_id \
|
||||
WHERE (ph.post_id IS NULL AND ph.created_at < now() - interval '1 day') \
|
||||
OR (p.deleted_at IS NOT NULL AND p.deleted_at < now() - interval '1 year') \
|
||||
LIMIT 500",
|
||||
)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
for (id, file, thumb) in &gone {
|
||||
for name in [file, thumb] {
|
||||
if let Err(e) = storage.delete(&format!("{FOLDER}/{name}")).await {
|
||||
tracing::warn!(error = %e, "removing a photo");
|
||||
}
|
||||
}
|
||||
sqlx::query("DELETE FROM forum.photos WHERE id = $1").bind(id).execute(&state.db).await?;
|
||||
}
|
||||
Ok(gone.len() as u64)
|
||||
}
|
||||
@@ -117,6 +117,9 @@ pub async fn posts_json(db: &PgPool, viewer: &Viewer, posts: &[PostRow]) -> ApiR
|
||||
let texts: Vec<(i64, &str)> =
|
||||
posts.iter().filter(|p| p.deleted_at.is_none()).map(|p| (p.id, p.body.as_str())).collect();
|
||||
let previews = crate::links::previews(db, &texts).await?;
|
||||
let shown: Vec<i64> =
|
||||
posts.iter().filter(|p| p.deleted_at.is_none() || viewer.is_moderator()).map(|p| p.id).collect();
|
||||
let photos = super::photos::of_posts(db, &shown).await?;
|
||||
let counts: Vec<(i64, String, i64)> =
|
||||
sqlx::query_as("SELECT post_id, kind, count(*) FROM forum.reactions WHERE post_id = ANY($1) GROUP BY 1, 2")
|
||||
.bind(&ids)
|
||||
@@ -197,6 +200,7 @@ pub async fn posts_json(db: &PgPool, viewer: &Viewer, posts: &[PostRow]) -> ApiR
|
||||
"share": p.share_id.and_then(|id| cards.get(&id).cloned()),
|
||||
// Previews of the links a provider knows (YouTube).
|
||||
"links": previews.get(&p.id),
|
||||
"photos": photos.get(&p.id),
|
||||
});
|
||||
if moderator {
|
||||
post["down"] = json!(down);
|
||||
@@ -328,6 +332,9 @@ pub struct CreateThread {
|
||||
/// A share made for the forum on the main site (`/s/<slug>`).
|
||||
#[serde(default)]
|
||||
share: Option<String>,
|
||||
/// Photos uploaded for the opening post.
|
||||
#[serde(default)]
|
||||
photos: Vec<Uuid>,
|
||||
}
|
||||
|
||||
/// Starts a thread with its opening post; the author follows it.
|
||||
@@ -382,6 +389,7 @@ pub async fn create(
|
||||
.bind(share)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
super::photos::attach(&mut tx, member.user_id, post_id, &req.photos).await?;
|
||||
after_post(&mut tx, member.user_id, thread_id, post_id).await?;
|
||||
tx.commit().await?;
|
||||
tracing::info!(thread = thread_id, topic = %req.topic, "thread started");
|
||||
@@ -436,6 +444,9 @@ pub struct Reply {
|
||||
/// post (two levels at most), a reply to the opening post is first-level.
|
||||
#[serde(default)]
|
||||
parent_id: Option<i64>,
|
||||
/// Photos uploaded for the reply.
|
||||
#[serde(default)]
|
||||
photos: Vec<Uuid>,
|
||||
}
|
||||
|
||||
pub async fn reply(
|
||||
@@ -486,6 +497,7 @@ pub async fn reply(
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
super::photos::attach(&mut tx, member.user_id, post.id, &req.photos).await?;
|
||||
after_post(&mut tx, member.user_id, id, post.id).await?;
|
||||
tx.commit().await?;
|
||||
// The one answered hears of it (on the second level, not the branch's first post).
|
||||
|
||||
Reference in New Issue
Block a user