Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

3.2 KB
Raw Blame
use std::str::FromStr;

use crate::api::context::{AppState, AuthorizationService};
use crate::model::api::*;
use crate::service::dynamodb::model::MetadataObject;
use axum::extract::{Json, State};
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::response::Response;
use chrono::Utc;
use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::document::FileType;
use uuid::Uuid;

#[utoipa::path(
  put,
  path = "/api/file",
  request_body = PutFileRequest,
  responses(
    (status = 200, body=PutFileResponse),
    (status = 400, body=String),
    (status = 401, body=String),
    (status = 500, body=String),
  ),
)]
#[tracing::instrument(skip(ctx, user), fields(actor = %user.acting_entity()))]
pub async fn put_presigned_url(
    State(ctx): State<AppState>,
    user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
    Json(request): Json<PutFileRequest>,
) -> Result<Response, Response> {
    // Checked before any metadata is written, so a rejected request leaves no row.
    if request
        .content_length
        .is_some_and(|length| i64::try_from(length).is_err())
    {
        return Err((StatusCode::BAD_REQUEST, "content length is out of range").into_response());
    }

    let content_type = if let Some(content_type) = request.content_type {
        Ok(content_type)
    } else {
        request
            .file_name
            .split(".")
            .last()
            .map(FileType::from_str)
            .and_then(Result::ok)
            .map(|file_type| file_type.mime_type().to_string())
            .ok_or_else(|| {
                (
                    StatusCode::UNSUPPORTED_MEDIA_TYPE,
                    "unknown or unsupported media type",
                )
                    .into_response()
            })
    }?;

    let request_content_length = request.content_length;

    let id: String = Uuid::new_v4().to_string();
    let static_file_key = s3_key::StaticFileKey::new(&id);
    let s3_key = static_file_key.to_key();
    let permalink = format!("{}/{}", ctx.public_url, s3_key);

    let owner_id = user.authorization.user.macro_user_id.as_ref().to_string();

    let metadata = MetadataObject {
        file_id: id.clone(),
        content_type: content_type.clone(),
        is_uploaded: false,
        last_accessed: Utc::now(),
        owner_id,
        extension_data: request.extension_data,
        file_name: request.file_name,
        s3_key: s3_key.clone(),
    };

    ctx.metadata_client
        .put_metadata(metadata)
        .await
        .map_err(|err| {
            tracing::error!(error=?err, "coult not create metadata");
            (StatusCode::INTERNAL_SERVER_ERROR, "internal server error").into_response()
        })?;

    let upload_url = ctx
        .storage_client
        .put_presigned_url(s3_key.clone(), content_type.clone(), request_content_length)
        .await
        .map_err(|err| {
            tracing::error!(error=?err, "could not create presigned url");
            (StatusCode::INTERNAL_SERVER_ERROR, "internal server error").into_response()
        })?;

    Ok((
        StatusCode::OK,
        Json(PutFileResponse {
            id: id.clone(),
            upload_url,
            file_location: permalink,
        }),
    )
        .into_response())
}