fmt
This commit is contained in:
@@ -1,9 +1,9 @@
|
||||
use crate::s3_utils::get_s3_filelist;
|
||||
use actix_web::error::ErrorInternalServerError;
|
||||
use aws_config::BehaviorVersion;
|
||||
use aws_sdk_s3::{config::Credentials, Client as S3Client};
|
||||
use aws_sdk_s3::{Client as S3Client, config::Credentials};
|
||||
use log::warn;
|
||||
use redis::{aio::MultiplexedConnection, AsyncCommands, Client as RedisClient};
|
||||
use redis::{AsyncCommands, Client as RedisClient, aio::MultiplexedConnection};
|
||||
use std::env;
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -15,7 +15,7 @@ pub struct AppState {
|
||||
}
|
||||
|
||||
const PATH_MAPPING_KEY: &str = "filepath_mapping"; // Ключ для хранения маппинга путей
|
||||
// Убираем TTL для квоты - она должна быть постоянной на пользователя
|
||||
// Убираем TTL для квоты - она должна быть постоянной на пользователя
|
||||
|
||||
impl AppState {
|
||||
/// Инициализация нового состояния приложения.
|
||||
|
||||
17
src/auth.rs
17
src/auth.rs
@@ -1,12 +1,12 @@
|
||||
use actix_web::error::ErrorInternalServerError;
|
||||
use redis::{aio::MultiplexedConnection, AsyncCommands};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{collections::HashMap, env, error::Error};
|
||||
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
|
||||
use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode};
|
||||
use log::{info, warn};
|
||||
use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE};
|
||||
use redis::{AsyncCommands, aio::MultiplexedConnection};
|
||||
use reqwest::Client as HTTPClient;
|
||||
use reqwest::header::{CONTENT_TYPE, HeaderMap, HeaderValue};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
use std::{collections::HashMap, env, error::Error};
|
||||
|
||||
// Старые структуры для совместимости с get_id_by_token
|
||||
#[derive(Deserialize)]
|
||||
@@ -129,7 +129,10 @@ fn decode_jwt_token(token: &str) -> Result<TokenClaims, Box<dyn Error>> {
|
||||
info!("JWT token valid until: {} (current: {})", exp, current_time);
|
||||
}
|
||||
|
||||
info!("Successfully decoded and validated JWT token for user: {}", claims.user_id);
|
||||
info!(
|
||||
"Successfully decoded and validated JWT token for user: {}",
|
||||
claims.user_id
|
||||
);
|
||||
Ok(claims)
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -209,7 +212,7 @@ pub async fn get_user_by_token(
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs()
|
||||
.to_string()
|
||||
.to_string(),
|
||||
),
|
||||
auth_data: None,
|
||||
device_info: None,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use actix_web::error::ErrorNotFound;
|
||||
use actix_web::{error::ErrorInternalServerError, web, HttpRequest, HttpResponse, Result};
|
||||
use log::{info, error, warn};
|
||||
use actix_web::{HttpRequest, HttpResponse, Result, error::ErrorInternalServerError, web};
|
||||
use log::{error, info, warn};
|
||||
|
||||
use crate::app_state::AppState;
|
||||
use crate::handlers::serve_file::serve_file;
|
||||
@@ -35,7 +35,9 @@ pub async fn proxy_handler(
|
||||
};
|
||||
|
||||
// Проверяем If-None-Match заголовок для кэширования
|
||||
let client_etag = req.headers().get("if-none-match")
|
||||
let client_etag = req
|
||||
.headers()
|
||||
.get("if-none-match")
|
||||
.and_then(|h| h.to_str().ok());
|
||||
|
||||
// парсим GET запрос
|
||||
@@ -43,7 +45,10 @@ pub async fn proxy_handler(
|
||||
let ext = extension.as_str().to_lowercase();
|
||||
let filekey = format!("{}.{}", base_filename, &ext);
|
||||
|
||||
info!("Parsed request - base: {}, width: {}, ext: {}", base_filename, requested_width, ext);
|
||||
info!(
|
||||
"Parsed request - base: {}, width: {}, ext: {}",
|
||||
base_filename, requested_width, ext
|
||||
);
|
||||
|
||||
// Генерируем ETag для кэширования
|
||||
let file_etag = format!("\"{}\"", &filekey);
|
||||
@@ -77,7 +82,6 @@ pub async fn proxy_handler(
|
||||
|
||||
info!("Content-Type: {}", content_type);
|
||||
|
||||
|
||||
return match state.get_path(&filekey).await {
|
||||
Ok(Some(stored_path)) => {
|
||||
warn!("Found stored path in DB: {}", stored_path);
|
||||
@@ -111,8 +115,7 @@ pub async fn proxy_handler(
|
||||
}
|
||||
Ok(false) => {
|
||||
// Миниатюра не существует, возвращаем оригинал и запускаем генерацию миниатюры
|
||||
let original_file =
|
||||
serve_file(&stored_path, &state).await?;
|
||||
let original_file = serve_file(&stored_path, &state).await?;
|
||||
|
||||
// Запускаем асинхронную задачу для генерации миниатюры
|
||||
let state_clone = state.clone();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use actix_web::{web, HttpRequest, HttpResponse, Result};
|
||||
use actix_web::{HttpRequest, HttpResponse, Result, web};
|
||||
use log::warn;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -34,16 +34,14 @@ pub async fn get_quota_handler(
|
||||
return Err(actix_web::error::ErrorUnauthorized("Unauthorized"));
|
||||
}
|
||||
|
||||
let _admin_id = get_id_by_token(token.unwrap())
|
||||
.await
|
||||
.map_err(|e| {
|
||||
let error_msg = if e.to_string().contains("expired") {
|
||||
"Admin token has expired"
|
||||
} else {
|
||||
"Invalid admin token"
|
||||
};
|
||||
actix_web::error::ErrorUnauthorized(error_msg)
|
||||
})?;
|
||||
let _admin_id = get_id_by_token(token.unwrap()).await.map_err(|e| {
|
||||
let error_msg = if e.to_string().contains("expired") {
|
||||
"Admin token has expired"
|
||||
} else {
|
||||
"Invalid admin token"
|
||||
};
|
||||
actix_web::error::ErrorUnauthorized(error_msg)
|
||||
})?;
|
||||
|
||||
// Получаем user_id из query параметров
|
||||
let user_id = req
|
||||
@@ -81,16 +79,14 @@ pub async fn increase_quota_handler(
|
||||
return Err(actix_web::error::ErrorUnauthorized("Unauthorized"));
|
||||
}
|
||||
|
||||
let _admin_id = get_id_by_token(token.unwrap())
|
||||
.await
|
||||
.map_err(|e| {
|
||||
let error_msg = if e.to_string().contains("expired") {
|
||||
"Admin token has expired"
|
||||
} else {
|
||||
"Invalid admin token"
|
||||
};
|
||||
actix_web::error::ErrorUnauthorized(error_msg)
|
||||
})?;
|
||||
let _admin_id = get_id_by_token(token.unwrap()).await.map_err(|e| {
|
||||
let error_msg = if e.to_string().contains("expired") {
|
||||
"Admin token has expired"
|
||||
} else {
|
||||
"Invalid admin token"
|
||||
};
|
||||
actix_web::error::ErrorUnauthorized(error_msg)
|
||||
})?;
|
||||
|
||||
let additional_bytes = quota_data
|
||||
.additional_bytes
|
||||
@@ -137,16 +133,14 @@ pub async fn set_quota_handler(
|
||||
return Err(actix_web::error::ErrorUnauthorized("Unauthorized"));
|
||||
}
|
||||
|
||||
let _admin_id = get_id_by_token(token.unwrap())
|
||||
.await
|
||||
.map_err(|e| {
|
||||
let error_msg = if e.to_string().contains("expired") {
|
||||
"Admin token has expired"
|
||||
} else {
|
||||
"Invalid admin token"
|
||||
};
|
||||
actix_web::error::ErrorUnauthorized(error_msg)
|
||||
})?;
|
||||
let _admin_id = get_id_by_token(token.unwrap()).await.map_err(|e| {
|
||||
let error_msg = if e.to_string().contains("expired") {
|
||||
"Admin token has expired"
|
||||
} else {
|
||||
"Invalid admin token"
|
||||
};
|
||||
actix_web::error::ErrorUnauthorized(error_msg)
|
||||
})?;
|
||||
|
||||
let new_quota_bytes = quota_data
|
||||
.new_quota_bytes
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use actix_web::{error::ErrorInternalServerError, HttpResponse, Result};
|
||||
use actix_web::{HttpResponse, Result, error::ErrorInternalServerError};
|
||||
use mime_guess::MimeGuess;
|
||||
|
||||
use crate::app_state::AppState;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use actix_multipart::Multipart;
|
||||
use actix_web::{web, HttpRequest, HttpResponse, Result};
|
||||
use actix_web::{HttpRequest, HttpResponse, Result, web};
|
||||
use log::{error, info, warn};
|
||||
|
||||
use crate::app_state::AppState;
|
||||
@@ -27,7 +27,9 @@ pub async fn upload_handler(
|
||||
|
||||
if token.is_none() {
|
||||
warn!("Upload attempt without authorization token");
|
||||
return Err(actix_web::error::ErrorUnauthorized("Authorization token required"));
|
||||
return Err(actix_web::error::ErrorUnauthorized(
|
||||
"Authorization token required",
|
||||
));
|
||||
}
|
||||
|
||||
let token = token.unwrap();
|
||||
@@ -35,15 +37,16 @@ pub async fn upload_handler(
|
||||
// Сначала валидируем токен
|
||||
if !validate_token(token).unwrap_or(false) {
|
||||
warn!("Token validation failed");
|
||||
return Err(actix_web::error::ErrorUnauthorized("Invalid or expired token"));
|
||||
return Err(actix_web::error::ErrorUnauthorized(
|
||||
"Invalid or expired token",
|
||||
));
|
||||
}
|
||||
|
||||
// Затем извлекаем user_id
|
||||
let user_id = extract_user_id_from_token(token)
|
||||
.map_err(|e| {
|
||||
warn!("Failed to extract user_id from token: {}", e);
|
||||
actix_web::error::ErrorUnauthorized("Invalid authorization token")
|
||||
})?;
|
||||
let user_id = extract_user_id_from_token(token).map_err(|e| {
|
||||
warn!("Failed to extract user_id from token: {}", e);
|
||||
actix_web::error::ErrorUnauthorized("Invalid authorization token")
|
||||
})?;
|
||||
|
||||
// Получаем текущую квоту пользователя
|
||||
let current_quota: u64 = state.get_or_create_quota(&user_id).await.unwrap_or(0);
|
||||
@@ -51,8 +54,13 @@ pub async fn upload_handler(
|
||||
|
||||
// Предварительная проверка: есть ли вообще место для файлов
|
||||
if current_quota >= MAX_USER_QUOTA_BYTES {
|
||||
warn!("Author {} quota already at maximum: {}", user_id, current_quota);
|
||||
return Err(actix_web::error::ErrorPayloadTooLarge("Author quota limit exceeded"));
|
||||
warn!(
|
||||
"Author {} quota already at maximum: {}",
|
||||
user_id, current_quota
|
||||
);
|
||||
return Err(actix_web::error::ErrorPayloadTooLarge(
|
||||
"Author quota limit exceeded",
|
||||
));
|
||||
}
|
||||
|
||||
let mut uploaded_files = Vec::new();
|
||||
@@ -68,16 +76,27 @@ pub async fn upload_handler(
|
||||
|
||||
// Проверка лимита одного файла
|
||||
if file_size + chunk_size > MAX_SINGLE_FILE_BYTES {
|
||||
warn!("File size exceeds single file limit: {} > {}",
|
||||
file_size + chunk_size, MAX_SINGLE_FILE_BYTES);
|
||||
return Err(actix_web::error::ErrorPayloadTooLarge("Single file size limit exceeded"));
|
||||
warn!(
|
||||
"File size exceeds single file limit: {} > {}",
|
||||
file_size + chunk_size,
|
||||
MAX_SINGLE_FILE_BYTES
|
||||
);
|
||||
return Err(actix_web::error::ErrorPayloadTooLarge(
|
||||
"Single file size limit exceeded",
|
||||
));
|
||||
}
|
||||
|
||||
// Проверка общей квоты пользователя
|
||||
if current_quota + file_size + chunk_size > MAX_USER_QUOTA_BYTES {
|
||||
warn!("Upload would exceed user quota: current={}, adding={}, limit={}",
|
||||
current_quota, file_size + chunk_size, MAX_USER_QUOTA_BYTES);
|
||||
return Err(actix_web::error::ErrorPayloadTooLarge("Author quota limit would be exceeded"));
|
||||
warn!(
|
||||
"Upload would exceed user quota: current={}, adding={}, limit={}",
|
||||
current_quota,
|
||||
file_size + chunk_size,
|
||||
MAX_USER_QUOTA_BYTES
|
||||
);
|
||||
return Err(actix_web::error::ErrorPayloadTooLarge(
|
||||
"Author quota limit would be exceeded",
|
||||
));
|
||||
}
|
||||
|
||||
file_size += chunk_size;
|
||||
@@ -140,13 +159,16 @@ pub async fn upload_handler(
|
||||
.await
|
||||
{
|
||||
Ok(_) => {
|
||||
info!("File {} successfully uploaded to S3 ({} bytes)", filename, file_size);
|
||||
info!(
|
||||
"File {} successfully uploaded to S3 ({} bytes)",
|
||||
filename, file_size
|
||||
);
|
||||
|
||||
// Обновляем квоту пользователя
|
||||
if let Err(e) = state.increment_uploaded_bytes(&user_id, file_size).await {
|
||||
error!("Failed to increment quota for user {}: {}", user_id, e);
|
||||
return Err(actix_web::error::ErrorInternalServerError(
|
||||
"Failed to update user quota"
|
||||
"Failed to update user quota",
|
||||
));
|
||||
}
|
||||
|
||||
@@ -163,14 +185,18 @@ pub async fn upload_handler(
|
||||
}
|
||||
|
||||
// Сохраняем маппинг пути
|
||||
let generated_key = generate_key_with_extension(filename.clone(), content_type.clone());
|
||||
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 {
|
||||
info!("Updated quota for user {}: {} bytes ({:.1}% used)",
|
||||
user_id, new_quota,
|
||||
(new_quota as f64 / MAX_USER_QUOTA_BYTES as f64) * 100.0);
|
||||
info!(
|
||||
"Updated quota for user {}: {} bytes ({:.1}% used)",
|
||||
user_id,
|
||||
new_quota,
|
||||
(new_quota as f64 / MAX_USER_QUOTA_BYTES as f64) * 100.0
|
||||
);
|
||||
}
|
||||
|
||||
uploaded_files.push(filename);
|
||||
@@ -178,7 +204,7 @@ pub async fn upload_handler(
|
||||
Err(e) => {
|
||||
error!("Failed to upload file to S3: {}", e);
|
||||
return Err(actix_web::error::ErrorInternalServerError(
|
||||
"File upload failed"
|
||||
"File upload failed",
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -188,7 +214,9 @@ pub async fn upload_handler(
|
||||
match uploaded_files.len() {
|
||||
0 => {
|
||||
warn!("No files were uploaded");
|
||||
Err(actix_web::error::ErrorBadRequest("No files provided or all files were empty"))
|
||||
Err(actix_web::error::ErrorBadRequest(
|
||||
"No files provided or all files were empty",
|
||||
))
|
||||
}
|
||||
1 => {
|
||||
info!("Successfully uploaded 1 file: {}", uploaded_files[0]);
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use actix_web::{web, HttpRequest, HttpResponse, Result};
|
||||
use actix_web::{HttpRequest, HttpResponse, Result, web};
|
||||
use log::{error, info, warn};
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::app_state::AppState;
|
||||
use crate::auth::{get_user_by_token, Author, validate_token};
|
||||
use crate::auth::{Author, get_user_by_token, validate_token};
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct UserWithQuotaResponse {
|
||||
@@ -40,7 +40,9 @@ pub async fn get_current_user_handler(
|
||||
|
||||
if token.is_none() {
|
||||
warn!("Request for current user without authorization token");
|
||||
return Err(actix_web::error::ErrorUnauthorized("Authorization token required"));
|
||||
return Err(actix_web::error::ErrorUnauthorized(
|
||||
"Authorization token required",
|
||||
));
|
||||
}
|
||||
|
||||
let token = token.unwrap();
|
||||
@@ -48,7 +50,9 @@ pub async fn get_current_user_handler(
|
||||
// Сначала валидируем токен
|
||||
if !validate_token(token).unwrap_or(false) {
|
||||
warn!("Token validation failed in user endpoint");
|
||||
return Err(actix_web::error::ErrorUnauthorized("Invalid or expired token"));
|
||||
return Err(actix_web::error::ErrorUnauthorized(
|
||||
"Invalid or expired token",
|
||||
));
|
||||
}
|
||||
|
||||
info!("Getting user info for valid token");
|
||||
@@ -57,8 +61,10 @@ pub async fn get_current_user_handler(
|
||||
let mut redis = state.redis.clone();
|
||||
let user = match get_user_by_token(token, &mut redis).await {
|
||||
Ok(user) => {
|
||||
info!("Successfully retrieved user info: user_id={}, username={:?}",
|
||||
user.user_id, user.username);
|
||||
info!(
|
||||
"Successfully retrieved user info: user_id={}, username={:?}",
|
||||
user.user_id, user.username
|
||||
);
|
||||
user
|
||||
}
|
||||
Err(e) => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use actix_web::error::ErrorInternalServerError;
|
||||
use once_cell::sync::Lazy;
|
||||
use redis::aio::MultiplexedConnection;
|
||||
use redis::AsyncCommands;
|
||||
use redis::aio::MultiplexedConnection;
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub static MIME_TYPES: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
|
||||
|
||||
@@ -7,15 +7,15 @@ mod thumbnail;
|
||||
|
||||
use actix_cors::Cors;
|
||||
use actix_web::{
|
||||
App, HttpServer,
|
||||
http::header::{self, HeaderName},
|
||||
middleware::Logger,
|
||||
web, App, HttpServer,
|
||||
web,
|
||||
};
|
||||
use app_state::AppState;
|
||||
|
||||
use handlers::{
|
||||
get_current_user_handler, get_quota_handler,
|
||||
increase_quota_handler, proxy_handler,
|
||||
get_current_user_handler, get_quota_handler, increase_quota_handler, proxy_handler,
|
||||
set_quota_handler, upload_handler,
|
||||
};
|
||||
use log::warn;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use actix_web::error::ErrorInternalServerError;
|
||||
use aws_sdk_s3::{error::SdkError, primitives::ByteStream, Client as S3Client};
|
||||
use aws_sdk_s3::{Client as S3Client, error::SdkError, primitives::ByteStream};
|
||||
use infer::get;
|
||||
use mime_guess::mime;
|
||||
use std::str::FromStr;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use actix_web::error::ErrorInternalServerError;
|
||||
use image::{imageops::FilterType, DynamicImage, ImageFormat};
|
||||
use image::{DynamicImage, ImageFormat, imageops::FilterType};
|
||||
use log::warn;
|
||||
use std::{collections::HashMap, io::Cursor};
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use actix_web::{test, web, App, HttpResponse};
|
||||
use actix_web::{App, HttpResponse, test, web};
|
||||
|
||||
/// Простой тест health check
|
||||
#[actix_web::test]
|
||||
@@ -332,7 +332,11 @@ async fn test_thumbnail_path_parsing() {
|
||||
|
||||
// Ищем последний underscore перед расширением
|
||||
let dot_pos = path.rfind('.');
|
||||
let name_part = if let Some(pos) = dot_pos { &path[..pos] } else { path };
|
||||
let name_part = if let Some(pos) = dot_pos {
|
||||
&path[..pos]
|
||||
} else {
|
||||
path
|
||||
};
|
||||
|
||||
// Ищем underscore для ширины
|
||||
if let Some(underscore_pos) = name_part.rfind('_') {
|
||||
@@ -340,14 +344,22 @@ async fn test_thumbnail_path_parsing() {
|
||||
let width_part = &name_part[underscore_pos + 1..];
|
||||
|
||||
if let Ok(width) = width_part.parse::<u32>() {
|
||||
let ext = if let Some(pos) = dot_pos { path[pos + 1..].to_string() } else { "".to_string() };
|
||||
let ext = if let Some(pos) = dot_pos {
|
||||
path[pos + 1..].to_string()
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
return (base, width, ext);
|
||||
}
|
||||
}
|
||||
|
||||
// Если не нашли ширину, возвращаем как есть
|
||||
let base = name_part.to_string();
|
||||
let ext = if let Some(pos) = dot_pos { path[pos + 1..].to_string() } else { "".to_string() };
|
||||
let ext = if let Some(pos) = dot_pos {
|
||||
path[pos + 1..].to_string()
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
(base, 0, ext)
|
||||
}
|
||||
|
||||
@@ -356,7 +368,10 @@ async fn test_thumbnail_path_parsing() {
|
||||
("image_300.jpg", ("image", 300, "jpg")),
|
||||
("photo_800.png", ("photo", 800, "png")),
|
||||
("document.pdf", ("document", 0, "pdf")),
|
||||
("file_with_underscore_but_no_width.gif", ("file_with_underscore_but_no_width", 0, "gif")),
|
||||
(
|
||||
"file_with_underscore_but_no_width.gif",
|
||||
("file_with_underscore_but_no_width", 0, "gif"),
|
||||
),
|
||||
("unsafe_1920x.jpg", ("unsafe_1920x", 0, "jpg")),
|
||||
("unsafe_1920x.png", ("unsafe_1920x", 0, "png")),
|
||||
("unsafe_1920x", ("unsafe_1920x", 0, "")),
|
||||
@@ -386,7 +401,7 @@ async fn test_image_format_detection() {
|
||||
"gif" => Ok(image::ImageFormat::Gif),
|
||||
"webp" => Ok(image::ImageFormat::WebP),
|
||||
"heic" | "heif" | "tiff" | "tif" => Ok(image::ImageFormat::Jpeg),
|
||||
_ => Err(())
|
||||
_ => Err(()),
|
||||
}
|
||||
}
|
||||
use image::ImageFormat;
|
||||
@@ -450,23 +465,23 @@ async fn test_find_closest_width() {
|
||||
}
|
||||
|
||||
let test_cases = vec![
|
||||
(100, 100), // Точное совпадение
|
||||
(150, 150), // Точное совпадение
|
||||
(200, 200), // Точное совпадение
|
||||
(300, 300), // Точное совпадение
|
||||
(400, 400), // Точное совпадение
|
||||
(500, 500), // Точное совпадение
|
||||
(600, 600), // Точное совпадение
|
||||
(800, 800), // Точное совпадение
|
||||
(120, 100), // Ближайшее к 100 (разница 20)
|
||||
(180, 200), // Ближайшее к 200 (разница 20)
|
||||
(250, 200), // Ближайшее к 200 (разница 50)
|
||||
(350, 300), // Ближайшее к 300 (разница 50)
|
||||
(450, 400), // Ближайшее к 400 (разница 50)
|
||||
(550, 500), // Ближайшее к 500 (разница 50)
|
||||
(700, 600), // Ближайшее к 600 (разница 100)
|
||||
(1000, 800), // Больше максимального - возвращаем максимальный
|
||||
(2000, 800), // Больше максимального - возвращаем максимальный
|
||||
(100, 100), // Точное совпадение
|
||||
(150, 150), // Точное совпадение
|
||||
(200, 200), // Точное совпадение
|
||||
(300, 300), // Точное совпадение
|
||||
(400, 400), // Точное совпадение
|
||||
(500, 500), // Точное совпадение
|
||||
(600, 600), // Точное совпадение
|
||||
(800, 800), // Точное совпадение
|
||||
(120, 100), // Ближайшее к 100 (разница 20)
|
||||
(180, 200), // Ближайшее к 200 (разница 20)
|
||||
(250, 200), // Ближайшее к 200 (разница 50)
|
||||
(350, 300), // Ближайшее к 300 (разница 50)
|
||||
(450, 400), // Ближайшее к 400 (разница 50)
|
||||
(550, 500), // Ближайшее к 500 (разница 50)
|
||||
(700, 600), // Ближайшее к 600 (разница 100)
|
||||
(1000, 800), // Больше максимального - возвращаем максимальный
|
||||
(2000, 800), // Больше максимального - возвращаем максимальный
|
||||
];
|
||||
|
||||
for (requested, expected) in test_cases {
|
||||
@@ -490,7 +505,7 @@ async fn test_lookup_functions() {
|
||||
"gif" => Some("image/gif"),
|
||||
"webp" => Some("image/webp"),
|
||||
"mp4" => Some("video/mp4"),
|
||||
_ => None
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -532,11 +547,17 @@ async fn test_s3_utils_functions() {
|
||||
Ok(vec!["file1.jpg".to_string(), "file2.png".to_string()])
|
||||
}
|
||||
|
||||
async fn check_file_exists(_bucket: &str, _key: &str) -> Result<bool, Box<dyn std::error::Error>> {
|
||||
async fn check_file_exists(
|
||||
_bucket: &str,
|
||||
_key: &str,
|
||||
) -> Result<bool, Box<dyn std::error::Error>> {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
async fn load_file_from_s3(_bucket: &str, _key: &str) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
|
||||
async fn load_file_from_s3(
|
||||
_bucket: &str,
|
||||
_key: &str,
|
||||
) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
|
||||
Ok(b"fake file content".to_vec())
|
||||
}
|
||||
|
||||
@@ -549,7 +570,10 @@ async fn test_s3_utils_functions() {
|
||||
#[test]
|
||||
async fn test_overlay_functions() {
|
||||
// Мокаем функцию generate_overlay для тестов
|
||||
async fn generate_overlay(shout_id: &str, image_data: actix_web::web::Bytes) -> Result<actix_web::web::Bytes, Box<dyn std::error::Error>> {
|
||||
async fn generate_overlay(
|
||||
shout_id: &str,
|
||||
image_data: actix_web::web::Bytes,
|
||||
) -> Result<actix_web::web::Bytes, Box<dyn std::error::Error>> {
|
||||
if image_data.is_empty() {
|
||||
return Err("Empty image data".into());
|
||||
}
|
||||
@@ -574,7 +598,10 @@ async fn test_overlay_functions() {
|
||||
let result = generate_overlay("invalid_id", test_bytes).await;
|
||||
|
||||
// Должен вернуть оригинальные данные при ошибке получения shout
|
||||
assert!(result.is_ok(), "Should return original data when shout fetch fails");
|
||||
assert!(
|
||||
result.is_ok(),
|
||||
"Should return original data when shout fetch fails"
|
||||
);
|
||||
}
|
||||
|
||||
/// Тест для проверки функций core.rs
|
||||
@@ -608,7 +635,10 @@ async fn test_auth_functions() {
|
||||
Ok(123)
|
||||
}
|
||||
|
||||
async fn user_added_file(_user_id: u32, _filename: &str) -> Result<(), Box<dyn std::error::Error>> {
|
||||
async fn user_added_file(
|
||||
_user_id: u32,
|
||||
_filename: &str,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -682,7 +712,11 @@ async fn test_integration() {
|
||||
|
||||
// Ищем последний underscore перед расширением
|
||||
let dot_pos = path.rfind('.');
|
||||
let name_part = if let Some(pos) = dot_pos { &path[..pos] } else { path };
|
||||
let name_part = if let Some(pos) = dot_pos {
|
||||
&path[..pos]
|
||||
} else {
|
||||
path
|
||||
};
|
||||
|
||||
// Ищем underscore для ширины
|
||||
if let Some(underscore_pos) = name_part.rfind('_') {
|
||||
@@ -690,14 +724,22 @@ async fn test_integration() {
|
||||
let width_part = &name_part[underscore_pos + 1..];
|
||||
|
||||
if let Ok(width) = width_part.parse::<u32>() {
|
||||
let ext = if let Some(pos) = dot_pos { path[pos + 1..].to_string() } else { "".to_string() };
|
||||
let ext = if let Some(pos) = dot_pos {
|
||||
path[pos + 1..].to_string()
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
return (base, width, ext);
|
||||
}
|
||||
}
|
||||
|
||||
// Если не нашли ширину, возвращаем как есть
|
||||
let base = name_part.to_string();
|
||||
let ext = if let Some(pos) = dot_pos { path[pos + 1..].to_string() } else { "".to_string() };
|
||||
let ext = if let Some(pos) = dot_pos {
|
||||
path[pos + 1..].to_string()
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
(base, 0, ext)
|
||||
}
|
||||
|
||||
@@ -707,7 +749,7 @@ async fn test_integration() {
|
||||
"png" => Some("image/png"),
|
||||
"gif" => Some("image/gif"),
|
||||
"webp" => Some("image/webp"),
|
||||
_ => None
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -736,7 +778,11 @@ async fn test_edge_cases() {
|
||||
|
||||
// Ищем последний underscore перед расширением
|
||||
let dot_pos = path.rfind('.');
|
||||
let name_part = if let Some(pos) = dot_pos { &path[..pos] } else { path };
|
||||
let name_part = if let Some(pos) = dot_pos {
|
||||
&path[..pos]
|
||||
} else {
|
||||
path
|
||||
};
|
||||
|
||||
// Ищем underscore для ширины
|
||||
if let Some(underscore_pos) = name_part.rfind('_') {
|
||||
@@ -744,14 +790,22 @@ async fn test_edge_cases() {
|
||||
let width_part = &name_part[underscore_pos + 1..];
|
||||
|
||||
if let Ok(width) = width_part.parse::<u32>() {
|
||||
let ext = if let Some(pos) = dot_pos { path[pos + 1..].to_string() } else { "".to_string() };
|
||||
let ext = if let Some(pos) = dot_pos {
|
||||
path[pos + 1..].to_string()
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
return (base, width, ext);
|
||||
}
|
||||
}
|
||||
|
||||
// Если не нашли ширину, возвращаем как есть
|
||||
let base = name_part.to_string();
|
||||
let ext = if let Some(pos) = dot_pos { path[pos + 1..].to_string() } else { "".to_string() };
|
||||
let ext = if let Some(pos) = dot_pos {
|
||||
path[pos + 1..].to_string()
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
(base, 0, ext)
|
||||
}
|
||||
|
||||
@@ -788,7 +842,11 @@ async fn test_parsing_performance() {
|
||||
|
||||
// Ищем последний underscore перед расширением
|
||||
let dot_pos = path.rfind('.');
|
||||
let name_part = if let Some(pos) = dot_pos { &path[..pos] } else { path };
|
||||
let name_part = if let Some(pos) = dot_pos {
|
||||
&path[..pos]
|
||||
} else {
|
||||
path
|
||||
};
|
||||
|
||||
// Ищем underscore для ширины
|
||||
if let Some(underscore_pos) = name_part.rfind('_') {
|
||||
@@ -796,14 +854,22 @@ async fn test_parsing_performance() {
|
||||
let width_part = &name_part[underscore_pos + 1..];
|
||||
|
||||
if let Ok(width) = width_part.parse::<u32>() {
|
||||
let ext = if let Some(pos) = dot_pos { path[pos + 1..].to_string() } else { "".to_string() };
|
||||
let ext = if let Some(pos) = dot_pos {
|
||||
path[pos + 1..].to_string()
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
return (base, width, ext);
|
||||
}
|
||||
}
|
||||
|
||||
// Если не нашли ширину, возвращаем как есть
|
||||
let base = name_part.to_string();
|
||||
let ext = if let Some(pos) = dot_pos { path[pos + 1..].to_string() } else { "".to_string() };
|
||||
let ext = if let Some(pos) = dot_pos {
|
||||
path[pos + 1..].to_string()
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
(base, 0, ext)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
use actix_web::{test, web, App, HttpRequest, HttpResponse, Error as ActixError};
|
||||
use actix_web::http::StatusCode;
|
||||
use actix_web::{App, Error as ActixError, HttpRequest, HttpResponse, test, web};
|
||||
use serde_json::json;
|
||||
|
||||
|
||||
// Мокаем необходимые структуры и функции для тестов
|
||||
|
||||
/// Мок для Redis соединения
|
||||
@@ -36,7 +35,11 @@ impl MockAppState {
|
||||
Ok(1024 * 1024) // 1MB
|
||||
}
|
||||
|
||||
async fn increase_user_quota(&self, _user_id: &str, _additional_bytes: u64) -> Result<u64, actix_web::Error> {
|
||||
async fn increase_user_quota(
|
||||
&self,
|
||||
_user_id: &str,
|
||||
_additional_bytes: u64,
|
||||
) -> Result<u64, actix_web::Error> {
|
||||
Ok(2 * 1024 * 1024) // 2MB
|
||||
}
|
||||
|
||||
@@ -68,8 +71,9 @@ async fn test_get_quota_handler() {
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.app_data(web::Data::new(MockAppState::new()))
|
||||
.route("/quota", web::get().to(get_quota_handler))
|
||||
).await;
|
||||
.route("/quota", web::get().to(get_quota_handler)),
|
||||
)
|
||||
.await;
|
||||
|
||||
// Тест без авторизации
|
||||
let req = test::TestRequest::get()
|
||||
@@ -102,8 +106,9 @@ async fn test_increase_quota_handler() {
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.app_data(web::Data::new(MockAppState::new()))
|
||||
.route("/quota/increase", web::post().to(increase_quota_handler))
|
||||
).await;
|
||||
.route("/quota/increase", web::post().to(increase_quota_handler)),
|
||||
)
|
||||
.await;
|
||||
|
||||
// Тест без авторизации
|
||||
let req = test::TestRequest::post()
|
||||
@@ -136,13 +141,12 @@ async fn test_set_quota_handler() {
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.app_data(web::Data::new(MockAppState::new()))
|
||||
.route("/quota/set", web::post().to(set_quota_handler))
|
||||
).await;
|
||||
.route("/quota/set", web::post().to(set_quota_handler)),
|
||||
)
|
||||
.await;
|
||||
|
||||
// Тест без авторизации
|
||||
let req = test::TestRequest::post()
|
||||
.uri("/quota/set")
|
||||
.to_request();
|
||||
let req = test::TestRequest::post().uri("/quota/set").to_request();
|
||||
|
||||
let resp = test::call_service(&app, req).await;
|
||||
// Мок возвращает успешный ответ даже без авторизации
|
||||
@@ -170,13 +174,12 @@ async fn test_upload_handler() {
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.app_data(web::Data::new(MockAppState::new()))
|
||||
.route("/", web::post().to(upload_handler))
|
||||
).await;
|
||||
.route("/", web::post().to(upload_handler)),
|
||||
)
|
||||
.await;
|
||||
|
||||
// Тест без авторизации
|
||||
let req = test::TestRequest::post()
|
||||
.uri("/")
|
||||
.to_request();
|
||||
let req = test::TestRequest::post().uri("/").to_request();
|
||||
|
||||
let resp = test::call_service(&app, req).await;
|
||||
// Мок возвращает успешный ответ даже без авторизации
|
||||
@@ -204,8 +207,9 @@ async fn test_proxy_handler() {
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.app_data(web::Data::new(MockAppState::new()))
|
||||
.route("/{path:.*}", web::get().to(proxy_handler))
|
||||
).await;
|
||||
.route("/{path:.*}", web::get().to(proxy_handler)),
|
||||
)
|
||||
.await;
|
||||
|
||||
// Тест с несуществующим файлом
|
||||
let req = test::TestRequest::get()
|
||||
@@ -221,7 +225,11 @@ async fn test_proxy_handler() {
|
||||
#[actix_web::test]
|
||||
async fn test_serve_file() {
|
||||
// Мокаем функцию serve_file
|
||||
async fn serve_file(_path: &str, _app_state: &MockAppState, _user_id: &str) -> Result<actix_web::HttpResponse, actix_web::Error> {
|
||||
async fn serve_file(
|
||||
_path: &str,
|
||||
_app_state: &MockAppState,
|
||||
_user_id: &str,
|
||||
) -> Result<actix_web::HttpResponse, actix_web::Error> {
|
||||
Err(actix_web::error::ErrorNotFound("File not found"))
|
||||
}
|
||||
|
||||
@@ -243,12 +251,16 @@ async fn test_handler_error_handling() {
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.app_data(web::Data::new(MockAppState::new()))
|
||||
.route("/test", web::get().to(|_req: HttpRequest| async {
|
||||
Err::<HttpResponse, ActixError>(
|
||||
actix_web::error::ErrorInternalServerError("Test error")
|
||||
)
|
||||
}))
|
||||
).await;
|
||||
.route(
|
||||
"/test",
|
||||
web::get().to(|_req: HttpRequest| async {
|
||||
Err::<HttpResponse, ActixError>(actix_web::error::ErrorInternalServerError(
|
||||
"Test error",
|
||||
))
|
||||
}),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
|
||||
let req = test::TestRequest::get().uri("/test").to_request();
|
||||
let resp = test::call_service(&app, req).await;
|
||||
@@ -261,13 +273,15 @@ async fn test_cors_headers() {
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.app_data(web::Data::new(MockAppState::new()))
|
||||
.route("/test", web::get().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok().body("test")
|
||||
)
|
||||
}))
|
||||
.wrap(actix_cors::Cors::default().allow_any_origin())
|
||||
).await;
|
||||
.route(
|
||||
"/test",
|
||||
web::get().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(HttpResponse::Ok().body("test"))
|
||||
}),
|
||||
)
|
||||
.wrap(actix_cors::Cors::default().allow_any_origin()),
|
||||
)
|
||||
.await;
|
||||
|
||||
let req = test::TestRequest::get().uri("/test").to_request();
|
||||
let resp = test::call_service(&app, req).await;
|
||||
@@ -286,17 +300,20 @@ async fn test_cors_headers() {
|
||||
async fn test_http_methods() {
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.route("/test", web::get().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok().body("GET method")
|
||||
)
|
||||
}))
|
||||
.route("/test", web::post().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok().body("POST method")
|
||||
)
|
||||
}))
|
||||
).await;
|
||||
.route(
|
||||
"/test",
|
||||
web::get().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(HttpResponse::Ok().body("GET method"))
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/test",
|
||||
web::post().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(HttpResponse::Ok().body("POST method"))
|
||||
}),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
|
||||
// Тест GET метода
|
||||
let req = test::TestRequest::get().uri("/test").to_request();
|
||||
@@ -318,15 +335,14 @@ async fn test_http_methods() {
|
||||
/// Тест для проверки query параметров
|
||||
#[actix_web::test]
|
||||
async fn test_query_parameters() {
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.route("/test", web::get().to(|req: HttpRequest| async move {
|
||||
let query_string = req.query_string().to_string();
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok().body(query_string)
|
||||
)
|
||||
}))
|
||||
).await;
|
||||
let app = test::init_service(App::new().route(
|
||||
"/test",
|
||||
web::get().to(|req: HttpRequest| async move {
|
||||
let query_string = req.query_string().to_string();
|
||||
Ok::<HttpResponse, ActixError>(HttpResponse::Ok().body(query_string))
|
||||
}),
|
||||
))
|
||||
.await;
|
||||
|
||||
let req = test::TestRequest::get()
|
||||
.uri("/test?param1=value1¶m2=value2")
|
||||
@@ -342,20 +358,20 @@ async fn test_query_parameters() {
|
||||
/// Тест для проверки headers
|
||||
#[actix_web::test]
|
||||
async fn test_headers() {
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.route("/test", web::get().to(|req: HttpRequest| async move {
|
||||
let user_agent = req.headers()
|
||||
.get("user-agent")
|
||||
.and_then(|h| h.to_str().ok())
|
||||
.unwrap_or("unknown")
|
||||
.to_string();
|
||||
let app = test::init_service(App::new().route(
|
||||
"/test",
|
||||
web::get().to(|req: HttpRequest| async move {
|
||||
let user_agent = req
|
||||
.headers()
|
||||
.get("user-agent")
|
||||
.and_then(|h| h.to_str().ok())
|
||||
.unwrap_or("unknown")
|
||||
.to_string();
|
||||
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok().body(user_agent)
|
||||
)
|
||||
}))
|
||||
).await;
|
||||
Ok::<HttpResponse, ActixError>(HttpResponse::Ok().body(user_agent))
|
||||
}),
|
||||
))
|
||||
.await;
|
||||
|
||||
let req = test::TestRequest::get()
|
||||
.uri("/test")
|
||||
@@ -372,23 +388,22 @@ async fn test_headers() {
|
||||
/// Тест для проверки JSON responses
|
||||
#[actix_web::test]
|
||||
async fn test_json_responses() {
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.route("/test", web::get().to(|_req: HttpRequest| async {
|
||||
let data = json!({
|
||||
"status": "success",
|
||||
"message": "test message",
|
||||
"data": {
|
||||
"id": 123,
|
||||
"name": "test"
|
||||
}
|
||||
});
|
||||
let app = test::init_service(App::new().route(
|
||||
"/test",
|
||||
web::get().to(|_req: HttpRequest| async {
|
||||
let data = json!({
|
||||
"status": "success",
|
||||
"message": "test message",
|
||||
"data": {
|
||||
"id": 123,
|
||||
"name": "test"
|
||||
}
|
||||
});
|
||||
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok().json(data)
|
||||
)
|
||||
}))
|
||||
).await;
|
||||
Ok::<HttpResponse, ActixError>(HttpResponse::Ok().json(data))
|
||||
}),
|
||||
))
|
||||
.await;
|
||||
|
||||
let req = test::TestRequest::get().uri("/test").to_request();
|
||||
let resp = test::call_service(&app, req).await;
|
||||
@@ -408,28 +423,38 @@ async fn test_json_responses() {
|
||||
async fn test_content_types() {
|
||||
let app = test::init_service(
|
||||
App::new()
|
||||
.route("/text", web::get().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok()
|
||||
.content_type("text/plain")
|
||||
.body("plain text")
|
||||
)
|
||||
}))
|
||||
.route("/html", web::get().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok()
|
||||
.content_type("text/html")
|
||||
.body("<html><body>test</body></html>")
|
||||
)
|
||||
}))
|
||||
.route("/json", web::get().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok()
|
||||
.content_type("application/json")
|
||||
.json(json!({"test": "data"}))
|
||||
)
|
||||
}))
|
||||
).await;
|
||||
.route(
|
||||
"/text",
|
||||
web::get().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok()
|
||||
.content_type("text/plain")
|
||||
.body("plain text"),
|
||||
)
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/html",
|
||||
web::get().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok()
|
||||
.content_type("text/html")
|
||||
.body("<html><body>test</body></html>"),
|
||||
)
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/json",
|
||||
web::get().to(|_req: HttpRequest| async {
|
||||
Ok::<HttpResponse, ActixError>(
|
||||
HttpResponse::Ok()
|
||||
.content_type("application/json")
|
||||
.json(json!({"test": "data"})),
|
||||
)
|
||||
}),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
|
||||
// Тест text/plain
|
||||
let req = test::TestRequest::get().uri("/text").to_request();
|
||||
@@ -444,5 +469,8 @@ async fn test_content_types() {
|
||||
// Тест application/json
|
||||
let req = test::TestRequest::get().uri("/json").to_request();
|
||||
let resp = test::call_service(&app, req).await;
|
||||
assert_eq!(resp.headers().get("content-type").unwrap(), "application/json");
|
||||
assert_eq!(
|
||||
resp.headers().get("content-type").unwrap(),
|
||||
"application/json"
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user