64 lines
1.8 KiB
Python
64 lines
1.8 KiB
Python
"""
|
||
Celery задачи для модуля communications
|
||
"""
|
||
|
||
from celery import shared_task
|
||
from django.utils import timezone
|
||
from datetime import timedelta
|
||
import logging
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
|
||
@shared_task
|
||
def cleanup_orphaned_attachments():
|
||
"""
|
||
Очистка временных вложений без привязки к сообщению.
|
||
Удаляет MessageAttachment с message=null старше 1 часа.
|
||
"""
|
||
from communications.models import MessageAttachment
|
||
|
||
cutoff_time = timezone.now() - timedelta(hours=1)
|
||
|
||
orphaned = MessageAttachment.objects.filter(
|
||
message__isnull=True, uploaded_at__lt=cutoff_time
|
||
)
|
||
|
||
count = orphaned.count()
|
||
|
||
if count > 0:
|
||
logger.info(
|
||
"Orphaned chat attachments found",
|
||
extra={
|
||
"event": "chat.attachment_cleanup.started",
|
||
"attachment_count": count,
|
||
"cutoff_at": cutoff_time,
|
||
},
|
||
)
|
||
|
||
# Удаляем файлы и записи
|
||
for attachment in orphaned:
|
||
try:
|
||
if attachment.file:
|
||
attachment.file.delete()
|
||
attachment.delete()
|
||
except Exception as e:
|
||
logger.exception(
|
||
"Orphaned chat attachment deletion failed",
|
||
extra={
|
||
"event": "chat.attachment_cleanup.item_failed",
|
||
"attachment_id": attachment.id,
|
||
"error_type": type(e).__name__,
|
||
},
|
||
)
|
||
|
||
logger.info(
|
||
"Orphaned chat attachment cleanup completed",
|
||
extra={
|
||
"event": "chat.attachment_cleanup.completed",
|
||
"attachment_count": count,
|
||
},
|
||
)
|
||
|
||
return count
|