split.py 2.0 KB

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