merge.py 5.9 KB

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