Files
quoter/src/handlers/upload.rs

130 lines
5.2 KiB
Rust
Raw Normal View History

2024-10-22 00:36:42 +03:00
use actix_multipart::Multipart;
use actix_web::{web, HttpRequest, HttpResponse, Result};
2024-11-12 12:29:19 +03:00
use log::{error, warn};
2024-10-22 00:36:42 +03:00
use crate::app_state::AppState;
use crate::auth::{get_id_by_token, user_added_file};
2025-08-02 00:18:09 +03:00
use crate::handlers::MAX_USER_QUOTA_BYTES;
2024-11-13 11:14:53 +03:00
use crate::lookup::store_file_info;
2025-08-02 00:18:09 +03:00
use crate::s3_utils::{self, generate_key_with_extension, upload_to_s3};
2024-10-22 00:36:42 +03:00
use futures::TryStreamExt;
2024-11-13 11:32:50 +03:00
// use crate::thumbnail::convert_heic_to_jpeg;
2024-10-22 00:36:42 +03:00
/// Обработчик для аплоада файлов.
pub async fn upload_handler(
req: HttpRequest,
mut payload: Multipart,
state: web::Data<AppState>,
) -> Result<HttpResponse, actix_web::Error> {
// Получаем токен из заголовка авторизации
let token = req
.headers()
.get("Authorization")
.and_then(|header_value| header_value.to_str().ok());
if token.is_none() {
return Err(actix_web::error::ErrorUnauthorized("Unauthorized")); // Если токен отсутствует, возвращаем ошибку
}
let user_id = get_id_by_token(token.unwrap()).await?;
// Получаем текущую квоту пользователя
2025-08-02 00:18:09 +03:00
let current_quota: u64 = state.get_or_create_quota(&user_id).await.unwrap_or(0);
2024-10-22 09:38:30 +03:00
let mut body = "ok".to_string();
2024-10-22 00:36:42 +03:00
while let Ok(Some(field)) = payload.try_next().await {
let mut field = field;
2024-11-13 11:14:53 +03:00
let mut file_bytes = Vec::new();
let mut file_size: u64 = 0;
2024-10-22 00:36:42 +03:00
2024-11-13 11:14:53 +03:00
// Читаем данные файла
while let Ok(Some(chunk)) = field.try_next().await {
file_size += chunk.len() as u64;
file_bytes.extend_from_slice(&chunk);
}
2024-10-22 00:36:42 +03:00
2024-11-13 11:14:53 +03:00
// Определяем MIME-тип из содержимого файла
let detected_mime_type = match s3_utils::detect_mime_type(&file_bytes) {
Some(mime) => mime,
None => {
warn!("Неподдерживаемый формат файла");
2025-08-02 00:18:09 +03:00
return Err(actix_web::error::ErrorUnsupportedMediaType(
"Неподдерживаемый формат файла",
));
2024-11-13 11:14:53 +03:00
}
};
2024-10-22 00:36:42 +03:00
2024-11-13 11:32:50 +03:00
// Для HEIC файлов просто сохраняем как есть
2024-11-13 11:14:53 +03:00
let (file_bytes, content_type) = if detected_mime_type == "image/heic" {
2024-11-13 11:32:50 +03:00
warn!("HEIC support is temporarily disabled, saving original file");
(file_bytes, detected_mime_type)
2024-11-13 11:14:53 +03:00
} else {
(file_bytes, detected_mime_type)
};
2024-10-22 00:36:42 +03:00
2024-11-13 11:14:53 +03:00
// Получаем расширение из MIME-типа
let extension = match s3_utils::get_extension_from_mime(&content_type) {
Some(ext) => ext,
None => {
warn!("Неподдерживаемый тип содержимого: {}", content_type);
2025-08-02 00:18:09 +03:00
return Err(actix_web::error::ErrorUnsupportedMediaType(
"Неподдерживаемый тип содержимого",
));
2024-10-22 00:36:42 +03:00
}
2024-11-13 11:14:53 +03:00
};
2024-10-22 00:36:42 +03:00
2024-11-13 11:14:53 +03:00
// Проверяем, что добавление файла не превышает лимит квоты
2025-08-02 00:18:09 +03:00
if current_quota + file_size > MAX_USER_QUOTA_BYTES {
warn!(
"Quota would exceed limit: current={}, adding={}, limit={}",
current_quota, file_size, MAX_USER_QUOTA_BYTES
);
2024-11-13 11:14:53 +03:00
return Err(actix_web::error::ErrorUnauthorized("Quota exceeded"));
}
// Генерируем имя файла с правильным расширением
let filename = format!("{}.{}", uuid::Uuid::new_v4(), extension);
// Загружаем файл в S3 storj
match upload_to_s3(
&state.storj_client,
&state.bucket,
&filename,
file_bytes,
&content_type,
2025-08-02 00:18:09 +03:00
)
.await
{
2024-11-13 11:14:53 +03:00
Ok(_) => {
2025-08-02 00:18:09 +03:00
warn!(
"file {} uploaded to storj, incrementing quota by {} bytes",
filename, file_size
);
2024-11-13 11:14:53 +03:00
if let Err(e) = state.increment_uploaded_bytes(&user_id, file_size).await {
error!("Failed to increment quota: {}", e);
return Err(e);
2024-11-12 12:29:19 +03:00
}
2025-08-02 00:18:09 +03:00
2024-11-13 11:14:53 +03:00
// Сохраняем информацию о файле в Redis
let mut redis = state.redis.clone();
store_file_info(&mut redis, &filename, &content_type).await?;
user_added_file(&mut redis, &user_id, &filename).await?;
2025-08-02 00:18:09 +03:00
2024-11-13 11:14:53 +03:00
// Сохраняем маппинг пути
2025-08-02 00:18:09 +03:00
let generated_key =
generate_key_with_extension(filename.clone(), content_type.clone());
2024-11-13 11:14:53 +03:00
state.set_path(&filename, &generated_key).await;
2025-08-02 00:18:09 +03:00
2024-11-13 11:14:53 +03:00
if let Ok(new_quota) = state.get_or_create_quota(&user_id).await {
warn!("New quota for user {}: {} bytes", user_id, new_quota);
2024-11-12 12:29:19 +03:00
}
2025-08-02 00:18:09 +03:00
2024-11-13 11:14:53 +03:00
body = filename;
}
Err(e) => {
warn!("Failed to upload to storj: {}", e);
return Err(actix_web::error::ErrorInternalServerError(e));
2024-10-22 21:23:34 +03:00
}
2024-10-22 00:36:42 +03:00
}
}
2024-10-22 09:38:30 +03:00
Ok(HttpResponse::Ok().body(body))
2024-10-22 00:36:42 +03:00
}