split.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. from rest_framework.response import Response
  2. from django.core.exceptions import PermissionDenied
  3. from django.utils.translation import gettext as _
  4. from misago.threads.models import Thread
  5. from misago.threads.moderation import threads as moderation
  6. from misago.threads.serializers import SplitPostsSerializer
  7. def posts_split_endpoint(request, thread):
  8. if not thread.acl['can_move_posts']:
  9. raise PermissionDenied(_("You can't split posts from this thread."))
  10. serializer = SplitPostsSerializer(
  11. data=request.data,
  12. context={
  13. 'settings': request.settings,
  14. 'thread': thread,
  15. 'user_acl': request.user_acl,
  16. },
  17. )
  18. if not serializer.is_valid():
  19. if 'posts' in serializer.errors:
  20. errors = {
  21. 'detail': serializer.errors['posts'][0]
  22. }
  23. else :
  24. errors = serializer.errors
  25. return Response(errors, status=400)
  26. split_posts_to_new_thread(request, thread, serializer.validated_data)
  27. return Response({})
  28. def split_posts_to_new_thread(request, thread, validated_data):
  29. new_thread = Thread(
  30. category=validated_data['category'],
  31. started_on=thread.started_on,
  32. last_post_on=thread.last_post_on,
  33. )
  34. new_thread.set_title(validated_data['title'])
  35. new_thread.save()
  36. for post in validated_data['posts']:
  37. post.move(new_thread)
  38. post.save()
  39. thread.synchronize()
  40. thread.save()
  41. new_thread.synchronize()
  42. new_thread.save()
  43. if validated_data.get('weight') == Thread.WEIGHT_GLOBAL:
  44. moderation.pin_thread_globally(request, new_thread)
  45. elif validated_data.get('weight'):
  46. moderation.pin_thread_locally(request, new_thread)
  47. if validated_data.get('is_hidden', False):
  48. moderation.hide_thread(request, new_thread)
  49. if validated_data.get('is_closed', False):
  50. moderation.close_thread(request, new_thread)
  51. thread.category.synchronize()
  52. thread.category.save()
  53. if new_thread.category != thread.category:
  54. new_thread.category.synchronize()
  55. new_thread.category.save()