merge.py 4.2 KB

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