logadd
All checks were successful
deploy / deploy (push) Successful in 4m47s

This commit is contained in:
Untone 2024-10-02 18:38:44 +03:00
parent 01b560085e
commit e3937e70ae
4 changed files with 20 additions and 4 deletions

1
Cargo.lock generated
View File

@ -1181,6 +1181,7 @@ dependencies = [
"aws-sdk-s3",
"futures",
"image",
"log",
"mime_guess",
"redis",
"reqwest",

View File

@ -21,6 +21,7 @@ image = "0.25.2"
mime_guess = "2.0.5"
aws-config = "1.5.5"
actix-multipart = "0.7.2"
log = "0.4.22"
[[bin]]
name = "quoter"

View File

@ -2,6 +2,7 @@ use actix_multipart::Multipart;
use actix_web::{error::ErrorInternalServerError, web, HttpRequest, HttpResponse, Result};
use futures::StreamExt;
use mime_guess::MimeGuess;
use log::{info, warn};
use crate::app_state::AppState;
use crate::auth::{get_id_by_token, user_added_file};
@ -124,30 +125,40 @@ pub async fn proxy_handler(
path: web::Path<String>,
state: web::Data<AppState>,
) -> Result<HttpResponse, actix_web::Error> {
info!("proxy_handler вызван с путем: {}", path);
// весь запрошенный путь
let requested_path = state.get_path(&path).await.unwrap().unwrap();
info!("Запрошенный путь: {}", requested_path);
// имя файла
let filename_with_extension = requested_path.split("/").last().unwrap();
info!("Имя файла с расширением: {}", filename_with_extension);
// убираем расширение файла
let requested_filekey = filename_with_extension
.rsplit_once('.')
.map(|(name, _ext)| name)
.unwrap_or(filename_with_extension); // Если расширение отсутствует, возвращаем оригинальное имя
.unwrap_or(filename_with_extension);
info!("Запрошенный ключ файла: {}", requested_filekey);
// Проверяем, запрошена ли миниатюра
if let Some((base_filename, requested_width, _ext)) =
parse_thumbnail_request(&requested_filekey)
{
info!("Запрошена миниатюра. Базовое имя файла: {}, Запрошенная ширина: {}", base_filename, requested_width);
// Находим ближайший подходящий размер
let closest_width = find_closest_width(requested_width);
let thumbnail_key = format!("{}_{}", base_filename, closest_width);
info!("Ближайшая ширина: {}, Ключ миниатюры: {}", closest_width, thumbnail_key);
// Проверяем наличие миниатюры в кэше
let cached_files = state.get_cached_file_list().await;
if !cached_files.contains(&thumbnail_key) {
info!("Миниатюра не найдена в кэше");
if cached_files.contains(&base_filename) {
info!("Оригинальный файл найден в кэше, генерируем миниатюру");
// Загружаем оригинальный файл из S3
let original_data =
load_file_from_s3(&state.s3_client, &state.s3_bucket, &base_filename).await?;
@ -169,17 +180,20 @@ pub async fn proxy_handler(
"image/jpeg",
)
.await?;
info!("Миниатюра сгенерирована и загружена в S3");
return Ok(HttpResponse::Ok()
.content_type("image/jpeg")
.body(thumbnail_bytes));
} else {
warn!("Оригинальный файл не найден в кэше");
}
} else {
// Если миниатюра уже есть в кэше, просто возвращаем её
info!("Миниатюра найдена в кэше, возвращаем её");
return serve_file(&thumbnail_key, &state).await;
}
}
// Если запрошен целый файл
info!("Запрошен целый файл, возвращаем его");
serve_file(&requested_filekey, &state).await
}

View File

@ -4,7 +4,7 @@ mod handlers;
mod s3_utils;
mod thumbnail;
use actix_web::{middleware::Logger, web, App, HttpServer, HttpResponse};
use actix_web::{middleware::Logger, web, App, HttpServer};
use app_state::AppState;
use handlers::{proxy_handler, upload_handler};
use tokio::task::spawn_blocking;