merge.py 5.9 KB

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