Forum photos, a one-row bottom menu, and the site's own question windows
CI / test (push) Successful in 3m10s
CI / build (push) Skipped
CI / deploy (push) Skipped

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:
feco
2026-11-27 00:34:59 +00:00
co-authored by Claude Opus 5.5
parent 758c3ce7ea
commit de629a068d
38 changed files with 1536 additions and 92 deletions
+229 -1
View File
@@ -35,17 +35,40 @@ impl TestApp {
/// With the link providers at these (fake) addresses.
fn with_links(pool: PgPool, links: crate::links::LinkConfig) -> Self {
Self::with_parts(pool, links, None)
}
fn with_parts(pool: PgPool, links: crate::links::LinkConfig, storage: Option<object_storage::Storage>) -> Self {
let state = AppState {
db: pool.clone(),
flood_secs: 0,
base_url: "https://sorsfonalak.test".into(),
hub: crate::live::Hub::default(),
storage: None,
storage,
links,
};
Self { router: routes::router(Arc::new(state)), pool }
}
/// A raw request (an uploaded picture); status, headers and the body as bytes.
async fn raw(
&self,
method: &str,
uri: &str,
user: Option<&User>,
content_type: &str,
body: Vec<u8>,
) -> (StatusCode, axum::http::HeaderMap, Vec<u8>) {
let mut req = Request::builder().method(method).uri(uri).header("content-type", content_type);
if let Some(u) = user {
req = req.header("authorization", format!("Bearer {}", u.token));
}
let res = self.router.clone().oneshot(req.body(Body::from(body)).unwrap()).await.unwrap();
let (status, headers) = (res.status(), res.headers().clone());
let bytes = res.into_body().collect().await.unwrap().to_bytes().to_vec();
(status, headers, bytes)
}
/// A user with a session, as after a login in the backend.
async fn user(&self, email: &str, roles: &[&str]) -> User {
let id = Uuid::now_v7();
@@ -1436,3 +1459,208 @@ async fn latest_threads_with_their_beginning(pool: PgPool) {
let home = app.get("/v1/forum/home", None).await;
assert_eq!(home["pinned"][0]["id"], public);
}
/// An in-memory S3 bucket for the photo tests.
async fn fake_s3() -> object_storage::StorageConfig {
type Store = Arc<std::sync::Mutex<std::collections::HashMap<String, (String, Vec<u8>)>>>;
let store: Store = Default::default();
async fn handle(
axum::extract::State(store): axum::extract::State<Store>,
method: axum::http::Method,
headers: axum::http::HeaderMap,
axum::extract::Path(key): axum::extract::Path<String>,
body: axum::body::Bytes,
) -> axum::response::Response {
use axum::response::IntoResponse;
let mut store = store.lock().unwrap();
match method.as_str() {
"PUT" => {
let ct = headers.get("content-type").and_then(|v| v.to_str().ok()).unwrap_or_default().to_string();
store.insert(key, (ct, body.to_vec()));
StatusCode::OK.into_response()
}
"GET" => match store.get(&key) {
Some((ct, bytes)) => ([("content-type", ct.clone())], bytes.clone()).into_response(),
None => StatusCode::NOT_FOUND.into_response(),
},
"DELETE" => {
store.remove(&key);
StatusCode::NO_CONTENT.into_response()
}
_ => StatusCode::METHOD_NOT_ALLOWED.into_response(),
}
}
let app = Router::new().route("/photos/{*key}", axum::routing::any(handle)).with_state(store);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
object_storage::StorageConfig {
endpoint: format!("http://{addr}"),
bucket: "photos".into(),
region: "us-east-1".into(),
access_key: "test-key".into(),
secret_key: "test-secret".into(),
}
}
/// A made-up 800×600 picture as JPEG with an EXIF block hiding a "place".
fn jpeg_with_exif() -> Vec<u8> {
let img = image::RgbImage::from_fn(800, 600, |x, y| image::Rgb([(x % 256) as u8, (y % 256) as u8, 120]));
let mut jpeg = Vec::new();
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 80).encode_image(&img).unwrap();
let mut exif = b"Exif\0\0GPSSECRET-47.49N-19.04E".to_vec();
let len = (exif.len() + 2) as u16;
let mut out = vec![0xFF, 0xD8, 0xFF, 0xE1];
out.extend_from_slice(&len.to_be_bytes());
out.append(&mut exif);
out.extend_from_slice(&jpeg[2..]);
out
}
/// A made-up picture as an extended WebP with an EXIF chunk.
fn webp_with_exif() -> Vec<u8> {
let img = image::RgbImage::from_fn(640, 480, |x, y| image::Rgb([(y % 256) as u8, 90, (x % 256) as u8]));
let mut simple = Vec::new();
image::codecs::webp::WebPEncoder::new_lossless(&mut simple)
.encode(img.as_raw(), 640, 480, image::ExtendedColorType::Rgb8)
.unwrap();
let chunk = |fourcc: &[u8], data: &[u8]| {
let mut c = fourcc.to_vec();
c.extend_from_slice(&(data.len() as u32).to_le_bytes());
c.extend_from_slice(data);
if data.len() % 2 == 1 {
c.push(0);
}
c
};
let mut vp8x = vec![0x08, 0, 0, 0];
vp8x.extend_from_slice(&(639u32).to_le_bytes()[..3]);
vp8x.extend_from_slice(&(479u32).to_le_bytes()[..3]);
let mut body = b"WEBP".to_vec();
body.extend(chunk(b"VP8X", &vp8x));
body.extend_from_slice(&simple[12..]);
body.extend(chunk(b"EXIF", b"GPSSECRET-47.49N-19.04E"));
let mut out = b"RIFF".to_vec();
out.extend_from_slice(&(body.len() as u32).to_le_bytes());
out.extend(body);
out
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn photos_in_posts(pool: PgPool) {
let storage = fake_s3().await;
let app = TestApp::with_parts(
pool.clone(),
crate::links::LinkConfig::new("http://127.0.0.1:9/oembed", "http://127.0.0.1:9"),
Some(object_storage::Storage::new(storage.clone())),
);
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
let bea = app.member("bea@example.com", "Holdfény", &["user"]).await;
let upload = |user: &User, ct: &str, body: Vec<u8>| {
let user = User { id: user.id, token: user.token.clone() };
let ct = ct.to_string();
let app = &app;
async move {
let (status, _, body) = app.raw("POST", "/v1/forum/photos", Some(&user), &ct, body).await;
(status, serde_json::from_slice::<Value>(&body).unwrap_or(Value::Null))
}
};
// A JPEG and a WebP: kept without their metadata, with a square preview.
let (status, jpeg) = upload(&anna, "image/jpeg", jpeg_with_exif()).await;
assert_eq!(status, StatusCode::CREATED, "{jpeg}");
assert_eq!(
(jpeg["width"].as_i64(), jpeg["height"].as_i64(), jpeg["remaining"].as_i64()),
(Some(800), Some(600), Some(4))
);
let (status, webp) = upload(&anna, "image/webp", webp_with_exif()).await;
assert_eq!(status, StatusCode::CREATED, "{webp}");
let path = |url: &Value| url.as_str().unwrap().trim_start_matches("/api").to_string();
for photo in [&jpeg, &webp] {
let (status, headers, bytes) = app.raw("GET", &path(&photo["url"]), Some(&anna), "", Vec::new()).await;
assert_eq!(status, StatusCode::OK);
assert!(!bytes.windows(9).any(|w| w == b"GPSSECRET"), "metadata must go");
image::load_from_memory(&bytes).expect("still a picture");
assert!(headers["cache-control"].to_str().unwrap().starts_with("private"), "not sent yet: the uploader only");
let (_, _, thumb) = app.raw("GET", &path(&photo["thumb"]), Some(&anna), "", Vec::new()).await;
let preview = image::load_from_memory(&thumb).unwrap();
assert_eq!((preview.width(), preview.height()), (360, 360));
}
assert_eq!(app.raw("GET", &path(&jpeg["url"]), None, "", Vec::new()).await.0, StatusCode::NOT_FOUND);
let (status, _) = upload(&anna, "image/jpeg", b"nem kep".to_vec()).await;
assert_eq!(status, StatusCode::BAD_REQUEST);
// Sent with a thread in a public topic: everyone sees them, cached for long.
let (status, created) = app
.call(
"POST",
"/v1/forum/threads",
Some(&anna),
json!({ "topic": "torzsasztal", "title": "Őszi kert", "body": "Nézzétek!", "photos": [jpeg["id"], webp["id"]] }),
)
.await;
assert_eq!(status, StatusCode::CREATED, "{created}");
let thread = app.get(&format!("/v1/forum/threads/{}", created["id"]), None).await;
assert_eq!(thread["posts"][0]["photos"].as_array().unwrap().len(), 2);
let (status, headers, _) = app.raw("GET", &path(&jpeg["url"]), None, "", Vec::new()).await;
assert_eq!(status, StatusCode::OK);
assert!(headers["cache-control"].to_str().unwrap().contains("immutable"));
// In a members-only topic: members only, not cached publicly; Bea cannot use Anna's photo.
let (_, third) = upload(&anna, "image/jpeg", jpeg_with_exif()).await;
let heart = app.thread(&bea, "ami-a-szivemen-van", "Nehéz napok").await;
let reply = |user: &User, photos: Value| {
let user = User { id: user.id, token: user.token.clone() };
let app = &app;
async move {
app.call(
"POST",
&format!("/v1/forum/threads/{heart}/posts"),
Some(&user),
json!({ "body": "Itt vagyok.", "photos": photos }),
)
.await
}
};
let (_, stolen) = reply(&bea, json!([third["id"]])).await;
assert!(stolen["photos"].is_null(), "not hers");
let (_, mine) = reply(&anna, json!([third["id"]])).await;
assert_eq!(mine["photos"][0]["id"], third["id"]);
assert_eq!(app.raw("GET", &path(&third["url"]), None, "", Vec::new()).await.0, StatusCode::NOT_FOUND);
let (status, headers, _) = app.raw("GET", &path(&third["url"]), Some(&bea), "", Vec::new()).await;
assert_eq!(status, StatusCode::OK);
assert!(headers["cache-control"].to_str().unwrap().starts_with("private"));
// Taken off before sending: gone, and it does not count.
let (_, extra) = upload(&anna, "image/jpeg", jpeg_with_exif()).await;
let gone = format!("/v1/forum/photos/{}", extra["id"].as_str().unwrap());
assert_eq!(app.raw("DELETE", &gone, Some(&bea), "", Vec::new()).await.0, StatusCode::NOT_FOUND);
assert_eq!(app.raw("DELETE", &gone, Some(&anna), "", Vec::new()).await.0, StatusCode::NO_CONTENT);
assert_eq!(app.raw("GET", &path(&extra["url"]), Some(&anna), "", Vec::new()).await.0, StatusCode::NOT_FOUND);
let sent = format!("/v1/forum/photos/{}", third["id"].as_str().unwrap());
assert_eq!(app.raw("DELETE", &sent, Some(&anna), "", Vec::new()).await.0, StatusCode::NOT_FOUND, "already sent");
// Five a day.
for _ in 0..2 {
assert_eq!(upload(&anna, "image/jpeg", jpeg_with_exif()).await.0, StatusCode::CREATED);
}
let (status, body) = upload(&anna, "image/jpeg", jpeg_with_exif()).await;
assert_eq!(status, StatusCode::TOO_MANY_REQUESTS, "{body}");
// Unattached for over a day: gone from the table and the storage.
sqlx::query("UPDATE forum.photos SET created_at = now() - interval '2 days' WHERE post_id IS NULL")
.execute(&pool)
.await
.unwrap();
let state = AppState {
db: pool.clone(),
flood_secs: 0,
base_url: "https://sorsfonalak.test".into(),
hub: crate::live::Hub::default(),
storage: Some(object_storage::Storage::new(storage)),
links: crate::links::LinkConfig::new("http://127.0.0.1:9/oembed", "http://127.0.0.1:9"),
};
assert_eq!(crate::routes::photo_cleanup(&state).await.unwrap(), 2);
let left: i64 = sqlx::query_scalar("SELECT count(*) FROM forum.photos").fetch_one(&pool).await.unwrap();
assert_eq!(left, 3);
}