merge.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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 import serializers
  5. from rest_framework.response import Response
  6. from misago.acl import add_acl
  7. from misago.categories.models import THREADS_ROOT_NAME, Category
  8. from ...events import record_event
  9. from ...models import THREAD_WEIGHT_DEFAULT, THREAD_WEIGHT_GLOBAL, Thread
  10. from ...moderation import threads as moderation
  11. from ...permissions import can_start_thread, can_reply_thread, can_see_thread
  12. from ...serializers import ThreadsListSerializer
  13. from ...threadtypes import trees_map
  14. from ...validators import validate_category, validate_title
  15. from ...utils import add_categories_to_threads, get_thread_id_from_url
  16. MERGE_LIMIT = 20 # no more than 20 threads can be merged in single action
  17. class MergeError(Exception):
  18. def __init__(self, msg):
  19. self.msg = msg
  20. def thread_merge_endpoint(request, thread, viewmodel):
  21. if not thread.acl['can_merge']:
  22. raise PermissionDenied(_("You don't have permission to merge this thread with others."))
  23. other_thread_id = get_thread_id_from_url(request, request.data.get('thread_url', None))
  24. if not other_thread_id:
  25. return Response({'detail': _("This is not a valid thread link.")}, status=400)
  26. if other_thread_id == thread.pk:
  27. return Response({'detail': _("You can't merge thread with itself.")}, status=400)
  28. try:
  29. other_thread = viewmodel(request, other_thread_id, select_for_update=True).model
  30. if not can_reply_thread(request.user, other_thread):
  31. raise PermissionDenied(_("You can't merge this thread into thread you can't reply."))
  32. if not other_thread.acl['can_merge']:
  33. raise PermissionDenied(_("You don't have permission to merge this thread with current one."))
  34. except PermissionDenied as e:
  35. return Response({
  36. 'detail': e.args[0]
  37. }, status=400)
  38. except Http404:
  39. return Response({
  40. 'detail': _("The thread you have entered link to doesn't exist or you don't have permission to see it.")
  41. }, status=400)
  42. moderation.merge_thread(request, other_thread, thread)
  43. other_thread.synchronize()
  44. other_thread.save()
  45. other_thread.category.synchronize()
  46. other_thread.category.save()
  47. if thread.category != other_thread.category:
  48. thread.category.synchronize()
  49. thread.category.save()
  50. return Response({
  51. 'id': other_thread.pk,
  52. 'title': other_thread.title,
  53. 'url': other_thread.get_absolute_url()
  54. })
  55. def threads_merge_endpoint(request):
  56. try:
  57. threads = clean_threads_for_merge(request)
  58. except MergeError as e:
  59. return Response({'detail': e.msg}, status=403)
  60. invalid_threads = []
  61. for thread in threads:
  62. if not thread.acl['can_merge']:
  63. invalid_threads.append({
  64. 'id': thread.pk,
  65. 'title': thread.title,
  66. 'errors': [
  67. _("You don't have permission to merge this thread with others.")
  68. ]
  69. })
  70. if invalid_threads:
  71. return Response(invalid_threads, status=403)
  72. serializer = MergeThreadsSerializer(context=request.user, data=request.data)
  73. if serializer.is_valid():
  74. new_thread = merge_threads(request, serializer.validated_data, threads)
  75. return Response(ThreadsListSerializer(new_thread).data)
  76. else:
  77. return Response(serializer.errors, status=400)
  78. def clean_threads_for_merge(request):
  79. try:
  80. threads_ids = list(map(int, request.data.get('threads', [])))
  81. except (ValueError, TypeError):
  82. raise MergeError(_("One or more thread ids received were invalid."))
  83. if len(threads_ids) < 2:
  84. raise MergeError(_("You have to select at least two threads to merge."))
  85. elif len(threads_ids) > MERGE_LIMIT:
  86. message = ungettext(
  87. "No more than %(limit)s thread can be merged at single time.",
  88. "No more than %(limit)s threads can be merged at single time.",
  89. MERGE_LIMIT)
  90. raise MergeError(message % {'limit': MERGE_LIMIT})
  91. threads_tree_id = trees_map.get_tree_id_for_root(THREADS_ROOT_NAME)
  92. threads_queryset = Thread.objects.filter(
  93. id__in=threads_ids,
  94. category__tree_id=threads_tree_id,
  95. ).select_for_update().select_related('category').order_by('-id')
  96. threads = []
  97. for thread in threads_queryset:
  98. add_acl(request.user, thread)
  99. if can_see_thread(request.user, thread):
  100. threads.append(thread)
  101. if len(threads) != len(threads_ids):
  102. raise MergeError(_("One or more threads to merge could not be found."))
  103. return threads
  104. def merge_threads(request, validated_data, threads):
  105. new_thread = Thread(
  106. category=validated_data['category'],
  107. weight=validated_data.get('weight', 0),
  108. is_closed=validated_data.get('is_closed', False),
  109. started_on=threads[0].started_on,
  110. last_post_on=threads[0].last_post_on,
  111. )
  112. new_thread.set_title(validated_data['title'])
  113. new_thread.save()
  114. categories = []
  115. for thread in threads:
  116. categories.append(thread.category)
  117. new_thread.merge(thread)
  118. thread.delete()
  119. record_event(request, new_thread, 'merged', {
  120. 'merged_thread': thread.title,
  121. }, commit=False)
  122. new_thread.synchronize()
  123. new_thread.save()
  124. if new_thread.category not in categories:
  125. categories.append(new_thread.category)
  126. for category in categories:
  127. category.synchronize()
  128. category.save()
  129. # set extra attrs on thread for UI
  130. new_thread.is_read = False
  131. new_thread.subscription = None
  132. # add top category to thread
  133. if validated_data.get('top_category'):
  134. categories = list(Category.objects.all_categories().filter(
  135. id__in=request.user.acl['visible_categories']
  136. ))
  137. add_categories_to_threads(validated_data['top_category'], categories, [new_thread])
  138. else:
  139. new_thread.top_category = None
  140. new_thread.save()
  141. add_acl(request.user, new_thread)
  142. return new_thread
  143. class MergeThreadsSerializer(serializers.Serializer):
  144. title = serializers.CharField()
  145. category = serializers.IntegerField()
  146. top_category = serializers.IntegerField(required=False, allow_null=True)
  147. weight = serializers.IntegerField(
  148. required=False,
  149. allow_null=True,
  150. max_value=THREAD_WEIGHT_GLOBAL,
  151. min_value=THREAD_WEIGHT_DEFAULT,
  152. )
  153. is_closed = serializers.NullBooleanField(required=False)
  154. def validate_title(self, title):
  155. return validate_title(title)
  156. def validate_top_category(self, category_id):
  157. return validate_category(self.context, category_id, allow_root=True)
  158. def validate_category(self, category_id):
  159. self.category = validate_category(self.context, category_id)
  160. if not can_start_thread(self.context, self.category):
  161. raise ValidationError(_("You can't create new threads in selected category."))
  162. return self.category
  163. def validate_weight(self, weight):
  164. try:
  165. add_acl(self.context, self.category)
  166. except AttributeError:
  167. return weight # don't validate weight further if category failed
  168. if weight > self.category.acl.get('can_pin_threads', 0):
  169. if weight == 2:
  170. raise ValidationError(_("You don't have permission to pin threads globally in this category."))
  171. else:
  172. raise ValidationError(_("You don't have permission to pin threads in this category."))
  173. return weight
  174. def validate_is_closed(self, is_closed):
  175. try:
  176. add_acl(self.context, self.category)
  177. except AttributeError:
  178. return is_closed # don't validate closed further if category failed
  179. if is_closed and not self.category.acl.get('can_close_threads'):
  180. raise ValidationError(_("You don't have permission to close threads in this category."))
  181. return is_closed