split.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. from django.core.exceptions import PermissionDenied
  2. from django.utils.translation import gettext as _
  3. from rest_framework.response import Response
  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 = {"detail": serializer.errors["posts"][0]}
  21. else:
  22. errors = serializer.errors
  23. return Response(errors, status=400)
  24. split_posts_to_new_thread(request, thread, serializer.validated_data)
  25. return Response({})
  26. def split_posts_to_new_thread(request, thread, validated_data):
  27. new_thread = Thread(
  28. category=validated_data["category"],
  29. started_on=thread.started_on,
  30. last_post_on=thread.last_post_on,
  31. )
  32. new_thread.set_title(validated_data["title"])
  33. new_thread.save()
  34. for post in validated_data["posts"]:
  35. post.move(new_thread)
  36. post.save()
  37. thread.synchronize()
  38. thread.save()
  39. new_thread.synchronize()
  40. new_thread.save()
  41. if validated_data.get("weight") == Thread.WEIGHT_GLOBAL:
  42. moderation.pin_thread_globally(request, new_thread)
  43. elif validated_data.get("weight"):
  44. moderation.pin_thread_locally(request, new_thread)
  45. if validated_data.get("is_hidden", False):
  46. moderation.hide_thread(request, new_thread)
  47. if validated_data.get("is_closed", False):
  48. moderation.close_thread(request, new_thread)
  49. thread.category.synchronize()
  50. thread.category.save()
  51. if new_thread.category != thread.category:
  52. new_thread.category.synchronize()
  53. new_thread.category.save()