patch.py 10 KB

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