merge.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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. from .pollmergehandler import PollMergeHandler
  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).unwrap()
  29. if not can_reply_thread(request.user, other_thread):
  30. raise PermissionDenied(_("You can't merge this thread into thread you can't reply."))
  31. if not other_thread.acl['can_merge']:
  32. raise PermissionDenied(_("You don't have permission to merge this thread with current one."))
  33. except PermissionDenied as e:
  34. return Response({
  35. 'detail': e.args[0]
  36. }, status=400)
  37. except Http404:
  38. return Response({
  39. 'detail': _("The thread you have entered link to doesn't exist or you don't have permission to see it.")
  40. }, status=400)
  41. polls_handler = PollMergeHandler([thread, other_thread])
  42. if len(polls_handler.polls) == 1:
  43. poll = polls_handler.polls[0]
  44. poll.move(other_thread)
  45. elif polls_handler.is_merge_conflict():
  46. if 'poll' in request.data:
  47. polls_handler.set_resolution(request.data.get('poll'))
  48. if polls_handler.is_valid():
  49. poll = polls_handler.get_resolution()
  50. if poll and poll.thread_id != other_thread.id:
  51. other_thread.poll.delete()
  52. poll.move(other_thread)
  53. elif not poll:
  54. other_thread.poll.delete()
  55. else:
  56. return Response({
  57. 'detail': _("Invalid choice.")
  58. }, status=400)
  59. else:
  60. return Response({
  61. 'polls': polls_handler.get_available_resolutions()
  62. }, 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. if not thread.acl['can_merge']:
  84. invalid_threads.append({
  85. 'id': thread.pk,
  86. 'title': thread.title,
  87. 'errors': [
  88. _("You don't have permission to merge this thread with others.")
  89. ]
  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({
  105. 'detail': _("Invalid choice.")
  106. }, status=400)
  107. else:
  108. return Response({
  109. 'polls': polls_handler.get_available_resolutions()
  110. }, status=400)
  111. else:
  112. poll = None
  113. new_thread = merge_threads(request, serializer.validated_data, threads, poll)
  114. return Response(ThreadsListSerializer(new_thread).data)
  115. else:
  116. return Response(serializer.errors, status=400)
  117. def clean_threads_for_merge(request):
  118. try:
  119. threads_ids = list(map(int, request.data.get('threads', [])))
  120. except (ValueError, TypeError):
  121. raise MergeError(_("One or more thread ids received were invalid."))
  122. if len(threads_ids) < 2:
  123. raise MergeError(_("You have to select at least two threads to merge."))
  124. elif len(threads_ids) > MERGE_LIMIT:
  125. message = ungettext(
  126. "No more than %(limit)s thread can be merged at single time.",
  127. "No more than %(limit)s threads can be merged at single time.",
  128. MERGE_LIMIT)
  129. raise MergeError(message % {'limit': MERGE_LIMIT})
  130. threads_tree_id = trees_map.get_tree_id_for_root(THREADS_ROOT_NAME)
  131. threads_queryset = Thread.objects.filter(
  132. id__in=threads_ids,
  133. category__tree_id=threads_tree_id,
  134. ).select_for_update().select_related('category').order_by('-id')
  135. threads = []
  136. for thread in threads_queryset:
  137. add_acl(request.user, thread)
  138. if can_see_thread(request.user, thread):
  139. threads.append(thread)
  140. if len(threads) != len(threads_ids):
  141. raise MergeError(_("One or more threads to merge could not be found."))
  142. return threads
  143. def merge_threads(request, validated_data, threads, poll):
  144. new_thread = Thread(
  145. category=validated_data['category'],
  146. started_on=threads[0].started_on,
  147. last_post_on=threads[0].last_post_on
  148. )
  149. new_thread.set_title(validated_data['title'])
  150. new_thread.save()
  151. if poll:
  152. poll.move(new_thread)
  153. categories = []
  154. for thread in threads:
  155. categories.append(thread.category)
  156. new_thread.merge(thread)
  157. thread.delete()
  158. record_event(request, new_thread, 'merged', {
  159. 'merged_thread': thread.title,
  160. }, commit=False)
  161. new_thread.synchronize()
  162. new_thread.save()
  163. if validated_data.get('weight') == THREAD_WEIGHT_GLOBAL:
  164. moderation.pin_thread_globally(request, new_thread)
  165. elif validated_data.get('weight'):
  166. moderation.pin_thread_locally(request, new_thread)
  167. if validated_data.get('is_hidden', False):
  168. moderation.hide_thread(request, new_thread)
  169. if validated_data.get('is_closed', False):
  170. moderation.close_thread(request, new_thread)
  171. if new_thread.category not in categories:
  172. categories.append(new_thread.category)
  173. for category in categories:
  174. category.synchronize()
  175. category.save()
  176. # set extra attrs on thread for UI
  177. new_thread.is_read = False
  178. new_thread.subscription = None
  179. # add top category to thread
  180. if validated_data.get('top_category'):
  181. categories = list(Category.objects.all_categories().filter(
  182. id__in=request.user.acl['visible_categories']
  183. ))
  184. add_categories_to_threads(validated_data['top_category'], categories, [new_thread])
  185. else:
  186. new_thread.top_category = None
  187. add_acl(request.user, new_thread)
  188. return new_thread