Dough Git

clove/allInOne

src/web_media.rs

back to src

// src/web_media.rs

use std::path::Path;

use hyper::{Request, StatusCode, body::Incoming, header};
use serde_json::{Value, json};

use crate::{
    http::{self, Error, Reply},
    storage_event,
    store::{self, Store},
};

const MEDIA: &str = "data/media";

fn media_type(content: &[u8]) -> Option<&'static str> {
    if content.starts_with(b"\x89PNG\r\n\x1a\n") {
        Some("image/png")
    } else if content.starts_with(b"\xff\xd8\xff") {
        Some("image/jpeg")
    } else if content.starts_with(b"GIF87a") || content.starts_with(b"GIF89a") {
        Some("image/gif")
    } else if content.starts_with(b"RIFF") && content.get(8..12) == Some(b"WEBP") {
        Some("image/webp")
    } else {
        None
    }
}

pub async fn get(key: &str) -> Result<Reply, Error> {
    if key.is_empty()
        || !key
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || b"-_".contains(&byte))
    {
        return Err(Error::missing("Image not found"));
    }
    let content = tokio::fs::read(Path::new(MEDIA).join(key))
        .await
        .map_err(|_| Error::missing("Image not found"))?;
    let mime = media_type(&content).ok_or_else(|| Error::missing("Image not found"))?;
    Ok(http::reply(StatusCode::OK, mime, content))
}

pub async fn upload(
    store: &Store,
    request: &mut Request<Incoming>,
    identifier: &str,
    field: &str,
) -> Result<Value, Error> {
    let supplied_type = request
        .headers()
        .get(header::CONTENT_TYPE)
        .and_then(|value| value.to_str().ok())
        .unwrap_or_default()
        .to_owned();
    let bytes = http::bytes(request, 10 * 1024 * 1024).await?;
    if media_type(&bytes) != Some(supplied_type.as_str()) {
        return Err(Error(
            StatusCode::UNSUPPORTED_MEDIA_TYPE,
            "Use a PNG, JPEG, GIF or WebP image".into(),
        ));
    }
    let key = format!("member-{field}-{}", store::uuid());
    tokio::fs::create_dir_all(MEDIA)
        .await
        .map_err(anyhow::Error::from)?;
    let path = Path::new(MEDIA).join(&key);
    tokio::fs::write(&path, bytes)
        .await
        .map_err(anyhow::Error::from)?;
    let result = store
        .change(|data| {
            let index = data
                .member_index(identifier)
                .ok_or_else(|| Error::missing("Member not found"))?;
            let url = format!("/api/plural/media/{key}");
            let member = &mut data.members[index];
            if field == "avatar" {
                member["avatar_url"] = json!(url);
                member["webhook_avatar_url"] = Value::Null;
            } else {
                member["banner"] = json!(url);
            }
            Ok((
                data.member(&data.members[index]),
                vec![
                    storage_event("members_update", Value::Null),
                    storage_event("fronters_update", data.fronters()),
                ],
            ))
        })
        .await;
    if result.is_err() {
        let _ = tokio::fs::remove_file(path).await;
    }
    result
}