merge.py 8.0 KB

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