split.py 2.3 KB

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