prunecategories.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. from datetime import timedelta
  2. from django.core.management.base import BaseCommand
  3. from django.utils import timezone
  4. from misago.categories.models import Category
  5. class Command(BaseCommand):
  6. """
  7. This command is intended to work as CRON job fired
  8. every few days (or more often) to execute categories pruning policies
  9. """
  10. help = 'Prunes categories'
  11. def handle(self, *args, **options):
  12. now = timezone.now()
  13. synchronize_categories = []
  14. for category in Category.objects.iterator():
  15. archive = category.archive_pruned_in
  16. pruned_threads = 0
  17. threads_qs = category.thread_set.filter(is_pinned=False)
  18. if category.prune_started_after:
  19. cutoff = now - timedelta(days=category.prune_started_after)
  20. prune_qs = threads_qs.filter(started_on__lte=cutoff)
  21. for thread in prune_qs.iterator():
  22. if archive:
  23. thread.move(archive)
  24. thread.save()
  25. else:
  26. thread.delete()
  27. pruned_threads += 1
  28. if category.prune_replied_after:
  29. cutoff = now - timedelta(days=category.prune_replied_after)
  30. prune_qs = threads_qs.filter(last_post_on__lte=cutoff)
  31. for thread in prune_qs.iterator():
  32. if archive:
  33. thread.move(archive)
  34. thread.save()
  35. else:
  36. thread.delete()
  37. pruned_threads += 1
  38. if pruned_threads:
  39. if category not in synchronize_categories:
  40. synchronize_categories.append(category)
  41. if archive and archive not in synchronize_categories:
  42. synchronize_categories.append(archive)
  43. for category in synchronize_categories:
  44. category.synchronize()
  45. category.save()
  46. self.stdout.write('\n\nCategories were pruned')