Files
docupulse/tasks.py
2025-06-19 16:11:42 +02:00

78 lines
2.7 KiB
Python

from datetime import datetime, timedelta
from models import db, RoomFile, PasswordResetToken, PasswordSetupToken
import os
def cleanup_trash():
"""
Permanently deletes files that have been in trash for more than 30 days.
This function should be called by a scheduler (e.g., cron job) daily.
"""
# Calculate the cutoff date (30 days ago)
cutoff_date = datetime.utcnow() - timedelta(days=30)
# Find all files that were deleted before the cutoff date
files_to_delete = RoomFile.query.filter(
RoomFile.deleted == True,
RoomFile.deleted_at <= cutoff_date
).all()
for file in files_to_delete:
try:
# Delete the file from storage if it's a file
if file.type == 'file':
file_path = os.path.join('/app/uploads/rooms', str(file.room_id), file.path, file.name)
if os.path.exists(file_path):
os.remove(file_path)
# Delete the database record
db.session.delete(file)
except Exception as e:
print(f"Error deleting file {file.name}: {str(e)}")
continue
# Commit all changes
try:
db.session.commit()
except Exception as e:
print(f"Error committing changes: {str(e)}")
db.session.rollback()
def cleanup_expired_tokens():
"""
Removes expired password reset and setup tokens from the database.
This function should be called by a scheduler (e.g., cron job) daily.
"""
current_time = datetime.utcnow()
# Clean up expired password reset tokens
expired_reset_tokens = PasswordResetToken.query.filter(
PasswordResetToken.expires_at < current_time
).all()
for token in expired_reset_tokens:
try:
db.session.delete(token)
except Exception as e:
print(f"Error deleting expired password reset token {token.id}: {str(e)}")
continue
# Clean up expired password setup tokens
expired_setup_tokens = PasswordSetupToken.query.filter(
PasswordSetupToken.expires_at < current_time
).all()
for token in expired_setup_tokens:
try:
db.session.delete(token)
except Exception as e:
print(f"Error deleting expired password setup token {token.id}: {str(e)}")
continue
# Commit all changes
try:
db.session.commit()
print(f"Cleaned up {len(expired_reset_tokens)} expired password reset tokens and {len(expired_setup_tokens)} expired password setup tokens")
except Exception as e:
print(f"Error committing token cleanup changes: {str(e)}")
db.session.rollback()