Files
eventspace/backend/app/utils/files.py
Felipe Cardoso d2e71feb69
All checks were successful
Build and Push Docker Images / changes (push) Successful in 4s
Build and Push Docker Images / build-backend (push) Successful in 49s
Build and Push Docker Images / build-frontend (push) Has been skipped
Refactor file relocation logic for theme-specific files.
Updated the file relocation function to use `settings.DATA_FILES_DIR` for theme folders and improved filename handling by prefixing with the file type. Adjusted logic to handle URLs consistently and ensure paths are properly resolved. This enhances maintainability and organizes theme files more effectively.
2025-03-14 02:22:21 +01:00

81 lines
2.5 KiB
Python

import os
import shutil
import uuid
from datetime import datetime
from app.core.config import settings
from app.core.storage import StorageProvider
def generate_unique_filename(original_filename: str) -> str:
"""Generate a unique filename preserving the original extension."""
name, ext = os.path.splitext(original_filename)
unique_id = uuid.uuid4().hex
return f"{unique_id}{ext}"
def get_relative_storage_path(folder: str, filename: str) -> str:
"""
Generate a relative storage path using date-based organization.
Example: "event-themes/2023/03/filename.jpg"
"""
today = datetime.now()
year_month = today.strftime("%Y/%m")
return os.path.join(folder, year_month, filename)
def validate_image_content_type(content_type: str) -> bool:
"""Check if the content type is an allowed image type."""
return content_type in settings.ALLOWED_IMAGE_TYPES
def _relocate_theme_file(theme_id: uuid.UUID, current_url: str, file_type: str, storage: StorageProvider) -> str:
"""
Move an uploaded file to a theme-specific folder.
Args:
theme_id: The theme ID
current_url: The current file URL
file_type: Type of file (preview, background, etc.)
storage: The storage provider
Returns:
The new URL if successful, otherwise None
"""
try:
# Extract the filename from the URL
if 'uploads/' in current_url:
# Extract the part after 'uploads/'
current_file = current_url.split('uploads/')[1]
else:
current_file = current_url
filename = os.path.basename(current_file)
# Define source and destination paths
source_path = os.path.join(storage.upload_folder, current_file)
# Use settings.DATA_FILES_DIR for theme files
theme_folder = os.path.join(settings.DATA_FILES_DIR, f'event-themes/{theme_id}')
# Create the destination folder if it doesn't exist
os.makedirs(theme_folder, exist_ok=True)
# Define destination path
prefixed_filename = f"{file_type}_{filename}"
dest_path = os.path.join(theme_folder, prefixed_filename)
# Move the file
if os.path.exists(source_path):
shutil.move(source_path, dest_path)
# Return the new URL - relative to the upload folder
relative_path = os.path.relpath(dest_path, settings.DATA_FILES_DIR)
return relative_path
return None
except Exception as e:
print(f"Error relocating file: {str(e)}")
return None