Files
web-at-transit/backend/src/api/upload_image/service.rs
T
2026-05-24 22:55:17 +07:00

137 lines
4.3 KiB
Rust

use super::{dto::*, repo};
use crate::{error::{AppError, AppResult}, state::AppState};
use bytes::Bytes;
use sha2::{Digest, Sha256};
use std::path::Path;
pub struct UploadInput {
pub form: UploadForm,
pub filename: String,
pub mime: String,
pub bytes: Bytes,
}
pub async fn upload(state: &AppState, input: UploadInput) -> AppResult<CreatedImage> {
validate_entity_type(&input.form.entity_type)?;
validate_kind(&input.form.kind)?;
if input.bytes.is_empty() {
return Err(AppError::BadRequest("empty file".into()));
}
let (w, h) = probe_dimensions(&input.bytes);
let sha = hex::encode(Sha256::digest(&input.bytes));
let size = input.bytes.len() as i64;
let stored = state
.seaweed
.upload(
&input.form.entity_type,
&input.form.entity_id,
&input.filename,
&input.mime,
input.bytes,
)
.await
.map_err(|e| AppError::Internal(e.to_string()))?;
let meta = serde_json::json!({
"mime": input.mime,
"size_bytes": size,
"width": w,
"height": h,
"alt_th": input.form.alt_th,
"sha256": sha,
});
let row = repo::insert(
&state.db,
&input.form.entity_type,
&input.form.entity_id,
&input.form.kind,
&stored.fid,
&format!("{}{}", state.public_base, stored.url_path),
input.form.display_order,
&meta,
)
.await?;
Ok(row)
}
fn validate_entity_type(t: &str) -> AppResult<()> {
match t {
"route" | "station" | "sponsor" | "province" | "bus" | "misc" => Ok(()),
_ => Err(AppError::BadRequest("invalid entity_type".into())),
}
}
fn validate_kind(k: &str) -> AppResult<()> {
match k {
"photo" | "logo" | "icon" | "map" | "hero" => Ok(()),
_ => Err(AppError::BadRequest("invalid kind".into())),
}
}
fn probe_dimensions(bytes: &[u8]) -> (Option<u32>, Option<u32>) {
match image::load_from_memory(bytes) {
Ok(img) => (Some(img.width()), Some(img.height())),
Err(_) => (None, None),
}
}
/// Walk `dir/<entity_type>/<entity_id>/*.{jpg,png,webp}` and ingest each file
/// once. Skips files whose sha256 already lives in `images` (matched
/// by fid path).
pub async fn ingest_seed_dir(state: &AppState, dir: &str) -> AppResult<()> {
if repo::count(&state.db).await? > 0 {
tracing::info!("seed-assets: images table already populated, skipping");
return Ok(());
}
let base = Path::new(dir);
if !base.exists() {
tracing::warn!("seed-assets dir not found: {dir}");
return Ok(());
}
let mut count = 0;
for entry in walkdir::WalkDir::new(base).min_depth(3).max_depth(3) {
let entry = match entry { Ok(e) => e, Err(_) => continue };
if !entry.file_type().is_file() { continue; }
let path = entry.path();
let rel = match path.strip_prefix(base) { Ok(p) => p, Err(_) => continue };
let mut comps = rel.components();
let Some(et) = comps.next().and_then(|c| c.as_os_str().to_str()) else { continue };
let Some(eid) = comps.next().and_then(|c| c.as_os_str().to_str()) else { continue };
let Some(fname) = path.file_name().and_then(|s| s.to_str()) else { continue };
let mime = mime_guess::from_path(path).first_or_octet_stream().to_string();
let bytes = match tokio::fs::read(path).await {
Ok(b) => Bytes::from(b),
Err(e) => { tracing::warn!("read {path:?}: {e}"); continue }
};
let candidate_fid = format!("/{}/{}/{}", et, eid, fname);
if repo::exists_fid(&state.db, &candidate_fid).await.unwrap_or(false) {
continue;
}
let res = upload(
state,
UploadInput {
form: UploadForm {
entity_type: et.into(),
entity_id: eid.into(),
kind: "photo".into(),
alt_th: None,
display_order: 0,
},
filename: fname.into(),
mime,
bytes,
},
)
.await;
match res {
Ok(_) => count += 1,
Err(e) => tracing::warn!("ingest {path:?} failed: {e:?}"),
}
}
tracing::info!("seed-assets ingested {count} files from {dir}");
Ok(())
}