merge.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. from rest_framework.response import Response
  2. from django.core.exceptions import PermissionDenied
  3. from django.http import Http404
  4. from django.utils.translation import gettext as _
  5. from django.utils.translation import ungettext
  6. from misago.acl import add_acl
  7. from misago.categories import THREADS_ROOT_NAME
  8. from misago.threads.events import record_event
  9. from misago.threads.models import Thread
  10. from misago.threads.moderation import threads as moderation
  11. from misago.threads.permissions import can_reply_thread, can_see_thread
  12. from misago.threads.serializers import NewThreadSerializer, ThreadsListSerializer
  13. from misago.threads.threadtypes import trees_map
  14. from misago.threads.utils import get_thread_id_from_url
  15. from .pollmergehandler import PollMergeHandler
  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).unwrap()
  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(
  34. _("You don't have permission to merge this thread with current one.")
  35. )
  36. except PermissionDenied as e:
  37. return Response({'detail': e.args[0]}, status=400)
  38. except Http404:
  39. return Response(
  40. {
  41. 'detail': _(
  42. "The thread you have entered link to doesn't "
  43. "exist or you don't have permission to see it."
  44. )
  45. },
  46. status=400,
  47. )
  48. polls_handler = PollMergeHandler([thread, other_thread])
  49. if len(polls_handler.polls) == 1:
  50. poll = polls_handler.polls[0]
  51. poll.move(other_thread)
  52. elif polls_handler.is_merge_conflict():
  53. if 'poll' in request.data:
  54. polls_handler.set_resolution(request.data.get('poll'))
  55. if polls_handler.is_valid():
  56. poll = polls_handler.get_resolution()
  57. if poll and poll.thread_id != other_thread.id:
  58. other_thread.poll.delete()
  59. poll.move(other_thread)
  60. elif not poll:
  61. other_thread.poll.delete()
  62. else:
  63. return Response({'detail': _("Invalid choice.")}, status=400)
  64. else:
  65. return Response({'polls': polls_handler.get_available_resolutions()}, status=400)
  66. moderation.merge_thread(request, other_thread, thread)
  67. other_thread.synchronize()
  68. other_thread.save()
  69. other_thread.category.synchronize()
  70. other_thread.category.save()
  71. if thread.category != other_thread.category:
  72. thread.category.synchronize()
  73. thread.category.save()
  74. return Response({
  75. 'id': other_thread.pk,
  76. 'title': other_thread.title,
  77. 'url': other_thread.get_absolute_url(),
  78. })
  79. def threads_merge_endpoint(request):
  80. try:
  81. threads = clean_threads_for_merge(request)
  82. except MergeError as e:
  83. return Response({'detail': e.msg}, status=403)
  84. invalid_threads = []
  85. for thread in threads:
  86. if not thread.acl['can_merge']:
  87. invalid_threads.append({
  88. 'id': thread.pk,
  89. 'title': thread.title,
  90. 'errors': [_("You don't have permission to merge this thread with others.")]
  91. })
  92. if invalid_threads:
  93. return Response(invalid_threads, status=403)
  94. serializer = NewThreadSerializer(context=request.user, data=request.data)
  95. if serializer.is_valid():
  96. polls_handler = PollMergeHandler(threads)
  97. if len(polls_handler.polls) == 1:
  98. poll = polls_handler.polls[0]
  99. elif polls_handler.is_merge_conflict():
  100. if 'poll' in request.data:
  101. polls_handler.set_resolution(request.data.get('poll'))
  102. if polls_handler.is_valid():
  103. poll = polls_handler.get_resolution()
  104. else:
  105. return Response({'detail': _("Invalid choice.")}, status=400)
  106. else:
  107. return Response({'polls': polls_handler.get_available_resolutions()}, status=400)
  108. else:
  109. poll = None
  110. new_thread = merge_threads(request, serializer.validated_data, threads, poll)
  111. return Response(ThreadsListSerializer(new_thread).data)
  112. else:
  113. return Response(serializer.errors, status=400)
  114. def clean_threads_for_merge(request):
  115. try:
  116. threads_ids = list(map(int, request.data.get('threads', [])))
  117. except (ValueError, TypeError):
  118. raise MergeError(_("One or more thread ids received were invalid."))
  119. if len(threads_ids) < 2:
  120. raise MergeError(_("You have to select at least two threads to merge."))
  121. elif len(threads_ids) > MERGE_LIMIT:
  122. message = ungettext(
  123. "No more than %(limit)s thread can be merged at single time.",
  124. "No more than %(limit)s threads can be merged at single time.",
  125. MERGE_LIMIT,
  126. )
  127. raise MergeError(message % {'limit': MERGE_LIMIT})
  128. threads_tree_id = trees_map.get_tree_id_for_root(THREADS_ROOT_NAME)
  129. threads_queryset = Thread.objects.filter(
  130. id__in=threads_ids,
  131. category__tree_id=threads_tree_id,
  132. ).select_for_update().select_related('category').order_by('-id')
  133. threads = []
  134. for thread in threads_queryset:
  135. add_acl(request.user, thread)
  136. if can_see_thread(request.user, thread):
  137. threads.append(thread)
  138. if len(threads) != len(threads_ids):
  139. raise MergeError(_("One or more threads to merge could not be found."))
  140. return threads
  141. def merge_threads(request, validated_data, threads, poll):
  142. new_thread = Thread(
  143. category=validated_data['category'],
  144. started_on=threads[0].started_on,
  145. last_post_on=threads[0].last_post_on,
  146. )
  147. new_thread.set_title(validated_data['title'])
  148. new_thread.save()
  149. if poll:
  150. poll.move(new_thread)
  151. categories = []
  152. for thread in threads:
  153. categories.append(thread.category)
  154. new_thread.merge(thread)
  155. thread.delete()
  156. record_event(
  157. request,
  158. new_thread,
  159. 'merged',
  160. {
  161. 'merged_thread': thread.title,
  162. },
  163. commit=False,
  164. )
  165. new_thread.synchronize()
  166. new_thread.save()
  167. if validated_data.get('weight') == Thread.WEIGHT_GLOBAL:
  168. moderation.pin_thread_globally(request, new_thread)
  169. elif validated_data.get('weight'):
  170. moderation.pin_thread_locally(request, new_thread)
  171. if validated_data.get('is_hidden', False):
  172. moderation.hide_thread(request, new_thread)
  173. if validated_data.get('is_closed', False):
  174. moderation.close_thread(request, new_thread)
  175. if new_thread.category not in categories:
  176. categories.append(new_thread.category)
  177. for category in categories:
  178. category.synchronize()
  179. category.save()
  180. # set extra attrs on thread for UI
  181. new_thread.is_read = False
  182. new_thread.subscription = None
  183. add_acl(request.user, new_thread)
  184. return new_thread