quoter/src/handlers/proxy.rs

91 lines
3.7 KiB
Rust
Raw Normal View History

2024-10-21 21:36:42 +00:00
use actix_web::{error::ErrorInternalServerError, web, HttpRequest, HttpResponse, Result};
use log::{info, warn, error};
use crate::app_state::AppState;
2024-10-22 06:38:30 +00:00
use crate::thumbnail::{parse_thumbnail_request, find_closest_width, generate_thumbnails};
2024-10-21 21:36:42 +00:00
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,
2024-10-22 06:38:30 +00:00
requested_res: web::Path<String>,
2024-10-21 21:36:42 +00:00
state: web::Data<AppState>,
) -> Result<HttpResponse, actix_web::Error> {
2024-10-22 06:52:05 +00:00
info!("req.path: {}", req.path());
2024-10-21 21:36:42 +00:00
2024-10-22 06:38:30 +00:00
let requested_path = match state.get_path(&requested_res).await {
2024-10-21 21:36:42 +00:00
Ok(Some(path)) => path,
Ok(None) => {
2024-10-22 06:52:05 +00:00
warn!("wrong request: {}", req.path());
2024-10-21 21:36:42 +00:00
return Ok(HttpResponse::NotFound().finish());
}
Err(e) => {
2024-10-22 06:52:05 +00:00
warn!("error: {}", e);
2024-10-21 21:36:42 +00:00
return Ok(HttpResponse::InternalServerError().finish());
}
};
2024-10-22 06:52:05 +00:00
info!("requested path: {}", requested_path);
2024-10-21 21:36:42 +00:00
// Проверяем, запрошена ли миниатюра
2024-10-22 06:38:30 +00:00
if let Some((base_filename, requested_width, extension)) =
parse_thumbnail_request(&requested_res)
2024-10-21 21:36:42 +00:00
{
2024-10-22 06:52:05 +00:00
info!("thumbnail requested: {} width: {}, ext: {}", base_filename, requested_width, extension);
2024-10-21 21:36:42 +00:00
// Находим ближайший подходящий размер
let closest_width = find_closest_width(requested_width);
2024-10-22 06:38:30 +00:00
let thumb_filekey = format!("{}_{}", base_filename, closest_width);
2024-10-22 06:52:05 +00:00
info!("closest width: {}, thumb_filekey: {}", closest_width, thumb_filekey);
2024-10-21 21:36:42 +00:00
// Проверяем наличие миниатюры в кэше
let cached_files = state.get_cached_file_list().await;
2024-10-22 06:38:30 +00:00
if !cached_files.contains(&thumb_filekey) {
2024-10-22 06:52:05 +00:00
info!("no thumb found");
2024-10-21 21:36:42 +00:00
if cached_files.contains(&base_filename) {
2024-10-22 06:52:05 +00:00
info!("no original file found");
2024-10-21 21:36:42 +00:00
// Загружаем оригинальный файл из S3
let original_data: Vec<u8> =
2024-10-22 06:38:30 +00:00
load_file_from_s3(&state.storj_client, &state.storj_bucket, &base_filename).await?;
2024-10-21 21:36:42 +00:00
// Генерируем миниатюру для ближайшего подходящего размера
let image = image::load_from_memory(&original_data).map_err(|_| {
ErrorInternalServerError("Failed to load image for thumbnail generation")
})?;
let thumbnails_bytes =
2024-10-22 06:38:30 +00:00
generate_thumbnails(&image).await?;
2024-10-21 21:36:42 +00:00
let thumbnail_bytes = thumbnails_bytes[&closest_width].clone();
// Загружаем миниатюру в S3
upload_to_s3(
2024-10-22 06:38:30 +00:00
&state.storj_client,
&state.storj_bucket,
&thumb_filekey,
2024-10-21 21:36:42 +00:00
thumbnail_bytes.clone(),
"image/jpeg",
)
.await?;
2024-10-22 06:52:05 +00:00
info!("thumb was saved in storj");
2024-10-21 21:36:42 +00:00
return Ok(HttpResponse::Ok()
.content_type("image/jpeg")
.body(thumbnail_bytes));
} else {
2024-10-22 06:52:05 +00:00
warn!("original was not found");
2024-10-21 21:36:42 +00:00
}
} else {
2024-10-22 06:52:05 +00:00
info!("thumb was found");
2024-10-22 06:38:30 +00:00
return serve_file(&thumb_filekey, &state).await;
2024-10-21 21:36:42 +00:00
}
}
// Если запрошен целый файл
2024-10-22 06:52:05 +00:00
info!("serving full file: {}", requested_path);
2024-10-22 06:38:30 +00:00
match serve_file(&requested_path, &state).await {
2024-10-21 21:36:42 +00:00
Ok(response) => Ok(response),
Err(e) => {
2024-10-22 06:52:05 +00:00
error!("error: {}", e);
2024-10-21 21:36:42 +00:00
Err(e)
}
}
}