merge.py 7.5 KB

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