patch.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. from django.contrib.auth import get_user_model
  2. from django.core.exceptions import PermissionDenied, ValidationError
  3. from django.utils import six
  4. from django.utils.translation import gettext as _
  5. from misago.acl import add_acl
  6. from misago.categories.models import Category
  7. from misago.categories.permissions import allow_browse_category, allow_see_category
  8. from misago.categories.serializers import CategorySerializer
  9. from misago.core.apipatch import ApiPatch
  10. from misago.core.shortcuts import get_int_or_404, get_object_or_404
  11. from ...models import ThreadParticipant
  12. from ...moderation import threads as moderation
  13. from ...participants import add_participant, change_owner, remove_participant
  14. from ...permissions import (
  15. allow_add_participants, allow_add_participant,
  16. allow_change_owner, allow_remove_participant, allow_start_thread)
  17. from ...serializers import ThreadParticipantSerializer
  18. from ...utils import add_categories_to_items
  19. from ...validators import validate_title
  20. thread_patch_dispatcher = ApiPatch()
  21. def patch_acl(request, thread, value):
  22. """useful little op that updates thread acl to current state"""
  23. if value:
  24. add_acl(request.user, thread)
  25. return {'acl': thread.acl}
  26. else:
  27. return {'acl': None}
  28. thread_patch_dispatcher.add('acl', patch_acl)
  29. def patch_title(request, thread, value):
  30. try:
  31. value_cleaned = six.text_type(value).strip()
  32. except (TypeError, ValueError):
  33. raise PermissionDenied(_("Invalid thread title."))
  34. try:
  35. validate_title(value_cleaned)
  36. except ValidationError as e:
  37. raise PermissionDenied(e.args[0])
  38. if not thread.acl.get('can_edit'):
  39. raise PermissionDenied(_("You don't have permission to edit this thread."))
  40. moderation.change_thread_title(request, thread, value_cleaned)
  41. return {'title': thread.title}
  42. thread_patch_dispatcher.replace('title', patch_title)
  43. def patch_weight(request, thread, value):
  44. message = _("You don't have permission to change this thread's weight.")
  45. if not thread.acl.get('can_pin'):
  46. raise PermissionDenied(message)
  47. elif thread.weight > thread.acl.get('can_pin'):
  48. raise PermissionDenied(message)
  49. if value == 2:
  50. if thread.acl.get('can_pin') == 2:
  51. moderation.pin_thread_globally(request, thread)
  52. else:
  53. raise PermissionDenied(_("You don't have permission to pin this thread globally."))
  54. elif value == 1:
  55. moderation.pin_thread_locally(request, thread)
  56. elif value == 0:
  57. moderation.unpin_thread(request, thread)
  58. return {'weight': thread.weight}
  59. thread_patch_dispatcher.replace('weight', patch_weight)
  60. def patch_move(request, thread, value):
  61. if not thread.acl.get('can_move'):
  62. raise PermissionDenied(_("You don't have permission to move this thread."))
  63. category_pk = get_int_or_404(value)
  64. new_category = get_object_or_404(
  65. Category.objects.all_categories().select_related('parent'),
  66. pk=category_pk
  67. )
  68. add_acl(request.user, new_category)
  69. allow_see_category(request.user, new_category)
  70. allow_browse_category(request.user, new_category)
  71. allow_start_thread(request.user, new_category)
  72. if new_category == thread.category:
  73. raise PermissionDenied(_("You can't move thread to the category it's already in."))
  74. moderation.move_thread(request, thread, new_category)
  75. return {'category': CategorySerializer(new_category).data}
  76. thread_patch_dispatcher.replace('category', patch_move)
  77. def patch_top_category(request, thread, value):
  78. category_pk = get_int_or_404(value)
  79. root_category = get_object_or_404(
  80. Category.objects.all_categories(include_root=True),
  81. pk=category_pk
  82. )
  83. categories = list(Category.objects.all_categories().filter(
  84. id__in=request.user.acl['visible_categories']
  85. ))
  86. add_categories_to_items(root_category, categories, [thread])
  87. return {'top_category': CategorySerializer(thread.top_category).data}
  88. thread_patch_dispatcher.add('top-category', patch_top_category)
  89. def patch_flatten_categories(request, thread, value):
  90. try:
  91. return {
  92. 'category': thread.category_id,
  93. 'top_category': thread.top_category.pk,
  94. }
  95. except AttributeError as e:
  96. return {
  97. 'category': thread.category_id,
  98. 'top_category': None
  99. }
  100. thread_patch_dispatcher.replace('flatten-categories', patch_flatten_categories)
  101. def patch_is_unapproved(request, thread, value):
  102. if thread.acl.get('can_approve'):
  103. if value:
  104. raise PermissionDenied(_("Content approval can't be reversed."))
  105. moderation.approve_thread(request, thread)
  106. return {
  107. 'is_unapproved': thread.is_unapproved,
  108. 'has_unapproved_posts': thread.has_unapproved_posts,
  109. }
  110. else:
  111. raise PermissionDenied(_("You don't have permission to approve this thread."))
  112. thread_patch_dispatcher.replace('is-unapproved', patch_is_unapproved)
  113. def patch_is_closed(request, thread, value):
  114. if thread.acl.get('can_close'):
  115. if value:
  116. moderation.close_thread(request, thread)
  117. else:
  118. moderation.open_thread(request, thread)
  119. return {'is_closed': thread.is_closed}
  120. else:
  121. if value:
  122. raise PermissionDenied(_("You don't have permission to close this thread."))
  123. else:
  124. raise PermissionDenied(_("You don't have permission to open this thread."))
  125. thread_patch_dispatcher.replace('is-closed', patch_is_closed)
  126. def patch_is_hidden(request, thread, value):
  127. if thread.acl.get('can_hide'):
  128. if value:
  129. moderation.hide_thread(request, thread)
  130. else:
  131. moderation.unhide_thread(request, thread)
  132. return {'is_hidden': thread.is_hidden}
  133. else:
  134. raise PermissionDenied(_("You don't have permission to hide this thread."))
  135. thread_patch_dispatcher.replace('is-hidden', patch_is_hidden)
  136. def patch_subscribtion(request, thread, value):
  137. request.user.subscription_set.filter(thread=thread).delete()
  138. if value == 'notify':
  139. thread.subscription = request.user.subscription_set.create(
  140. thread=thread,
  141. category=thread.category,
  142. last_read_on=thread.last_post_on,
  143. send_email=False,
  144. )
  145. return {'subscription': False}
  146. elif value == 'email':
  147. thread.subscription = request.user.subscription_set.create(
  148. thread=thread,
  149. category=thread.category,
  150. last_read_on=thread.last_post_on,
  151. send_email=True,
  152. )
  153. return {'subscription': True}
  154. else:
  155. return {'subscription': None}
  156. thread_patch_dispatcher.replace('subscription', patch_subscribtion)
  157. def patch_add_participant(request, thread, value):
  158. allow_add_participants(request.user, thread)
  159. User = get_user_model()
  160. try:
  161. username = six.text_type(value).strip().lower()
  162. if not username:
  163. raise PermissionDenied(
  164. _("You have to enter new participant's username."))
  165. participant = User.objects.get(slug=username)
  166. except User.DoesNotExist:
  167. raise PermissionDenied(_("No user with such name exists."))
  168. if participant in [p.user for p in thread.participants_list]:
  169. raise PermissionDenied(_("This user is already thread participant."))
  170. allow_add_participant(request.user, participant)
  171. add_participant(request, thread, participant)
  172. return {
  173. 'participant': ThreadParticipantSerializer(
  174. ThreadParticipant(user=participant, is_owner=False)
  175. ).data
  176. }
  177. thread_patch_dispatcher.add('participants', patch_add_participant)
  178. def patch_remove_participant(request, thread, value):
  179. try:
  180. user_id = int(value)
  181. except (ValueError, TypeError):
  182. raise PermissionDenied(_("Participant to remove is invalid."))
  183. for participant in thread.participants_list:
  184. if participant.user_id == user_id:
  185. break
  186. else:
  187. raise PermissionDenied(_("Participant doesn't exist."))
  188. allow_remove_participant(request.user, thread, participant.user)
  189. remove_participant(request, thread, participant.user)
  190. return {
  191. 'deleted': len(thread.participants_list) == 1
  192. }
  193. thread_patch_dispatcher.remove('participants', patch_remove_participant)
  194. def patch_replace_owner(request, thread, value):
  195. try:
  196. user_id = int(value)
  197. except (ValueError, TypeError):
  198. raise PermissionDenied(_("Participant to remove is invalid."))
  199. for participant in thread.participants_list:
  200. if participant.user_id == user_id:
  201. break
  202. else:
  203. raise PermissionDenied(_("Participant doesn't exist."))
  204. allow_change_owner(request.user, thread)
  205. thread_patch_dispatcher.replace('owner', patch_replace_owner)
  206. def thread_patch_endpoint(request, thread):
  207. old_title = thread.title
  208. old_is_hidden = thread.is_hidden
  209. old_is_unapproved = thread.is_unapproved
  210. old_category = thread.category
  211. response = thread_patch_dispatcher.dispatch(request, thread)
  212. # diff thread's state against pre-patch and resync category if necessary
  213. hidden_changed = old_is_hidden != thread.is_hidden
  214. unapproved_changed = old_is_unapproved != thread.is_unapproved
  215. category_changed = old_category != thread.category
  216. title_changed = old_is_hidden != thread.is_hidden
  217. if thread.category.last_thread_id != thread.pk:
  218. title_changed = False # don't trigger resync on simple title change
  219. if hidden_changed or unapproved_changed or category_changed:
  220. thread.category.synchronize()
  221. thread.category.save()
  222. if category_changed:
  223. old_category.synchronize()
  224. old_category.save()
  225. elif title_changed:
  226. thread.category.last_thread_title = thread.title
  227. thread.category.last_thread_slug = thread.slug
  228. thread.category.save(update_fields=['last_thread_title', 'last_thread_slug'])
  229. return response