2024-10-23 14:46:30 +00:00
|
|
|
use actix_web::error::ErrorNotFound;
|
2024-10-21 21:36:42 +00:00
|
|
|
use actix_web::{error::ErrorInternalServerError, web, HttpRequest, HttpResponse, Result};
|
2024-10-23 08:55:21 +00:00
|
|
|
use log::{error, warn};
|
2024-10-21 21:36:42 +00:00
|
|
|
|
|
|
|
use crate::app_state::AppState;
|
|
|
|
use crate::handlers::serve_file::serve_file;
|
2024-10-22 17:35:51 +00:00
|
|
|
use crate::s3_utils::{check_file_exists, load_file_from_s3, upload_to_s3};
|
2024-10-23 14:29:03 +00:00
|
|
|
use crate::thumbnail::{find_closest_width, parse_file_path, thumbdata_save};
|
2024-10-21 21:36:42 +00:00
|
|
|
|
|
|
|
/// Обработчик для скачивания файла и генерации миниатюры, если она недоступна.
|
|
|
|
pub async fn proxy_handler(
|
2024-10-23 17:06:34 +00:00
|
|
|
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 18:19:40 +00:00
|
|
|
warn!("\t>>>\tGET {}", requested_res);
|
2024-10-22 19:56:12 +00:00
|
|
|
let normalized_path = if requested_res.ends_with("/webp") {
|
|
|
|
requested_res.replace("/webp", "")
|
|
|
|
} else {
|
|
|
|
requested_res.to_string()
|
2024-10-21 21:36:42 +00:00
|
|
|
};
|
|
|
|
|
2024-10-22 16:34:08 +00:00
|
|
|
// парсим GET запрос
|
2024-10-23 12:31:33 +00:00
|
|
|
let (base_filename, requested_width, extension) = parse_file_path(&normalized_path);
|
2024-10-23 12:02:33 +00:00
|
|
|
warn!("detected file extension: {}", extension);
|
2024-10-23 13:21:18 +00:00
|
|
|
warn!("base_filename: {}", base_filename);
|
|
|
|
warn!("requested width: {}", requested_width);
|
2024-10-23 12:02:33 +00:00
|
|
|
let ext = extension.as_str().to_lowercase();
|
|
|
|
warn!("normalized to lowercase: {}", ext);
|
2024-10-23 11:45:23 +00:00
|
|
|
let filekey = format!("{}.{}", base_filename, &ext);
|
2024-10-23 12:02:33 +00:00
|
|
|
warn!("filekey: {}", filekey);
|
2024-10-23 11:45:23 +00:00
|
|
|
let content_type = match ext.as_str() {
|
2024-10-23 10:31:05 +00:00
|
|
|
"jpg" | "jpeg" => "image/jpeg",
|
|
|
|
"png" => "image/png",
|
|
|
|
"webp" => "image/webp",
|
|
|
|
"gif" => "image/gif",
|
|
|
|
"mp3" => "audio/mpeg",
|
|
|
|
"wav" => "audio/x-wav",
|
|
|
|
"ogg" => "audio/ogg",
|
|
|
|
"aac" => "audio/aac",
|
|
|
|
"m4a" => "audio/m4a",
|
|
|
|
"flac" => "audio/flac",
|
|
|
|
_ => {
|
|
|
|
error!("unsupported file format");
|
|
|
|
return Err(ErrorInternalServerError("unsupported file format"));
|
|
|
|
},
|
|
|
|
};
|
2024-10-22 17:42:45 +00:00
|
|
|
|
2024-10-23 10:31:05 +00:00
|
|
|
warn!("content_type: {}", content_type);
|
2024-10-22 17:35:51 +00:00
|
|
|
|
2024-10-23 17:06:34 +00:00
|
|
|
let shout_id = match req.query_string().contains("s=") {
|
|
|
|
true => req.query_string().split("s=").collect::<Vec<&str>>().pop().unwrap_or(""),
|
|
|
|
false => ""
|
|
|
|
};
|
|
|
|
|
2024-10-23 10:31:05 +00:00
|
|
|
return match state.get_path(&filekey).await {
|
|
|
|
Ok(Some(stored_path)) => {
|
|
|
|
warn!("stored_path: {}", stored_path);
|
2024-10-23 17:32:07 +00:00
|
|
|
// Проверяем, существует ли файл в Storj
|
2024-10-23 10:31:05 +00:00
|
|
|
if check_file_exists(&state.storj_client, &state.bucket, &stored_path).await? {
|
|
|
|
if content_type.starts_with("image") {
|
2024-10-23 17:32:07 +00:00
|
|
|
if requested_width == 0 {
|
|
|
|
return serve_file(&stored_path, &state, shout_id).await;
|
|
|
|
} else {
|
|
|
|
// Находим ближайшую ширину для миниатюры
|
|
|
|
let closest: u32 = find_closest_width(requested_width as u32);
|
|
|
|
let thumb_filename = &format!("{}_{}.{}", base_filename, closest, ext);
|
|
|
|
|
|
|
|
// Проверяем, существует ли уже миниатюра в Storj
|
|
|
|
match check_file_exists(&state.storj_client, &state.bucket, thumb_filename).await {
|
|
|
|
Ok(true) => {
|
|
|
|
warn!("serve existed thumb file: {}", thumb_filename);
|
|
|
|
return serve_file(thumb_filename, &state, shout_id).await;
|
|
|
|
},
|
|
|
|
Ok(false) => {
|
|
|
|
// Миниатюра не существует, создаем и загружаем её
|
|
|
|
if let Ok(filedata) = load_file_from_s3(&state.storj_client, &state.bucket, &stored_path).await {
|
|
|
|
warn!("generate new thumb files: {}", stored_path);
|
|
|
|
warn!("{} bytes", filedata.len());
|
2024-10-23 10:31:05 +00:00
|
|
|
|
2024-10-23 17:32:07 +00:00
|
|
|
// Генерируем миниатюру и сохраняем
|
|
|
|
if let Ok(_) = thumbdata_save(filedata.clone(), &state, &filekey, content_type.to_string()).await {
|
2024-10-23 10:31:05 +00:00
|
|
|
warn!("serve new thumb file: {}", thumb_filename);
|
2024-10-23 17:32:07 +00:00
|
|
|
return serve_file(thumb_filename, &state, shout_id).await;
|
2024-10-23 10:31:05 +00:00
|
|
|
} else {
|
2024-10-23 14:20:25 +00:00
|
|
|
error!("cannot generate thumbnail");
|
2024-10-23 17:32:07 +00:00
|
|
|
return Err(ErrorInternalServerError("cannot generate thumbnail"));
|
2024-10-22 17:35:51 +00:00
|
|
|
}
|
2024-10-23 17:32:07 +00:00
|
|
|
} else {
|
|
|
|
error!("cannot load file from Storj to generate thumbnail");
|
|
|
|
return Err(ErrorInternalServerError("cannot generate thumbnail"));
|
2024-10-23 10:31:05 +00:00
|
|
|
}
|
2024-10-23 17:32:07 +00:00
|
|
|
}
|
|
|
|
Err(e) => {
|
|
|
|
error!("ошибка при проверке существования миниатюры: {}", e);
|
|
|
|
return Err(ErrorInternalServerError("failed to load thumbnail"));
|
|
|
|
}
|
2024-10-23 10:31:05 +00:00
|
|
|
}
|
2024-10-23 17:32:07 +00:00
|
|
|
}
|
2024-10-22 16:34:08 +00:00
|
|
|
}
|
2024-10-23 17:32:07 +00:00
|
|
|
// Если файл не изображение, продолжаем обработку
|
2024-10-23 12:45:05 +00:00
|
|
|
warn!("file is not an image");
|
2024-10-23 10:31:05 +00:00
|
|
|
}
|
2024-10-21 21:36:42 +00:00
|
|
|
|
2024-10-23 10:31:05 +00:00
|
|
|
// we need to download what stored_path keeping in aws
|
|
|
|
return match load_file_from_s3(&state.aws_client, &state.bucket, &stored_path).await
|
|
|
|
{
|
|
|
|
Ok(filedata) => {
|
|
|
|
warn!("download stored_path from aws: {:?}", stored_path);
|
|
|
|
if let Err(e) = upload_to_s3(
|
|
|
|
&state.storj_client,
|
|
|
|
&state.bucket,
|
|
|
|
&filekey,
|
|
|
|
filedata.clone(),
|
|
|
|
content_type,
|
|
|
|
)
|
|
|
|
.await {
|
2024-10-23 14:20:25 +00:00
|
|
|
error!("cannot upload to storj: {}", e);
|
2024-10-23 10:31:05 +00:00
|
|
|
} else {
|
|
|
|
warn!("file {} uploaded to storj", filekey);
|
|
|
|
}
|
2024-10-23 14:29:03 +00:00
|
|
|
let _ = thumbdata_save(filedata.clone(), &state, &filekey, content_type.to_string())
|
2024-10-23 10:31:05 +00:00
|
|
|
.await;
|
2024-10-22 17:35:51 +00:00
|
|
|
|
2024-10-23 10:31:05 +00:00
|
|
|
Ok(HttpResponse::Ok().content_type(content_type).body(filedata))
|
|
|
|
}
|
2024-10-23 12:45:05 +00:00
|
|
|
Err(err) => {
|
|
|
|
error!("cannot download {} from aws: {}", stored_path, err);
|
|
|
|
Err(ErrorInternalServerError(err))
|
|
|
|
},
|
2024-10-23 10:31:05 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
Ok(None) => {
|
2024-10-23 13:26:57 +00:00
|
|
|
warn!("cannot find stored path for: {}", filekey);
|
2024-10-23 13:38:34 +00:00
|
|
|
let ct_parts = content_type.split("/").collect::<Vec<&str>>();
|
2024-10-23 14:20:25 +00:00
|
|
|
let filepath = format!("production/{}/{}.{}", ct_parts[0], base_filename, extension); // NOTE: original ext
|
2024-10-23 13:38:34 +00:00
|
|
|
|
2024-10-23 14:46:30 +00:00
|
|
|
let exists_in_storj = check_file_exists(&state.storj_client, &state.bucket, &filepath).await?;
|
2024-10-23 13:38:34 +00:00
|
|
|
|
2024-10-23 14:46:30 +00:00
|
|
|
if exists_in_storj {
|
|
|
|
warn!("file {} exists in storj, try to generate thumbnails", filepath);
|
|
|
|
|
|
|
|
match load_file_from_s3(&state.aws_client, &state.bucket, &filepath).await {
|
|
|
|
Ok(filedata) => {
|
|
|
|
let _ = thumbdata_save(filedata.clone(), &state, &filekey, content_type.to_string()).await;
|
|
|
|
}
|
|
|
|
Err(e) => {
|
|
|
|
error!("cannot download {} from storj: {}", filekey, e);
|
|
|
|
return Err(ErrorInternalServerError(e));
|
|
|
|
}
|
2024-10-23 13:38:34 +00:00
|
|
|
}
|
2024-10-23 14:46:30 +00:00
|
|
|
} else {
|
|
|
|
warn!("file {} does not exist in storj", filepath);
|
2024-10-23 13:38:34 +00:00
|
|
|
}
|
|
|
|
|
2024-10-23 14:46:30 +00:00
|
|
|
let exists_in_aws = check_file_exists(&state.aws_client, &state.bucket, &filepath).await?;
|
|
|
|
if exists_in_aws {
|
|
|
|
match load_file_from_s3(&state.aws_client, &state.bucket, &filepath).await {
|
|
|
|
Ok(filedata) => {
|
|
|
|
let _ = thumbdata_save(filedata.clone(), &state, &filekey, content_type.to_string())
|
|
|
|
.await;
|
|
|
|
if let Err(e) = upload_to_s3(
|
|
|
|
&state.storj_client,
|
|
|
|
&state.bucket,
|
|
|
|
&filekey,
|
|
|
|
filedata.clone(),
|
|
|
|
content_type,
|
|
|
|
)
|
|
|
|
.await {
|
|
|
|
warn!("cannot upload to storj: {}", e);
|
|
|
|
} else {
|
|
|
|
warn!("file {} uploaded to storj", filekey);
|
|
|
|
}
|
|
|
|
Ok(HttpResponse::Ok().content_type(content_type).body(filedata))
|
|
|
|
},
|
|
|
|
Err(e) => {
|
|
|
|
error!("cannot download {} from aws: {}", filepath, e);
|
|
|
|
Err(ErrorInternalServerError(e))
|
|
|
|
},
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
error!("file {} does not exist in aws", filepath);
|
|
|
|
Err(ErrorNotFound("file does not exist"))
|
2024-10-22 17:35:51 +00:00
|
|
|
}
|
2024-10-23 10:31:05 +00:00
|
|
|
},
|
2024-10-23 12:45:05 +00:00
|
|
|
Err(e) => {
|
|
|
|
error!("cannot get path from aws: {}", e);
|
|
|
|
Err(ErrorInternalServerError(e))
|
|
|
|
}
|
2024-10-22 16:34:08 +00:00
|
|
|
}
|
|
|
|
}
|