delete.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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.permissions import allow_delete_thread
  10. from misago.threads.moderation import threads as moderation
  11. DELETE_LIMIT = settings.MISAGO_THREADS_PER_PAGE + settings.MISAGO_THREADS_TAIL
  12. @transaction.atomic
  13. def delete_thread(request, thread):
  14. allow_delete_thread(request.user, thread)
  15. moderation.delete_thread(request.user, thread)
  16. return Response({})
  17. def delete_bulk(request, viewmodel):
  18. threads_ids = clean_threads_ids(request)
  19. errors = []
  20. for thread_id in threads_ids:
  21. try:
  22. thread = viewmodel(request, thread_id).unwrap()
  23. delete_thread(request, thread)
  24. except PermissionDenied as e:
  25. errors.append({
  26. 'thread': {
  27. 'id': thread.id,
  28. 'title': thread.title
  29. },
  30. 'error': text_type(e)
  31. })
  32. except Http404:
  33. pass # skip invisible threads
  34. if errors:
  35. return Response(errors, status=400)
  36. return Response([])
  37. def clean_threads_ids(request):
  38. try:
  39. threads_ids = list(map(int, request.data or []))
  40. except (ValueError, TypeError):
  41. raise PermissionDenied(_("One or more thread ids received were invalid."))
  42. if not threads_ids:
  43. raise PermissionDenied(_("You have to specify at least one thread to delete."))
  44. elif len(threads_ids) > DELETE_LIMIT:
  45. message = ungettext(
  46. "No more than %(limit)s thread can be deleted at single time.",
  47. "No more than %(limit)s threads can be deleted at single time.",
  48. DELETE_LIMIT,
  49. )
  50. raise PermissionDenied(message % {'limit': DELETE_LIMIT})
  51. return set(threads_ids)