@@ -6,6 +6,7 @@ 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};
|
||||
use crate::lookup::{find_file_by_pattern, get_mime_type};
|
||||
|
||||
/// Обработчик для скачивания файла и генерации миниатюры, если она недоступна.
|
||||
pub async fn proxy_handler(
|
||||
@@ -30,24 +31,26 @@ pub async fn proxy_handler(
|
||||
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",
|
||||
"jfif" => "image/jpeg",
|
||||
"heic" | "heif" => "image/heic",
|
||||
"tif" | "tiff" => "image/tiff",
|
||||
"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"));
|
||||
},
|
||||
let content_type = match get_mime_type(&ext) {
|
||||
Some(mime) => mime.to_string(),
|
||||
None => {
|
||||
let mut redis = state.redis.clone();
|
||||
match find_file_by_pattern(&mut redis, &base_filename).await {
|
||||
Ok(Some(found_file)) => {
|
||||
if let Some(found_ext) = found_file.split('.').last() {
|
||||
get_mime_type(found_ext)
|
||||
.unwrap_or("application/octet-stream")
|
||||
.to_string()
|
||||
} else {
|
||||
"application/octet-stream".to_string()
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
error!("unsupported file format");
|
||||
return Err(ErrorInternalServerError("unsupported file format"));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
warn!("content_type: {}", content_type);
|
||||
@@ -148,7 +151,7 @@ pub async fn proxy_handler(
|
||||
&state.bucket,
|
||||
&filekey,
|
||||
filedata.clone(),
|
||||
content_type,
|
||||
&content_type,
|
||||
).await {
|
||||
error!("Failed to upload to Storj: {} - Error: {}", filekey, e);
|
||||
} else {
|
||||
@@ -226,7 +229,7 @@ pub async fn proxy_handler(
|
||||
&state.bucket,
|
||||
&filekey,
|
||||
filedata.clone(),
|
||||
content_type,
|
||||
&content_type,
|
||||
)
|
||||
.await {
|
||||
warn!("cannot upload to storj: {}", e);
|
||||
|
@@ -4,9 +4,11 @@ use log::{error, warn};
|
||||
|
||||
use crate::app_state::AppState;
|
||||
use crate::auth::{get_id_by_token, user_added_file};
|
||||
use crate::s3_utils::{generate_key_with_extension, upload_to_s3};
|
||||
use crate::s3_utils::{self, upload_to_s3, generate_key_with_extension};
|
||||
use crate::lookup::store_file_info;
|
||||
use futures::TryStreamExt;
|
||||
use crate::handlers::MAX_WEEK_BYTES;
|
||||
use crate::thumbnail::convert_heic_to_jpeg;
|
||||
|
||||
/// Обработчик для аплоада файлов.
|
||||
pub async fn upload_handler(
|
||||
@@ -30,67 +32,90 @@ pub async fn upload_handler(
|
||||
let mut body = "ok".to_string();
|
||||
while let Ok(Some(field)) = payload.try_next().await {
|
||||
let mut field = field;
|
||||
let mut file_bytes = Vec::new();
|
||||
let mut file_size: u64 = 0;
|
||||
|
||||
let content_type = field.content_type().unwrap().to_string();
|
||||
let file_name = field
|
||||
.content_disposition()
|
||||
.unwrap()
|
||||
.get_filename()
|
||||
.map(|f| f.to_string());
|
||||
// Читаем данные файла
|
||||
while let Ok(Some(chunk)) = field.try_next().await {
|
||||
file_size += chunk.len() as u64;
|
||||
file_bytes.extend_from_slice(&chunk);
|
||||
}
|
||||
|
||||
if let Some(name) = file_name {
|
||||
let mut file_bytes = Vec::new();
|
||||
let mut file_size: u64 = 0;
|
||||
|
||||
// Читаем данные файла
|
||||
while let Ok(Some(chunk)) = field.try_next().await {
|
||||
file_size += chunk.len() as u64;
|
||||
file_bytes.extend_from_slice(&chunk);
|
||||
// Определяем MIME-тип из содержимого файла
|
||||
let detected_mime_type = match s3_utils::detect_mime_type(&file_bytes) {
|
||||
Some(mime) => mime,
|
||||
None => {
|
||||
warn!("Неподдерживаемый формат файла");
|
||||
return Err(actix_web::error::ErrorUnsupportedMediaType("Неподдерживаемый формат файла"));
|
||||
}
|
||||
};
|
||||
|
||||
// Проверяем, что добавление файла не превышает лимит квоты
|
||||
if this_week_amount + file_size > MAX_WEEK_BYTES {
|
||||
warn!("Quota would exceed limit: current={}, adding={}, limit={}",
|
||||
this_week_amount, file_size, MAX_WEEK_BYTES);
|
||||
return Err(actix_web::error::ErrorUnauthorized("Quota exceeded"));
|
||||
}
|
||||
|
||||
// Загружаем файл в S3 storj с использованием ключа в нижнем регистре
|
||||
let filekey = generate_key_with_extension(name.clone(), content_type.to_owned());
|
||||
let orig_path = name.clone();
|
||||
|
||||
match upload_to_s3(
|
||||
&state.storj_client,
|
||||
&state.bucket,
|
||||
&filekey,
|
||||
file_bytes.clone(),
|
||||
&content_type,
|
||||
).await {
|
||||
Ok(_) => {
|
||||
warn!("file {} uploaded to storj, incrementing quota by {} bytes", filekey, file_size);
|
||||
// Инкрементируем квоту только после успешной загрузки
|
||||
if let Err(e) = state.increment_uploaded_bytes(&user_id, file_size).await {
|
||||
error!("Failed to increment quota: {}", e);
|
||||
// Можно добавить откат загрузки файла здесь
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
// Сохраняем информацию о загруженном файле
|
||||
user_added_file(&mut state.redis.clone(), &user_id, &filekey).await?;
|
||||
state.set_path(&filekey, &orig_path).await;
|
||||
|
||||
// Логируем новое значение квоты
|
||||
if let Ok(new_quota) = state.get_or_create_quota(&user_id).await {
|
||||
warn!("New quota for user {}: {} bytes", user_id, new_quota);
|
||||
}
|
||||
|
||||
body = filekey;
|
||||
}
|
||||
// Для HEIC файлов конвертируем в JPEG
|
||||
let (file_bytes, content_type) = if detected_mime_type == "image/heic" {
|
||||
match convert_heic_to_jpeg(&file_bytes) {
|
||||
Ok(jpeg_data) => (jpeg_data, "image/jpeg".to_string()),
|
||||
Err(e) => {
|
||||
warn!("Failed to upload to storj: {}", e);
|
||||
return Err(actix_web::error::ErrorInternalServerError(e));
|
||||
warn!("Failed to convert HEIC to JPEG: {}", e);
|
||||
(file_bytes, detected_mime_type)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
(file_bytes, detected_mime_type)
|
||||
};
|
||||
|
||||
// Получаем расширение из MIME-типа
|
||||
let extension = match s3_utils::get_extension_from_mime(&content_type) {
|
||||
Some(ext) => ext,
|
||||
None => {
|
||||
warn!("Неподдерживаемый тип содержимого: {}", content_type);
|
||||
return Err(actix_web::error::ErrorUnsupportedMediaType("Неподдерживаемый тип содержимого"));
|
||||
}
|
||||
};
|
||||
|
||||
// Проверяем, что добавление файла не превышает лимит квоты
|
||||
if this_week_amount + file_size > MAX_WEEK_BYTES {
|
||||
warn!("Quota would exceed limit: current={}, adding={}, limit={}",
|
||||
this_week_amount, file_size, MAX_WEEK_BYTES);
|
||||
return Err(actix_web::error::ErrorUnauthorized("Quota exceeded"));
|
||||
}
|
||||
|
||||
// Генерируем имя файла с правильным расширением
|
||||
let filename = format!("{}.{}", uuid::Uuid::new_v4(), extension);
|
||||
|
||||
// Загружаем файл в S3 storj
|
||||
match upload_to_s3(
|
||||
&state.storj_client,
|
||||
&state.bucket,
|
||||
&filename,
|
||||
file_bytes,
|
||||
&content_type,
|
||||
).await {
|
||||
Ok(_) => {
|
||||
warn!("file {} uploaded to storj, incrementing quota by {} bytes", filename, file_size);
|
||||
if let Err(e) = state.increment_uploaded_bytes(&user_id, file_size).await {
|
||||
error!("Failed to increment quota: {}", e);
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
// Сохраняем информацию о файле в Redis
|
||||
let mut redis = state.redis.clone();
|
||||
store_file_info(&mut redis, &filename, &content_type).await?;
|
||||
user_added_file(&mut redis, &user_id, &filename).await?;
|
||||
|
||||
// Сохраняем маппинг пути
|
||||
let generated_key = generate_key_with_extension(filename.clone(), content_type.clone());
|
||||
state.set_path(&filename, &generated_key).await;
|
||||
|
||||
if let Ok(new_quota) = state.get_or_create_quota(&user_id).await {
|
||||
warn!("New quota for user {}: {} bytes", user_id, new_quota);
|
||||
}
|
||||
|
||||
body = filename;
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("Failed to upload to storj: {}", e);
|
||||
return Err(actix_web::error::ErrorInternalServerError(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(HttpResponse::Ok().body(body))
|
||||
|
65
src/lookup.rs
Normal file
65
src/lookup.rs
Normal file
@@ -0,0 +1,65 @@
|
||||
use std::collections::HashMap;
|
||||
use actix_web::error::ErrorInternalServerError;
|
||||
use once_cell::sync::Lazy;
|
||||
use redis::aio::MultiplexedConnection;
|
||||
use redis::AsyncCommands;
|
||||
|
||||
pub static MIME_TYPES: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
|
||||
let mut m = HashMap::new();
|
||||
// Изображения
|
||||
m.insert("jpg", "image/jpeg");
|
||||
m.insert("jpeg", "image/jpeg");
|
||||
m.insert("jfif", "image/jpeg");
|
||||
m.insert("png", "image/png");
|
||||
m.insert("webp", "image/webp");
|
||||
m.insert("gif", "image/gif");
|
||||
m.insert("heic", "image/heic");
|
||||
m.insert("heif", "image/heic");
|
||||
m.insert("tif", "image/tiff");
|
||||
m.insert("tiff", "image/tiff");
|
||||
// Аудио
|
||||
m.insert("mp3", "audio/mpeg");
|
||||
m.insert("wav", "audio/x-wav");
|
||||
m.insert("ogg", "audio/ogg");
|
||||
m.insert("aac", "audio/aac");
|
||||
m.insert("m4a", "audio/m4a");
|
||||
m.insert("flac", "audio/flac");
|
||||
m
|
||||
});
|
||||
|
||||
pub fn get_mime_type(extension: &str) -> Option<&'static str> {
|
||||
MIME_TYPES.get(extension).copied()
|
||||
}
|
||||
|
||||
|
||||
/// Ищет файл в Redis по шаблону имени
|
||||
pub async fn find_file_by_pattern(
|
||||
redis: &mut MultiplexedConnection,
|
||||
pattern: &str,
|
||||
) -> Result<Option<String>, actix_web::Error> {
|
||||
let pattern_key = format!("files:*{}*", pattern);
|
||||
let files: Vec<String> = redis
|
||||
.keys(&pattern_key)
|
||||
.await
|
||||
.map_err(|_| ErrorInternalServerError("Failed to search files in Redis"))?;
|
||||
|
||||
if files.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(files[0].clone()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Сохраняет файл в Redis с его MIME-типом
|
||||
pub async fn store_file_info(
|
||||
redis: &mut MultiplexedConnection,
|
||||
filename: &str,
|
||||
mime_type: &str,
|
||||
) -> Result<(), actix_web::Error> {
|
||||
let file_key = format!("files:{}", filename);
|
||||
redis
|
||||
.set::<_, _, ()>(&file_key, mime_type)
|
||||
.await
|
||||
.map_err(|_| ErrorInternalServerError("Failed to store file info in Redis"))?;
|
||||
Ok(())
|
||||
}
|
@@ -1,5 +1,6 @@
|
||||
mod app_state;
|
||||
mod auth;
|
||||
mod lookup;
|
||||
mod handlers;
|
||||
mod s3_utils;
|
||||
mod thumbnail;
|
||||
|
@@ -2,6 +2,7 @@ use actix_web::error::ErrorInternalServerError;
|
||||
use aws_sdk_s3::{error::SdkError, primitives::ByteStream, Client as S3Client};
|
||||
use mime_guess::mime;
|
||||
use std::str::FromStr;
|
||||
use infer::get;
|
||||
|
||||
/// Загружает файл в S3 хранилище.
|
||||
pub async fn upload_to_s3(
|
||||
@@ -101,4 +102,21 @@ pub async fn get_s3_filelist(client: &S3Client, bucket: &str) -> Vec<[std::strin
|
||||
}
|
||||
}
|
||||
filenames
|
||||
}
|
||||
|
||||
pub fn detect_mime_type(bytes: &[u8]) -> Option<String> {
|
||||
let kind = get(bytes)?;
|
||||
Some(kind.mime_type().to_string())
|
||||
}
|
||||
|
||||
pub fn get_extension_from_mime(mime_type: &str) -> Option<&str> {
|
||||
match mime_type {
|
||||
"image/jpeg" => Some("jpg"),
|
||||
"image/png" => Some("png"),
|
||||
"image/gif" => Some("gif"),
|
||||
"image/webp" => Some("webp"),
|
||||
"image/heic" => Some("heic"),
|
||||
"image/tiff" => Some("tiff"),
|
||||
_ => None
|
||||
}
|
||||
}
|
@@ -195,3 +195,34 @@ pub fn find_closest_width(requested_width: u32) -> u32 {
|
||||
.min_by_key(|&&width| (width as i32 - requested_width as i32).abs())
|
||||
.unwrap_or(&THUMB_WIDTHS[0]) // Возвращаем самый маленький размер, если ничего не подошло
|
||||
}
|
||||
|
||||
/// Конвертирует HEIC в JPEG
|
||||
pub fn convert_heic_to_jpeg(data: &[u8]) -> Result<Vec<u8>, actix_web::Error> {
|
||||
// Пробуем прочитать как обычное изображение
|
||||
if let Ok(img) = image::load_from_memory(data) {
|
||||
let mut buffer = Vec::new();
|
||||
img.write_to(&mut Cursor::new(&mut buffer), ImageFormat::Jpeg)
|
||||
.map_err(|e| actix_web::error::ErrorInternalServerError(format!("Failed to convert to JPEG: {}", e)))?;
|
||||
return Ok(buffer);
|
||||
}
|
||||
|
||||
// Если не получилось, пробуем через exif
|
||||
let mut cursor = Cursor::new(data);
|
||||
match exif::Reader::new().read_from_container(&mut cursor) {
|
||||
Ok(_exif) => {
|
||||
// Конвертируем в JPEG
|
||||
let img = image::load_from_memory(data)
|
||||
.map_err(|e| actix_web::error::ErrorInternalServerError(format!("Failed to load HEIC: {}", e)))?;
|
||||
|
||||
let mut buffer = Vec::new();
|
||||
img.write_to(&mut Cursor::new(&mut buffer), ImageFormat::Jpeg)
|
||||
.map_err(|e| actix_web::error::ErrorInternalServerError(format!("Failed to convert to JPEG: {}", e)))?;
|
||||
|
||||
Ok(buffer)
|
||||
}
|
||||
Err(e) => Err(actix_web::error::ErrorInternalServerError(format!(
|
||||
"Failed to process HEIC: {}",
|
||||
e
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user