This commit is contained in:
parent
1385f64824
commit
ca97ecf128
|
@ -108,18 +108,20 @@ impl AppState {
|
||||||
// Формируем список файлов без дубликатов по имени файла (без расширения)
|
// Формируем список файлов без дубликатов по имени файла (без расширения)
|
||||||
|
|
||||||
for object in objects.iter() {
|
for object in objects.iter() {
|
||||||
if let Some(storj_objkey) = &object.key {
|
if let Some(storj_filepath) = &object.key {
|
||||||
let filekey = storj_objkey.split('.')
|
let filepath = match storj_filepath.ends_with("/webp") {
|
||||||
.chain(std::iter::once("")) // Ensure the chain doesn't break on empty strings
|
true => &storj_filepath.replace("/webp", ""),
|
||||||
.filter(|s| !s.is_empty()) // Filter out any empty strings
|
false => storj_filepath,
|
||||||
.map(|s| s.split('/')) // Map to Split iterator
|
};
|
||||||
.nth(0) // Get the first non-empty split result or default to &""
|
let mut parts = filepath.split('/').collect::<Vec<&str>>(); // Explicit type annotation
|
||||||
.and_then(|s| s.last()) // Call last() on the resulting iterator if it exists, otherwise None
|
let filename = parts.pop().unwrap();
|
||||||
.unwrap_or(&"");
|
let mut filename_parts = filename.split('.').collect::<Vec<&str>>();
|
||||||
|
let _ext = filename_parts.pop().unwrap();
|
||||||
|
let filekey = filename_parts.pop().unwrap();
|
||||||
|
|
||||||
// Сохраняем список файлов в Redis, используя HSET для каждого файла
|
// Сохраняем список файлов в Redis, используя HSET для каждого файла
|
||||||
let _: () = redis
|
let _: () = redis
|
||||||
.hset(PATH_MAPPING_KEY, filekey, storj_objkey)
|
.hset(PATH_MAPPING_KEY, filekey, storj_filepath)
|
||||||
.await
|
.await
|
||||||
.expect("Failed to cache file in Redis");
|
.expect("Failed to cache file in Redis");
|
||||||
}
|
}
|
||||||
|
@ -164,7 +166,7 @@ impl AppState {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Получает путь в хранилище из ключа (имени файла) в Redis.
|
/// Получает путь в Storj из ключа (имени файла) в Redis.
|
||||||
pub async fn get_path(&self, file_key: &str) -> Result<Option<String>, actix_web::Error> {
|
pub async fn get_path(&self, file_key: &str) -> Result<Option<String>, actix_web::Error> {
|
||||||
let mut redis = self.redis.clone();
|
let mut redis = self.redis.clone();
|
||||||
let new_path: Option<String> = redis
|
let new_path: Option<String> = redis
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
use actix_web::{error::ErrorInternalServerError, HttpResponse, Result};
|
use actix_web::{error::ErrorInternalServerError, HttpResponse, Result};
|
||||||
use mime_guess::MimeGuess;
|
use mime_guess::MimeGuess;
|
||||||
use log::warn;
|
|
||||||
|
|
||||||
use crate::app_state::AppState;
|
use crate::app_state::AppState;
|
||||||
use crate::s3_utils::check_file_exists;
|
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<HttpResponse, actix_web::Error> {
|
pub async fn serve_file(file_key: &str, state: &AppState) -> Result<HttpResponse, actix_web::Error> {
|
||||||
// Проверяем наличие файла в Storj S3
|
// Проверяем наличие файла в Storj S3
|
||||||
if !check_file_exists(&state.storj_client, &state.storj_bucket, &file_key).await? {
|
if !check_file_exists(&state.storj_client, &state.storj_bucket, &file_key).await? {
|
||||||
warn!("{}", file_key);
|
return Err(ErrorInternalServerError(format!("File {} not found in Storj", file_key)));
|
||||||
return Err(ErrorInternalServerError("File not found in Storj"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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
|
// Получаем объект из Storj S3
|
||||||
let get_object_output = state
|
let get_object_output = state
|
||||||
.storj_client
|
.storj_client
|
||||||
.get_object()
|
.get_object()
|
||||||
.bucket(&state.storj_bucket)
|
.bucket(&state.storj_bucket)
|
||||||
.key(file_path.clone())
|
.key(file_path_in_storj.clone())
|
||||||
.send()
|
.send()
|
||||||
.await
|
.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
|
let data: aws_sdk_s3::primitives::AggregatedBytes = get_object_output
|
||||||
.body
|
.body
|
||||||
|
@ -32,7 +30,7 @@ pub async fn serve_file(file_key: &str, state: &AppState) -> Result<HttpResponse
|
||||||
.map_err(|_| ErrorInternalServerError("Failed to read object body"))?;
|
.map_err(|_| ErrorInternalServerError("Failed to read object body"))?;
|
||||||
|
|
||||||
let data_bytes = data.into_bytes();
|
let data_bytes = data.into_bytes();
|
||||||
let mime_type = MimeGuess::from_path(&file_path).first_or_octet_stream();
|
let mime_type = MimeGuess::from_path(&file_path_in_storj).first_or_octet_stream();
|
||||||
|
|
||||||
Ok(HttpResponse::Ok()
|
Ok(HttpResponse::Ok()
|
||||||
.content_type(mime_type.as_ref())
|
.content_type(mime_type.as_ref())
|
||||||
|
|
Loading…
Reference in New Issue
Block a user