Files
eventspace/backend/app/utils/files.py
Felipe Cardoso 9fdf8971e3 Add function to relocate theme files in storage
Introduce `_relocate_theme_file` to handle moving files to theme-specific directories in the storage system. This ensures better organization of uploaded files by associating them with a theme ID and file type, improving maintainability and structure.
2025-03-12 21:16:42 +01:00

71 lines
2.3 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
current_file = current_url.split('/files/')[1] if '/files/' in current_url else current_url
filename = os.path.basename(current_file)
# Define source and destination paths
source_path = os.path.join(storage.upload_folder, current_file)
theme_folder = os.path.join(storage.upload_folder, f'event-themes/{theme_id}/{file_type}')
# Create the destination folder if it doesn't exist
os.makedirs(theme_folder, exist_ok=True)
# Define destination path
dest_path = os.path.join(theme_folder, filename)
# Move the file
if os.path.exists(source_path):
shutil.move(source_path, dest_path)
# Return the new URL
relative_path = os.path.relpath(dest_path, storage.upload_folder)
return f"/files/{relative_path}"
return None
except Exception as e:
print(f"Error relocating file: {str(e)}")
return None