@@ -4,9 +4,11 @@ use log::{error, warn};
|
||||
|
||||
use crate::app_state::AppState;
|
||||
use crate::auth::{get_id_by_token, user_added_file};
|
||||
use crate::s3_utils::{generate_key_with_extension, upload_to_s3};
|
||||
use crate::s3_utils::{self, upload_to_s3, generate_key_with_extension};
|
||||
use crate::lookup::store_file_info;
|
||||
use futures::TryStreamExt;
|
||||
use crate::handlers::MAX_WEEK_BYTES;
|
||||
use crate::thumbnail::convert_heic_to_jpeg;
|
||||
|
||||
/// Обработчик для аплоада файлов.
|
||||
pub async fn upload_handler(
|
||||
@@ -30,67 +32,90 @@ pub async fn upload_handler(
|
||||
let mut body = "ok".to_string();
|
||||
while let Ok(Some(field)) = payload.try_next().await {
|
||||
let mut field = field;
|
||||
let mut file_bytes = Vec::new();
|
||||
let mut file_size: u64 = 0;
|
||||
|
||||
let content_type = field.content_type().unwrap().to_string();
|
||||
let file_name = field
|
||||
.content_disposition()
|
||||
.unwrap()
|
||||
.get_filename()
|
||||
.map(|f| f.to_string());
|
||||
// Читаем данные файла
|
||||
while let Ok(Some(chunk)) = field.try_next().await {
|
||||
file_size += chunk.len() as u64;
|
||||
file_bytes.extend_from_slice(&chunk);
|
||||
}
|
||||
|
||||
if let Some(name) = file_name {
|
||||
let mut file_bytes = Vec::new();
|
||||
let mut file_size: u64 = 0;
|
||||
|
||||
// Читаем данные файла
|
||||
while let Ok(Some(chunk)) = field.try_next().await {
|
||||
file_size += chunk.len() as u64;
|
||||
file_bytes.extend_from_slice(&chunk);
|
||||
// Определяем MIME-тип из содержимого файла
|
||||
let detected_mime_type = match s3_utils::detect_mime_type(&file_bytes) {
|
||||
Some(mime) => mime,
|
||||
None => {
|
||||
warn!("Неподдерживаемый формат файла");
|
||||
return Err(actix_web::error::ErrorUnsupportedMediaType("Неподдерживаемый формат файла"));
|
||||
}
|
||||
};
|
||||
|
||||
// Проверяем, что добавление файла не превышает лимит квоты
|
||||
if this_week_amount + file_size > MAX_WEEK_BYTES {
|
||||
warn!("Quota would exceed limit: current={}, adding={}, limit={}",
|
||||
this_week_amount, file_size, MAX_WEEK_BYTES);
|
||||
return Err(actix_web::error::ErrorUnauthorized("Quota exceeded"));
|
||||
}
|
||||
|
||||
// Загружаем файл в S3 storj с использованием ключа в нижнем регистре
|
||||
let filekey = generate_key_with_extension(name.clone(), content_type.to_owned());
|
||||
let orig_path = name.clone();
|
||||
|
||||
match upload_to_s3(
|
||||
&state.storj_client,
|
||||
&state.bucket,
|
||||
&filekey,
|
||||
file_bytes.clone(),
|
||||
&content_type,
|
||||
).await {
|
||||
Ok(_) => {
|
||||
warn!("file {} uploaded to storj, incrementing quota by {} bytes", filekey, file_size);
|
||||
// Инкрементируем квоту только после успешной загрузки
|
||||
if let Err(e) = state.increment_uploaded_bytes(&user_id, file_size).await {
|
||||
error!("Failed to increment quota: {}", e);
|
||||
// Можно добавить откат загрузки файла здесь
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
// Сохраняем информацию о загруженном файле
|
||||
user_added_file(&mut state.redis.clone(), &user_id, &filekey).await?;
|
||||
state.set_path(&filekey, &orig_path).await;
|
||||
|
||||
// Логируем новое значение квоты
|
||||
if let Ok(new_quota) = state.get_or_create_quota(&user_id).await {
|
||||
warn!("New quota for user {}: {} bytes", user_id, new_quota);
|
||||
}
|
||||
|
||||
body = filekey;
|
||||
}
|
||||
// Для HEIC файлов конвертируем в JPEG
|
||||
let (file_bytes, content_type) = if detected_mime_type == "image/heic" {
|
||||
match convert_heic_to_jpeg(&file_bytes) {
|
||||
Ok(jpeg_data) => (jpeg_data, "image/jpeg".to_string()),
|
||||
Err(e) => {
|
||||
warn!("Failed to upload to storj: {}", e);
|
||||
return Err(actix_web::error::ErrorInternalServerError(e));
|
||||
warn!("Failed to convert HEIC to JPEG: {}", e);
|
||||
(file_bytes, detected_mime_type)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
(file_bytes, detected_mime_type)
|
||||
};
|
||||
|
||||
// Получаем расширение из MIME-типа
|
||||
let extension = match s3_utils::get_extension_from_mime(&content_type) {
|
||||
Some(ext) => ext,
|
||||
None => {
|
||||
warn!("Неподдерживаемый тип содержимого: {}", content_type);
|
||||
return Err(actix_web::error::ErrorUnsupportedMediaType("Неподдерживаемый тип содержимого"));
|
||||
}
|
||||
};
|
||||
|
||||
// Проверяем, что добавление файла не превышает лимит квоты
|
||||
if this_week_amount + file_size > MAX_WEEK_BYTES {
|
||||
warn!("Quota would exceed limit: current={}, adding={}, limit={}",
|
||||
this_week_amount, file_size, MAX_WEEK_BYTES);
|
||||
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,
|
||||
).await {
|
||||
Ok(_) => {
|
||||
warn!("file {} uploaded to storj, incrementing quota by {} bytes", filename, file_size);
|
||||
if let Err(e) = state.increment_uploaded_bytes(&user_id, file_size).await {
|
||||
error!("Failed to increment quota: {}", e);
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
// Сохраняем информацию о файле в 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?;
|
||||
|
||||
// Сохраняем маппинг пути
|
||||
let generated_key = generate_key_with_extension(filename.clone(), content_type.clone());
|
||||
state.set_path(&filename, &generated_key).await;
|
||||
|
||||
if let Ok(new_quota) = state.get_or_create_quota(&user_id).await {
|
||||
warn!("New quota for user {}: {} bytes", user_id, new_quota);
|
||||
}
|
||||
|
||||
body = filename;
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("Failed to upload to storj: {}", e);
|
||||
return Err(actix_web::error::ErrorInternalServerError(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(HttpResponse::Ok().body(body))
|
||||
|
||||
Reference in New Issue
Block a user