delete.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from rest_framework.response import Response
  2. from django.core.exceptions import PermissionDenied
  3. from django.db import transaction
  4. from django.http import Http404
  5. from django.utils.six import text_type
  6. from django.utils.translation import ugettext as _
  7. from django.utils.translation import ungettext
  8. from misago.conf import settings
  9. from misago.threads.moderation import threads as moderation
  10. DELETE_LIMIT = settings.MISAGO_THREADS_PER_PAGE + settings.MISAGO_THREADS_TAIL
  11. @transaction.atomic
  12. def delete_thread(request, thread):
  13. allow_delete_thread(request.user, thread)
  14. moderation.delete_thread(request.user, thread)
  15. return Response({})
  16. def delete_bulk(request, viewmodel):
  17. threads_ids = clean_threads_ids(request)
  18. errors = []
  19. for thread_id in threads_ids:
  20. try:
  21. thread = viewmodel(request, thread_id).unwrap()
  22. delete_thread(request, thread)
  23. except PermissionDenied as e:
  24. errors.append({
  25. 'thread': {
  26. 'id': thread.id,
  27. 'title': thread.title
  28. },
  29. 'error': text_type(e)
  30. })
  31. except Http404:
  32. pass # skip invisible threads
  33. return Response(errors)
  34. def clean_threads_ids(request):
  35. try:
  36. threads_ids = list(map(int, request.data or []))
  37. except (ValueError, TypeError):
  38. raise PermissionDenied(_("One or more thread ids received were invalid."))
  39. if not threads_ids:
  40. raise PermissionDenied(_("You have to specify at least one thread to delete."))
  41. elif len(threads_ids) > DELETE_LIMIT:
  42. message = ungettext(
  43. "No more than %(limit)s thread can be deleted at single time.",
  44. "No more than %(limit)s threads can be deleted at single time.",
  45. DELETE_LIMIT,
  46. )
  47. raise PermissionDenied(message % {'limit': DELETE_LIMIT})
  48. return set(threads_ids)
  49. def allow_delete_thread(user, thread):
  50. if thread.acl.get('can_hide') != 2:
  51. raise PermissionDenied(_("You don't have permission to delete this thread."))