2.9 KiB · text History 7e143f3
use axum::{
    extract::{Multipart, Path, State},
    http::{header, StatusCode},
    response::{IntoResponse, Redirect, Response},
};
use sea_orm::*;
use tracing::error;
use uuid::Uuid;

use crate::avatar::letter_avatar_svg;
use crate::entities::users;
use crate::middleware::UserContext;
use crate::AppState;


/// Serve a user's avatar: their uploaded image if present, otherwise a
/// generated letter avatar. Always returns an image so templates can use a
/// single `<img>` unconditionally.
pub async fn serve_avatar(State(state): State<AppState>, Path(id): Path<Uuid>) -> Response {
    let user = match users::Entity::find_by_id(id).one(state.db.as_ref()).await {
        Ok(Some(u)) => u,
        Ok(None) => return StatusCode::NOT_FOUND.into_response(),
        Err(e) => {
            error!(error = %e, "load user for avatar");
            return StatusCode::INTERNAL_SERVER_ERROR.into_response();
        }
    };

    let cache = (header::CACHE_CONTROL, "public, max-age=300");
    match (user.avatar_data, user.avatar_content_type) {
        (Some(bytes), Some(ct)) => {
            ([(header::CONTENT_TYPE, ct), (cache.0, cache.1.to_string())], bytes).into_response()
        }
        _ => {
            let svg = letter_avatar_svg(&user.username);
            (
                [
                    (header::CONTENT_TYPE, "image/svg+xml".to_string()),
                    (cache.0, cache.1.to_string()),
                ],
                svg,
            )
                .into_response()
        }
    }
}

/// Handle an avatar upload (multipart) from the profile panel.
pub async fn upload_avatar(
    State(state): State<AppState>,
    user: UserContext,
    mut multipart: Multipart,
) -> Result<Redirect, StatusCode> {
    while let Some(field) = multipart.next_field().await.map_err(|_| StatusCode::BAD_REQUEST)? {
        if field.name() != Some("avatar") {
            continue;
        }
        let content_type = field.content_type().map(|s| s.to_string());
        let data = field.bytes().await.map_err(|_| StatusCode::BAD_REQUEST)?;
        if data.is_empty() {
            return Ok(Redirect::to("/profile"));
        }
        if data.len() > crate::actions::MAX_AVATAR_BYTES {
            return Err(StatusCode::PAYLOAD_TOO_LARGE);
        }
        if !content_type.as_deref().is_some_and(|ct| crate::actions::AVATAR_TYPES.contains(&ct)) {
            return Err(StatusCode::UNSUPPORTED_MEDIA_TYPE);
        }
        crate::actions::set_avatar(&state, &user.user, content_type.as_deref(), data.to_vec()).await?;
        return Ok(Redirect::to("/profile"));
    }
    Ok(Redirect::to("/profile"))
}

/// Clear an uploaded avatar, reverting to the generated letter avatar.
pub async fn delete_avatar(
    State(state): State<AppState>,
    user: UserContext,
) -> Result<Redirect, StatusCode> {
    crate::actions::clear_avatar(&state, &user.user).await?;
    Ok(Redirect::to("/profile"))
}