merge.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. from django.core.exceptions import PermissionDenied
  2. from django.db import transaction
  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 misago.categories.permissions import can_see_category, can_browse_category
  8. from misago.threads.events import record_event
  9. from misago.threads.models import Thread
  10. from misago.threads.permissions import can_see_thread
  11. from misago.threads.serializers import ThreadListSerializer, MergeThreadsSerializer
  12. from misago.threads.threadtypes import trees_map
  13. from misago.threads.utils import add_categories_to_threads
  14. MERGE_LIMIT = 20 # no more than 20 threads can be merged in single action
  15. class MergeError(Exception):
  16. def __init__(self, msg):
  17. self.msg = msg
  18. def threads_merge_endpoint(request):
  19. try:
  20. threads = clean_threads_for_merge(request)
  21. except MergeError as e:
  22. return Response({'detail': e.msg}, status=403)
  23. invalid_threads = []
  24. for thread in threads:
  25. if not thread.acl['can_merge']:
  26. invalid_threads.append({
  27. 'id': thread.pk,
  28. 'title': thread.title,
  29. 'errors': [
  30. _("You don't have permission to merge this thread with others.")
  31. ]
  32. })
  33. if invalid_threads:
  34. return Response(invalid_threads, status=403)
  35. serializer = MergeThreadsSerializer(context=request.user, data=request.data)
  36. if serializer.is_valid():
  37. new_thread = merge_threads(request, serializer.validated_data, threads)
  38. return Response(ThreadListSerializer(new_thread).data)
  39. else:
  40. return Response(serializer.errors, status=400)
  41. def clean_threads_for_merge(request):
  42. try:
  43. threads_ids = map(int, request.data.get('threads', []))
  44. except (ValueError, TypeError):
  45. raise MergeError(_("One or more thread ids received were invalid."))
  46. if len(threads_ids) < 2:
  47. raise MergeError(_("You have to select at least two threads to merge."))
  48. elif len(threads_ids) > MERGE_LIMIT:
  49. message = ungettext(
  50. "No more than %(limit)s thread can be merged at single time.",
  51. "No more than %(limit)s threads can be merged at single time.",
  52. MERGE_LIMIT)
  53. raise MergeError(message % {'limit': MERGE_LIMIT})
  54. threads_tree_id = trees_map.get_tree_id_for_root(THREADS_ROOT_NAME)
  55. threads_queryset = Thread.objects.filter(
  56. id__in=threads_ids,
  57. category__tree_id=threads_tree_id,
  58. ).select_related('category').order_by('-id')
  59. threads = []
  60. for thread in threads_queryset:
  61. add_acl(request.user, thread)
  62. if can_see_thread(request.user, thread):
  63. threads.append(thread)
  64. if len(threads) != len(threads_ids):
  65. raise MergeError(_("One or more threads to merge could not be found."))
  66. return threads
  67. @transaction.atomic
  68. def merge_threads(request, validated_data, threads):
  69. new_thread = Thread(
  70. category=validated_data['category'],
  71. weight=validated_data.get('weight', 0),
  72. is_closed=validated_data.get('is_closed', False),
  73. started_on=threads[0].started_on,
  74. last_post_on=threads[0].last_post_on,
  75. )
  76. new_thread.set_title(validated_data['title'])
  77. new_thread.save()
  78. categories = []
  79. for thread in threads:
  80. categories.append(thread.category)
  81. new_thread.merge(thread)
  82. thread.delete()
  83. record_event(request, new_thread, 'merged', {
  84. 'merged_thread': thread.title,
  85. }, commit=False)
  86. new_thread.synchronize()
  87. new_thread.save()
  88. if new_thread.category not in categories:
  89. categories.append(new_thread.category)
  90. for category in categories:
  91. category.synchronize()
  92. category.save()
  93. # set extra attrs on thread for UI
  94. new_thread.is_read = False
  95. new_thread.subscription = None
  96. # add top category to thread
  97. if validated_data.get('top_category'):
  98. categories = list(Category.objects.all_categories().filter(
  99. id__in=request.user.acl['visible_categories']
  100. ))
  101. add_categories_to_threads(validated_data['top_category'], categories, [new_thread])
  102. else:
  103. new_thread.top_category = None
  104. new_thread.save()
  105. add_acl(request.user, new_thread)
  106. return new_thread