103 lines
3.6 KiB
Python
103 lines
3.6 KiB
Python
"""
|
||
Утилиты для работы с файлами чата.
|
||
"""
|
||
import os
|
||
import shutil
|
||
from django.conf import settings
|
||
from django.core.files.storage import default_storage
|
||
from django.core.files.base import ContentFile
|
||
|
||
|
||
def get_preload_chat_directory(chat_id: int) -> str:
|
||
"""Получить путь к директории предзагрузки для чата."""
|
||
return os.path.join('preload_file_chat', str(chat_id))
|
||
|
||
|
||
def get_chat_file_directory(chat_id: int) -> str:
|
||
"""Получить путь к директории файлов чата."""
|
||
return os.path.join('file_chat', str(chat_id))
|
||
|
||
|
||
def save_file_to_preload(chat_id: int, file, filename: str) -> str:
|
||
"""
|
||
Сохранить файл в директорию предзагрузки.
|
||
|
||
Args:
|
||
chat_id: ID чата
|
||
file: Файл для сохранения
|
||
filename: Имя файла
|
||
|
||
Returns:
|
||
Путь к сохраненному файлу относительно MEDIA_ROOT
|
||
"""
|
||
preload_dir = get_preload_chat_directory(chat_id)
|
||
|
||
# Создаем директорию если не существует
|
||
full_path = os.path.join(settings.MEDIA_ROOT, preload_dir)
|
||
os.makedirs(full_path, exist_ok=True)
|
||
|
||
# Сохраняем файл
|
||
file_path = os.path.join(preload_dir, filename)
|
||
path = default_storage.save(file_path, ContentFile(file.read()))
|
||
|
||
return path
|
||
|
||
|
||
def move_file_from_preload_to_chat(chat_id: int, filename: str) -> str:
|
||
"""
|
||
Переместить файл из preload в основную директорию чата.
|
||
|
||
Args:
|
||
chat_id: ID чата
|
||
filename: Имя файла
|
||
|
||
Returns:
|
||
Новый путь к файлу относительно MEDIA_ROOT
|
||
"""
|
||
preload_dir = get_preload_chat_directory(chat_id)
|
||
chat_dir = get_chat_file_directory(chat_id)
|
||
|
||
old_path = os.path.join(settings.MEDIA_ROOT, preload_dir, filename)
|
||
new_dir = os.path.join(settings.MEDIA_ROOT, chat_dir)
|
||
new_path = os.path.join(new_dir, filename)
|
||
|
||
# Создаем директорию если не существует
|
||
os.makedirs(new_dir, exist_ok=True)
|
||
|
||
# Перемещаем файл
|
||
if os.path.exists(old_path):
|
||
shutil.move(old_path, new_path)
|
||
# Возвращаем путь относительно MEDIA_ROOT
|
||
return os.path.join(chat_dir, filename)
|
||
|
||
raise FileNotFoundError(f"Файл {old_path} не найден")
|
||
|
||
|
||
def cleanup_preload_files(chat_id: int, filenames: list = None):
|
||
"""
|
||
Очистить файлы из директории предзагрузки.
|
||
|
||
Args:
|
||
chat_id: ID чата
|
||
filenames: Список имен файлов для удаления (если None - удалить все)
|
||
"""
|
||
preload_dir = get_preload_chat_directory(chat_id)
|
||
full_path = os.path.join(settings.MEDIA_ROOT, preload_dir)
|
||
|
||
if not os.path.exists(full_path):
|
||
return
|
||
|
||
if filenames:
|
||
# Удаляем только указанные файлы
|
||
for filename in filenames:
|
||
file_path = os.path.join(full_path, filename)
|
||
if os.path.exists(file_path):
|
||
os.remove(file_path)
|
||
else:
|
||
# Удаляем все файлы в директории
|
||
for filename in os.listdir(full_path):
|
||
file_path = os.path.join(full_path, filename)
|
||
if os.path.isfile(file_path):
|
||
os.remove(file_path)
|
||
|