0.0.6-onecachekey

This commit is contained in:
2024-10-22 09:38:30 +03:00
parent 9fcce86075
commit 8ff3f018b5
7 changed files with 95 additions and 123 deletions

View File

@@ -2,105 +2,88 @@ use actix_web::{error::ErrorInternalServerError, web, HttpRequest, HttpResponse,
use log::{info, warn, error};
use crate::app_state::AppState;
use crate::thumbnail::{parse_thumbnail_request, find_closest_width, generate_thumbnails, ALLOWED_THUMBNAIL_WIDTHS};
use crate::thumbnail::{parse_thumbnail_request, find_closest_width, generate_thumbnails};
use crate::s3_utils::{load_file_from_s3, upload_to_s3};
use crate::handlers::serve_file::serve_file;
/// Обработчик для скачивания файла и генерации миниатюры, если она недоступна.
pub async fn proxy_handler(
req: HttpRequest,
file_key: web::Path<String>,
requested_res: web::Path<String>,
state: web::Data<AppState>,
) -> Result<HttpResponse, actix_web::Error> {
info!("proxy_handler: {}", req.path());
info!("[proxy_handler] req.path: {}", req.path());
let requested_path = match state.get_path(&file_key).await {
let requested_path = match state.get_path(&requested_res).await {
Ok(Some(path)) => path,
Ok(None) => {
warn!("Путь не найден: {}", req.path());
warn!("[proxy_handler] wrong request: {}", req.path());
return Ok(HttpResponse::NotFound().finish());
}
Err(e) => {
warn!("Ошибка: {}", e);
warn!("[proxy_handler] error: {}", e);
return Ok(HttpResponse::InternalServerError().finish());
}
};
info!("Запрошенный путь: {}", requested_path);
// имя файла
let filename_with_extension = requested_path.split("/").last().ok_or_else(|| {
actix_web::error::ErrorInternalServerError("Неверный формат пути")
})?;
info!("Имя файла с расширением: {}", filename_with_extension);
// Разделяем имя и расширение файла, сохраняя их для дальнейшего использования
let (requested_filekey, extension) = filename_with_extension
.rsplit_once('.')
.map(|(name, ext)| (name.to_string(), Some(ext.to_lowercase())))
.unwrap_or((filename_with_extension.to_string(), None));
info!("Запрошенный ключ файла: {}", requested_filekey);
if let Some(ext) = &extension {
info!("Расширение файла: {}", ext);
}
info!("[proxy_handler] requested path: {}", requested_path);
// Проверяем, запрошена ли миниатюра
if let Some((base_filename, requested_width, _ext)) =
parse_thumbnail_request(&requested_filekey)
if let Some((base_filename, requested_width, extension)) =
parse_thumbnail_request(&requested_res)
{
info!("Запрошена миниатюра. Базов<D0BE><D0B2>е имя файла: {}, Запрошенная ширина: {}", base_filename, requested_width);
info!("[proxy_handler] thumbnail requested: {} width: {}, ext: {}", base_filename, requested_width, extension);
// Находим ближайший подходящий размер
let closest_width = find_closest_width(requested_width);
let thumbnail_key = format!("{}_{}", base_filename, closest_width);
info!("Ближайшая ширина: {}, Кюч миниатюры: {}", closest_width, thumbnail_key);
let thumb_filekey = format!("{}_{}", base_filename, closest_width);
info!("[proxy_handler] closest width: {}, thumb_filekey: {}", closest_width, thumb_filekey);
// Проверяем наличие миниатюры в кэше
let cached_files = state.get_cached_file_list().await;
if !cached_files.contains(&thumbnail_key) {
info!("Миниатюра не найдена в кэше");
if !cached_files.contains(&thumb_filekey) {
info!("[proxy_handler] no thumb found");
if cached_files.contains(&base_filename) {
info!("Оригинальный файл найден в кэше, генерируем миниатюру");
info!("[proxy_handler] no original file found");
// Загружаем оригинальный файл из S3
let original_data: Vec<u8> =
load_file_from_s3(&state.s3_client, &state.s3_bucket, &base_filename).await?;
load_file_from_s3(&state.storj_client, &state.storj_bucket, &base_filename).await?;
// Генерируем миниатюру для ближайшего подходящего размера
let image = image::load_from_memory(&original_data).map_err(|_| {
ErrorInternalServerError("Failed to load image for thumbnail generation")
})?;
let thumbnails_bytes =
generate_thumbnails(&image, &ALLOWED_THUMBNAIL_WIDTHS).await?;
generate_thumbnails(&image).await?;
let thumbnail_bytes = thumbnails_bytes[&closest_width].clone();
// Загружаем миниатюру в S3
upload_to_s3(
&state.s3_client,
&state.s3_bucket,
&thumbnail_key,
&state.storj_client,
&state.storj_bucket,
&thumb_filekey,
thumbnail_bytes.clone(),
"image/jpeg",
)
.await?;
info!("Миниатюра сгенерирована и загружена в S3");
info!("[proxy_handler] thumb was saved in storj");
return Ok(HttpResponse::Ok()
.content_type("image/jpeg")
.body(thumbnail_bytes));
} else {
warn!("Оригинальный файл не найден в кэше");
warn!("[proxy_handler] original was not found");
}
} else {
info!("Миниатюра найдена в кэше, возвращаем её");
return serve_file(&thumbnail_key, &state).await;
info!("[proxy_handler] thumb was found");
return serve_file(&thumb_filekey, &state).await;
}
}
// Если запрошен целый файл
info!("Запрошен целый файл, возвращаем его");
info!("Проверка наличия файла в S3: {}", requested_filekey);
match serve_file(&requested_filekey, &state).await {
info!("[proxy_handler] serving full file: {}", requested_path);
match serve_file(&requested_path, &state).await {
Ok(response) => Ok(response),
Err(e) => {
error!("Ошибка файла: {}", e);
error!("[proxy_handler] error: {}", e);
Err(e)
}
}

View File

@@ -8,22 +8,22 @@ use crate::s3_utils::check_file_exists;
/// Функция для обслуживания файла по заданному пути.
pub async fn serve_file(file_key: &str, state: &AppState) -> Result<HttpResponse, actix_web::Error> {
// Проверяем наличие файла в Storj S3
if !check_file_exists(&state.s3_client, &state.s3_bucket, &file_key).await? {
if !check_file_exists(&state.storj_client, &state.storj_bucket, &file_key).await? {
warn!("{}", file_key);
return Err(ErrorInternalServerError("File not found in S3"));
return Err(ErrorInternalServerError("File not found in Storj"));
}
let file_path = state.get_path(file_key).await.unwrap().unwrap();
// Получаем объект из Storj S3
let get_object_output = state
.s3_client
.storj_client
.get_object()
.bucket(&state.s3_bucket)
.bucket(&state.storj_bucket)
.key(file_path.clone())
.send()
.await
.map_err(|_| ErrorInternalServerError("Failed to get object from S3"))?;
.map_err(|_| ErrorInternalServerError("Failed to get object from Storj"))?;
let data: aws_sdk_s3::primitives::AggregatedBytes = get_object_output
.body

View File

@@ -26,7 +26,7 @@ pub async fn upload_handler(
// Получаем текущую квоту пользователя
let this_week_amount: u64 = state.get_or_create_quota(&user_id).await.unwrap_or(0);
let mut body = "ok".to_string();
while let Ok(Some(field)) = payload.try_next().await {
let mut field = field;
@@ -57,22 +57,21 @@ pub async fn upload_handler(
let _ = state.increment_uploaded_bytes(&user_id, file_size).await?;
// Определяем правильное расширение и ключ для S3
let file_key = generate_key_with_extension(name, content_type.to_owned());
body = generate_key_with_extension(name, content_type.to_owned());
// Загружаем файл в S3
upload_to_s3(
&state.s3_client,
&state.s3_bucket,
&file_key,
&state.storj_client,
&state.storj_bucket,
&body,
file_bytes,
&content_type,
)
.await?;
// Сохраняем информацию о загруженном файле для пользователя
user_added_file(&mut state.redis.clone(), &user_id, &file_key).await?;
user_added_file(&mut state.redis.clone(), &user_id, &body).await?;
}
}
Ok(HttpResponse::Ok().json("File uploaded successfully"))
Ok(HttpResponse::Ok().body(body))
}