quoter/src/handlers/proxy.rs
Untone eac5c770fc
All checks were successful
deploy / deploy (push) Successful in 57s
thumbfix
2024-10-23 17:29:03 +03:00

193 lines
8.3 KiB
Rust

use actix_web::{error::ErrorInternalServerError, web, HttpRequest, HttpResponse, Result};
use log::{error, warn};
use crate::app_state::AppState;
use crate::handlers::serve_file::serve_file;
use crate::s3_utils::{check_file_exists, load_file_from_s3, upload_to_s3};
use crate::thumbnail::{find_closest_width, parse_file_path, thumbdata_save};
/// Обработчик для скачивания файла и генерации миниатюры, если она недоступна.
pub async fn proxy_handler(
_req: HttpRequest,
requested_res: web::Path<String>,
state: web::Data<AppState>,
) -> Result<HttpResponse, actix_web::Error> {
warn!("\t>>>\tGET {}", requested_res);
let normalized_path = if requested_res.ends_with("/webp") {
requested_res.replace("/webp", "")
} else {
requested_res.to_string()
};
// парсим GET запрос
let (base_filename, requested_width, extension) = parse_file_path(&normalized_path);
warn!("detected file extension: {}", extension);
warn!("base_filename: {}", base_filename);
warn!("requested width: {}", requested_width);
let ext = extension.as_str().to_lowercase();
warn!("normalized to lowercase: {}", ext);
let filekey = format!("{}.{}", base_filename, &ext);
warn!("filekey: {}", filekey);
let content_type = match ext.as_str() {
"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"));
},
};
warn!("content_type: {}", content_type);
return match state.get_path(&filekey).await {
Ok(Some(stored_path)) => {
warn!("stored_path: {}", stored_path);
// we have stored file path in storj
if check_file_exists(&state.storj_client, &state.bucket, &stored_path).await? {
if content_type.starts_with("image") {
return match requested_width == 0 {
true => serve_file(&stored_path, &state).await,
false => {
// find closest thumb width
let closest: u32 = find_closest_width(requested_width as u32);
let thumb_filename =
&format!("{}_{}.{}", base_filename, closest, ext);
return match check_file_exists(
&state.storj_client,
&state.bucket,
thumb_filename,
)
.await
{
Ok(true) => {
warn!("serve existed thumb file: {}", thumb_filename);
serve_file(thumb_filename, &state).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());
let _ = thumbdata_save(
filedata.clone(),
&state,
&filekey,
content_type.to_string(),
)
.await;
warn!("serve new thumb file: {}", thumb_filename);
serve_file(thumb_filename, &state).await
} else {
error!("cannot generate thumbnail");
Err(ErrorInternalServerError(
"cannot generate thumbnail",
))
}
}
Err(_) => {
Err(ErrorInternalServerError("failed to load thumbnail"))
}
};
}
};
}
// not image passing thumb generation
warn!("file is not an image");
}
// 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 {
error!("cannot upload to storj: {}", e);
} else {
warn!("file {} uploaded to storj", filekey);
}
let _ = thumbdata_save(filedata.clone(), &state, &filekey, content_type.to_string())
.await;
Ok(HttpResponse::Ok().content_type(content_type).body(filedata))
}
Err(err) => {
error!("cannot download {} from aws: {}", stored_path, err);
Err(ErrorInternalServerError(err))
},
};
}
Ok(None) => {
warn!("cannot find stored path for: {}", filekey);
let ct_parts = content_type.split("/").collect::<Vec<&str>>();
let filepath = format!("production/{}/{}.{}", ct_parts[0], base_filename, extension); // NOTE: original ext
match check_file_exists(&state.storj_client, &state.bucket, &filepath).await? {
true => {
warn!("file {} exists in storj", filepath);
}
false => {
warn!("file {} does not exist in storj", filepath);
}
}
match check_file_exists(&state.aws_client, &state.bucket, &filepath).await? {
true => {
warn!("file {} exists in aws", filepath);
}
false => {
warn!("file {} does not exist in aws", 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;
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))
},
}
},
Err(e) => {
error!("cannot get path from aws: {}", e);
Err(ErrorInternalServerError(e))
}
}
}