50 lines
1.6 KiB
Python
50 lines
1.6 KiB
Python
"""Background tasks for sweeping trash and old versions."""
|
|
|
|
from datetime import UTC, datetime, timedelta
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.config import settings
|
|
from app.models.annotation_state import AnnotationState
|
|
from app.models.document import Document
|
|
from app.models.version import Version
|
|
from app.services.assets import delete_asset_directory
|
|
from app.services.storage import delete_pdf_file
|
|
from app.services.thumbnails import delete_thumbnail
|
|
|
|
|
|
def sweep_trash(db: Session) -> None:
|
|
"""Permanently delete documents that have been in the trash past the retention period."""
|
|
cutoff = datetime.now(UTC) - timedelta(days=settings.TRASH_RETENTION_DAYS)
|
|
cutoff_iso = cutoff.isoformat()
|
|
|
|
docs_to_delete = (
|
|
db.query(Document)
|
|
.filter(Document.deleted_at.is_not(None), Document.deleted_at <= cutoff_iso)
|
|
.all()
|
|
)
|
|
|
|
for doc in docs_to_delete:
|
|
# Delete files from disk
|
|
delete_pdf_file(doc.id)
|
|
delete_thumbnail(doc.id)
|
|
delete_asset_directory(doc.id)
|
|
|
|
# Delete DB associations
|
|
db.query(AnnotationState).filter(AnnotationState.document_id == doc.id).delete()
|
|
db.query(Version).filter(Version.document_id == doc.id).delete()
|
|
|
|
# Delete document record
|
|
db.delete(doc)
|
|
|
|
db.commit()
|
|
|
|
|
|
def prune_auto_versions(db: Session) -> None:
|
|
"""Delete automatic versions older than the retention period."""
|
|
cutoff = datetime.now(UTC) - timedelta(days=settings.AUTO_VERSION_RETENTION_DAYS)
|
|
cutoff_iso = cutoff.isoformat()
|
|
|
|
db.query(Version).filter(Version.kind == "auto", Version.created_at <= cutoff_iso).delete()
|
|
|
|
db.commit()
|