From ca97ecf12859b56846adcb839162180e62fdb44a Mon Sep 17 00:00:00 2001 From: Untone Date: Tue, 22 Oct 2024 11:38:28 +0300 Subject: [PATCH] serve-file-fix --- src/app_state.rs | 24 +++++++++++++----------- src/handlers/serve_file.rs | 12 +++++------- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/app_state.rs b/src/app_state.rs index daab0f7..bba7f79 100644 --- a/src/app_state.rs +++ b/src/app_state.rs @@ -108,18 +108,20 @@ impl AppState { // Формируем список файлов без дубликатов по имени файла (без расширения) for object in objects.iter() { - if let Some(storj_objkey) = &object.key { - let filekey = storj_objkey.split('.') - .chain(std::iter::once("")) // Ensure the chain doesn't break on empty strings - .filter(|s| !s.is_empty()) // Filter out any empty strings - .map(|s| s.split('/')) // Map to Split iterator - .nth(0) // Get the first non-empty split result or default to &"" - .and_then(|s| s.last()) // Call last() on the resulting iterator if it exists, otherwise None - .unwrap_or(&""); - + if let Some(storj_filepath) = &object.key { + let filepath = match storj_filepath.ends_with("/webp") { + true => &storj_filepath.replace("/webp", ""), + false => storj_filepath, + }; + let mut parts = filepath.split('/').collect::>(); // Explicit type annotation + let filename = parts.pop().unwrap(); + let mut filename_parts = filename.split('.').collect::>(); + let _ext = filename_parts.pop().unwrap(); + let filekey = filename_parts.pop().unwrap(); + // Сохраняем список файлов в Redis, используя HSET для каждого файла let _: () = redis - .hset(PATH_MAPPING_KEY, filekey, storj_objkey) + .hset(PATH_MAPPING_KEY, filekey, storj_filepath) .await .expect("Failed to cache file in Redis"); } @@ -164,7 +166,7 @@ impl AppState { Ok(()) } - /// Получает путь в хранилище из ключа (имени файла) в Redis. + /// Получает путь в Storj из ключа (имени файла) в Redis. pub async fn get_path(&self, file_key: &str) -> Result, actix_web::Error> { let mut redis = self.redis.clone(); let new_path: Option = redis diff --git a/src/handlers/serve_file.rs b/src/handlers/serve_file.rs index db70437..8fcafcc 100644 --- a/src/handlers/serve_file.rs +++ b/src/handlers/serve_file.rs @@ -1,6 +1,5 @@ use actix_web::{error::ErrorInternalServerError, HttpResponse, Result}; use mime_guess::MimeGuess; -use log::warn; use crate::app_state::AppState; use crate::s3_utils::check_file_exists; @@ -9,21 +8,20 @@ use crate::s3_utils::check_file_exists; pub async fn serve_file(file_key: &str, state: &AppState) -> Result { // Проверяем наличие файла в Storj S3 if !check_file_exists(&state.storj_client, &state.storj_bucket, &file_key).await? { - warn!("{}", file_key); - return Err(ErrorInternalServerError("File not found in Storj")); + return Err(ErrorInternalServerError(format!("File {} not found in Storj", file_key))); } - let file_path = state.get_path(file_key).await.unwrap().unwrap(); + let file_path_in_storj = state.get_path(file_key).await.unwrap().unwrap(); // Получаем объект из Storj S3 let get_object_output = state .storj_client .get_object() .bucket(&state.storj_bucket) - .key(file_path.clone()) + .key(file_path_in_storj.clone()) .send() .await - .map_err(|_| ErrorInternalServerError("Failed to get object from Storj"))?; + .map_err(|_| ErrorInternalServerError(format!("Failed to get {} object from Storj", file_path_in_storj)))?; let data: aws_sdk_s3::primitives::AggregatedBytes = get_object_output .body @@ -32,7 +30,7 @@ pub async fn serve_file(file_key: &str, state: &AppState) -> Result