merge.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. from django.core.exceptions import PermissionDenied, ValidationError
  2. from django.http import Http404
  3. from django.utils.translation import gettext as _, ungettext
  4. from rest_framework.response import Response
  5. from misago.acl import add_acl
  6. from misago.categories.models import THREADS_ROOT_NAME, Category
  7. from ...events import record_event
  8. from ...models import THREAD_WEIGHT_GLOBAL, Thread
  9. from ...moderation import threads as moderation
  10. from ...permissions import can_reply_thread, can_see_thread
  11. from ...serializers import NewThreadSerializer, ThreadsListSerializer
  12. from ...threadtypes import trees_map
  13. from ...utils import add_categories_to_threads, get_thread_id_from_url
  14. MERGE_LIMIT = 20 # no more than 20 threads can be merged in single action
  15. class MergeError(Exception):
  16. def __init__(self, msg):
  17. self.msg = msg
  18. def thread_merge_endpoint(request, thread, viewmodel):
  19. if not thread.acl['can_merge']:
  20. raise PermissionDenied(_("You don't have permission to merge this thread with others."))
  21. other_thread_id = get_thread_id_from_url(request, request.data.get('thread_url', None))
  22. if not other_thread_id:
  23. return Response({'detail': _("This is not a valid thread link.")}, status=400)
  24. if other_thread_id == thread.pk:
  25. return Response({'detail': _("You can't merge thread with itself.")}, status=400)
  26. try:
  27. other_thread = viewmodel(request, other_thread_id, select_for_update=True).model
  28. if not can_reply_thread(request.user, other_thread):
  29. raise PermissionDenied(_("You can't merge this thread into thread you can't reply."))
  30. if not other_thread.acl['can_merge']:
  31. raise PermissionDenied(_("You don't have permission to merge this thread with current one."))
  32. except PermissionDenied as e:
  33. return Response({
  34. 'detail': e.args[0]
  35. }, status=400)
  36. except Http404:
  37. return Response({
  38. 'detail': _("The thread you have entered link to doesn't exist or you don't have permission to see it.")
  39. }, status=400)
  40. moderation.merge_thread(request, other_thread, thread)
  41. other_thread.synchronize()
  42. other_thread.save()
  43. other_thread.category.synchronize()
  44. other_thread.category.save()
  45. if thread.category != other_thread.category:
  46. thread.category.synchronize()
  47. thread.category.save()
  48. return Response({
  49. 'id': other_thread.pk,
  50. 'title': other_thread.title,
  51. 'url': other_thread.get_absolute_url()
  52. })
  53. def threads_merge_endpoint(request):
  54. try:
  55. threads = clean_threads_for_merge(request)
  56. except MergeError as e:
  57. return Response({'detail': e.msg}, status=403)
  58. invalid_threads = []
  59. for thread in threads:
  60. if not thread.acl['can_merge']:
  61. invalid_threads.append({
  62. 'id': thread.pk,
  63. 'title': thread.title,
  64. 'errors': [
  65. _("You don't have permission to merge this thread with others.")
  66. ]
  67. })
  68. if invalid_threads:
  69. return Response(invalid_threads, status=403)
  70. serializer = NewThreadSerializer(context=request.user, data=request.data)
  71. if serializer.is_valid():
  72. new_thread = merge_threads(request, serializer.validated_data, threads)
  73. return Response(ThreadsListSerializer(new_thread).data)
  74. else:
  75. return Response(serializer.errors, status=400)
  76. def clean_threads_for_merge(request):
  77. try:
  78. threads_ids = list(map(int, request.data.get('threads', [])))
  79. except (ValueError, TypeError):
  80. raise MergeError(_("One or more thread ids received were invalid."))
  81. if len(threads_ids) < 2:
  82. raise MergeError(_("You have to select at least two threads to merge."))
  83. elif len(threads_ids) > MERGE_LIMIT:
  84. message = ungettext(
  85. "No more than %(limit)s thread can be merged at single time.",
  86. "No more than %(limit)s threads can be merged at single time.",
  87. MERGE_LIMIT)
  88. raise MergeError(message % {'limit': MERGE_LIMIT})
  89. threads_tree_id = trees_map.get_tree_id_for_root(THREADS_ROOT_NAME)
  90. threads_queryset = Thread.objects.filter(
  91. id__in=threads_ids,
  92. category__tree_id=threads_tree_id,
  93. ).select_for_update().select_related('category').order_by('-id')
  94. threads = []
  95. for thread in threads_queryset:
  96. add_acl(request.user, thread)
  97. if can_see_thread(request.user, thread):
  98. threads.append(thread)
  99. if len(threads) != len(threads_ids):
  100. raise MergeError(_("One or more threads to merge could not be found."))
  101. return threads
  102. def merge_threads(request, validated_data, threads):
  103. new_thread = Thread(
  104. category=validated_data['category'],
  105. started_on=threads[0].started_on,
  106. last_post_on=threads[0].last_post_on
  107. )
  108. new_thread.set_title(validated_data['title'])
  109. new_thread.save()
  110. categories = []
  111. for thread in threads:
  112. categories.append(thread.category)
  113. new_thread.merge(thread)
  114. thread.delete()
  115. record_event(request, new_thread, 'merged', {
  116. 'merged_thread': thread.title,
  117. }, commit=False)
  118. new_thread.synchronize()
  119. new_thread.save()
  120. if validated_data.get('weight') == THREAD_WEIGHT_GLOBAL:
  121. moderation.pin_thread_globally(request, new_thread)
  122. elif validated_data.get('weight'):
  123. moderation.pin_thread_locally(request, new_thread)
  124. if validated_data.get('is_hidden', False):
  125. moderation.hide_thread(request, new_thread)
  126. if validated_data.get('is_closed', False):
  127. moderation.close_thread(request, new_thread)
  128. if new_thread.category not in categories:
  129. categories.append(new_thread.category)
  130. for category in categories:
  131. category.synchronize()
  132. category.save()
  133. # set extra attrs on thread for UI
  134. new_thread.is_read = False
  135. new_thread.subscription = None
  136. # add top category to thread
  137. if validated_data.get('top_category'):
  138. categories = list(Category.objects.all_categories().filter(
  139. id__in=request.user.acl['visible_categories']
  140. ))
  141. add_categories_to_threads(validated_data['top_category'], categories, [new_thread])
  142. else:
  143. new_thread.top_category = None
  144. add_acl(request.user, new_thread)
  145. return new_thread