patch.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. from rest_framework import serializers
  2. from rest_framework.response import Response
  3. from django.contrib.auth import get_user_model
  4. from django.core.exceptions import PermissionDenied, ValidationError
  5. from django.http import Http404
  6. from django.shortcuts import get_object_or_404
  7. from django.utils import six
  8. from django.utils.translation import ugettext as _
  9. from misago.acl import add_acl
  10. from misago.api.patch import ApiPatch
  11. from misago.categories.models import Category
  12. from misago.categories.permissions import allow_browse_category, allow_see_category
  13. from misago.categories.serializers import CategorySerializer
  14. from misago.conf import settings
  15. from misago.core.shortcuts import get_int_or_404
  16. from misago.threads import moderation
  17. from misago.threads.participants import (
  18. add_participant, change_owner, make_participants_aware, remove_participant
  19. )
  20. from misago.threads.permissions import (
  21. allow_add_participant, allow_add_participants, allow_approve_thread, allow_change_best_answer,
  22. allow_change_owner, allow_edit_thread, allow_pin_thread, allow_hide_thread, allow_mark_as_best_answer,
  23. allow_mark_best_answer, allow_move_thread, allow_remove_participant, allow_see_post,
  24. allow_start_thread, allow_unhide_thread, allow_unmark_best_answer
  25. )
  26. from misago.threads.serializers import ThreadParticipantSerializer
  27. from misago.threads.validators import validate_title
  28. PATCH_LIMIT = settings.MISAGO_THREADS_PER_PAGE + settings.MISAGO_THREADS_TAIL
  29. UserModel = get_user_model()
  30. thread_patch_dispatcher = ApiPatch()
  31. def patch_acl(request, thread, value):
  32. """useful little op that updates thread acl to current state"""
  33. if value:
  34. add_acl(request.user, thread)
  35. return {'acl': thread.acl}
  36. else:
  37. return {'acl': None}
  38. thread_patch_dispatcher.add('acl', patch_acl)
  39. def patch_title(request, thread, value):
  40. try:
  41. value_cleaned = six.text_type(value).strip()
  42. except (TypeError, ValueError):
  43. raise ValidationError(_('Not a valid string.'))
  44. validate_title(value_cleaned)
  45. allow_edit_thread(request.user, thread)
  46. moderation.change_thread_title(request, thread, value_cleaned)
  47. return {'title': thread.title}
  48. thread_patch_dispatcher.replace('title', patch_title)
  49. def patch_weight(request, thread, value):
  50. allow_pin_thread(request.user, thread)
  51. if not thread.acl.get('can_pin_globally') and thread.weight == 2:
  52. raise PermissionDenied(_("You can't change globally pinned threads weights in this category."))
  53. if value == 2:
  54. if thread.acl.get('can_pin_globally'):
  55. moderation.pin_thread_globally(request, thread)
  56. else:
  57. raise PermissionDenied(_("You can't pin threads globally in this category."))
  58. elif value == 1:
  59. moderation.pin_thread_locally(request, thread)
  60. elif value == 0:
  61. moderation.unpin_thread(request, thread)
  62. return {'weight': thread.weight}
  63. thread_patch_dispatcher.replace('weight', patch_weight)
  64. def patch_move(request, thread, value):
  65. allow_move_thread(request.user, thread)
  66. category_pk = get_int_or_404(value)
  67. new_category = get_object_or_404(
  68. Category.objects.all_categories().select_related('parent'), pk=category_pk
  69. )
  70. add_acl(request.user, new_category)
  71. allow_see_category(request.user, new_category)
  72. allow_browse_category(request.user, new_category)
  73. allow_start_thread(request.user, new_category)
  74. if new_category == thread.category:
  75. raise ValidationError(_("You can't move thread to the category it's already in."))
  76. moderation.move_thread(request, thread, new_category)
  77. return {'category': CategorySerializer(new_category).data}
  78. thread_patch_dispatcher.replace('category', patch_move)
  79. def patch_flatten_categories(request, thread, value):
  80. try:
  81. return {'category': thread.category_id}
  82. except AttributeError:
  83. return {'category': thread.category_id}
  84. thread_patch_dispatcher.replace('flatten-categories', patch_flatten_categories)
  85. def patch_is_unapproved(request, thread, value):
  86. allow_approve_thread(request.user, thread)
  87. if value:
  88. raise PermissionDenied(_("Content approval can't be reversed."))
  89. moderation.approve_thread(request, thread)
  90. return {
  91. 'is_unapproved': thread.is_unapproved,
  92. 'has_unapproved_posts': thread.has_unapproved_posts,
  93. }
  94. thread_patch_dispatcher.replace('is-unapproved', patch_is_unapproved)
  95. def patch_is_closed(request, thread, value):
  96. if thread.acl.get('can_close'):
  97. if value:
  98. moderation.close_thread(request, thread)
  99. else:
  100. moderation.open_thread(request, thread)
  101. return {'is_closed': thread.is_closed}
  102. else:
  103. if value:
  104. raise PermissionDenied(_("You don't have permission to close this thread."))
  105. else:
  106. raise PermissionDenied(_("You don't have permission to open this thread."))
  107. thread_patch_dispatcher.replace('is-closed', patch_is_closed)
  108. def patch_is_hidden(request, thread, value):
  109. if value:
  110. allow_hide_thread(request.user, thread)
  111. moderation.hide_thread(request, thread)
  112. else:
  113. allow_unhide_thread(request.user, thread)
  114. moderation.unhide_thread(request, thread)
  115. return {'is_hidden': thread.is_hidden}
  116. thread_patch_dispatcher.replace('is-hidden', patch_is_hidden)
  117. def patch_subscription(request, thread, value):
  118. request.user.subscription_set.filter(thread=thread).delete()
  119. if value == 'notify':
  120. thread.subscription = request.user.subscription_set.create(
  121. thread=thread,
  122. category=thread.category,
  123. last_read_on=thread.last_post_on,
  124. send_email=False,
  125. )
  126. return {'subscription': False}
  127. elif value == 'email':
  128. thread.subscription = request.user.subscription_set.create(
  129. thread=thread,
  130. category=thread.category,
  131. last_read_on=thread.last_post_on,
  132. send_email=True,
  133. )
  134. return {'subscription': True}
  135. else:
  136. return {'subscription': None}
  137. thread_patch_dispatcher.replace('subscription', patch_subscription)
  138. def patch_best_answer(request, thread, value):
  139. try:
  140. post_id = int(value)
  141. except (TypeError, ValueError):
  142. raise ValidationError(_("A valid integer is required."))
  143. allow_mark_best_answer(request.user, thread)
  144. post = get_object_or_404(thread.post_set, id=post_id)
  145. post.category = thread.category
  146. post.thread = thread
  147. allow_see_post(request.user, post)
  148. allow_mark_as_best_answer(request.user, post)
  149. if post.is_best_answer:
  150. raise PermissionDenied(_("This post is already marked as thread's best answer."))
  151. if thread.has_best_answer:
  152. allow_change_best_answer(request.user, thread)
  153. thread.set_best_answer(request.user, post)
  154. thread.save()
  155. return {
  156. 'best_answer': thread.best_answer_id,
  157. 'best_answer_is_protected': thread.best_answer_is_protected,
  158. 'best_answer_marked_on': thread.best_answer_marked_on,
  159. 'best_answer_marked_by': thread.best_answer_marked_by_id,
  160. 'best_answer_marked_by_name': thread.best_answer_marked_by_name,
  161. 'best_answer_marked_by_slug': thread.best_answer_marked_by_slug,
  162. }
  163. thread_patch_dispatcher.replace('best-answer', patch_best_answer)
  164. def patch_unmark_best_answer(request, thread, value):
  165. try:
  166. post_id = int(value)
  167. except (TypeError, ValueError):
  168. raise ValidationError(_("A valid integer is required."))
  169. post = get_object_or_404(thread.post_set, id=post_id)
  170. post.category = thread.category
  171. post.thread = thread
  172. if not post.is_best_answer:
  173. raise PermissionDenied(
  174. _("This post can't be unmarked because it's not currently marked as best answer."))
  175. allow_unmark_best_answer(request.user, thread)
  176. thread.clear_best_answer()
  177. thread.save()
  178. return {
  179. 'best_answer': None,
  180. 'best_answer_is_protected': False,
  181. 'best_answer_marked_on': None,
  182. 'best_answer_marked_by': None,
  183. 'best_answer_marked_by_name': None,
  184. 'best_answer_marked_by_slug': None,
  185. }
  186. thread_patch_dispatcher.remove('best-answer', patch_unmark_best_answer)
  187. def patch_add_participant(request, thread, value):
  188. allow_add_participants(request.user, thread)
  189. try:
  190. username = six.text_type(value).strip().lower()
  191. if not username:
  192. raise ValidationError(_("You have to enter new participant's username."))
  193. participant = UserModel.objects.get(slug=username)
  194. except UserModel.DoesNotExist:
  195. raise ValidationError(_("No user with such name exists."))
  196. if participant in [p.user for p in thread.participants_list]:
  197. raise ValidationError(_("This user is already thread participant."))
  198. max_participants = request.user.acl_cache['max_private_thread_participants']
  199. if max_participants:
  200. current_participants = len(thread.participants_list)
  201. if current_participants >= max_participants:
  202. raise ValidationError(_("You can't add any more new users to this thread."))
  203. try:
  204. allow_add_participant(request.user, participant)
  205. except PermissionDenied as e:
  206. raise ValidationError(six.text_type(e))
  207. add_participant(request, thread, participant)
  208. make_participants_aware(request.user, thread)
  209. participants = ThreadParticipantSerializer(thread.participants_list, many=True)
  210. return {'participants': participants.data}
  211. thread_patch_dispatcher.add('participants', patch_add_participant)
  212. def patch_remove_participant(request, thread, value):
  213. try:
  214. user_id = int(value)
  215. except (TypeError, ValueError):
  216. raise ValidationError(_("A valid integer is required."))
  217. for participant in thread.participants_list:
  218. if participant.user_id == user_id:
  219. break
  220. else:
  221. raise ValidationError(_("Participant doesn't exist."))
  222. allow_remove_participant(request.user, thread, participant.user)
  223. remove_participant(request, thread, participant.user)
  224. if len(thread.participants_list) == 1:
  225. return {'deleted': True}
  226. else:
  227. make_participants_aware(request.user, thread)
  228. participants = ThreadParticipantSerializer(thread.participants_list, many=True)
  229. return {
  230. 'deleted': False,
  231. 'participants': participants.data,
  232. }
  233. thread_patch_dispatcher.remove('participants', patch_remove_participant)
  234. def patch_replace_owner(request, thread, value):
  235. try:
  236. user_id = int(value)
  237. except (TypeError, ValueError):
  238. raise ValidationError(_("A valid integer is required."))
  239. for participant in thread.participants_list:
  240. if participant.user_id == user_id:
  241. if participant.is_owner:
  242. raise ValidationError(_("This user already is thread owner."))
  243. else:
  244. break
  245. else:
  246. raise ValidationError(_("Participant doesn't exist."))
  247. allow_change_owner(request.user, thread)
  248. change_owner(request, thread, participant.user)
  249. make_participants_aware(request.user, thread)
  250. participants = ThreadParticipantSerializer(thread.participants_list, many=True)
  251. return {'participants': participants.data}
  252. thread_patch_dispatcher.replace('owner', patch_replace_owner)
  253. def thread_patch_endpoint(request, thread):
  254. old_title = thread.title
  255. old_is_hidden = thread.is_hidden
  256. old_is_unapproved = thread.is_unapproved
  257. old_category = thread.category
  258. response = thread_patch_dispatcher.dispatch(request, thread)
  259. # diff thread's state against pre-patch and resync category if necessary
  260. hidden_changed = old_is_hidden != thread.is_hidden
  261. unapproved_changed = old_is_unapproved != thread.is_unapproved
  262. category_changed = old_category != thread.category
  263. title_changed = old_title != thread.title
  264. if thread.category.last_thread_id != thread.pk:
  265. title_changed = False # don't trigger resync on simple title change
  266. if hidden_changed or unapproved_changed or category_changed:
  267. thread.category.synchronize()
  268. thread.category.save()
  269. if category_changed:
  270. old_category.synchronize()
  271. old_category.save()
  272. elif title_changed:
  273. thread.category.last_thread_title = thread.title
  274. thread.category.last_thread_slug = thread.slug
  275. thread.category.save(update_fields=['last_thread_title', 'last_thread_slug'])
  276. return response
  277. def bulk_patch_endpoint(request, viewmodel):
  278. serializer = BulkPatchSerializer(data=request.data)
  279. serializer.is_valid(raise_exception=True)
  280. threads = clean_threads_for_patch(request, viewmodel, serializer.data['ids'])
  281. old_titles = [t.title for t in threads]
  282. old_is_hidden = [t.is_hidden for t in threads]
  283. old_is_unapproved = [t.is_unapproved for t in threads]
  284. old_category = [t.category_id for t in threads]
  285. response = thread_patch_dispatcher.dispatch_bulk(request, threads)
  286. new_titles = [t.title for t in threads]
  287. new_is_hidden = [t.is_hidden for t in threads]
  288. new_is_unapproved = [t.is_unapproved for t in threads]
  289. new_category = [t.category_id for t in threads]
  290. # sync titles
  291. if new_titles != old_titles:
  292. for i, t in enumerate(threads):
  293. if t.title != old_titles[i] and t.category.last_thread_id == t.pk:
  294. t.category.last_thread_title = t.title
  295. t.category.last_thread_slug = t.slug
  296. t.category.save(update_fields=['last_thread_title', 'last_thread_slug'])
  297. # sync categories
  298. sync_categories = []
  299. if new_is_hidden != old_is_hidden:
  300. for i, t in enumerate(threads):
  301. if t.is_hidden != old_is_hidden[i] and t.category_id not in sync_categories:
  302. sync_categories.append(t.category_id)
  303. if new_is_unapproved != old_is_unapproved:
  304. for i, t in enumerate(threads):
  305. if t.is_unapproved != old_is_unapproved[i] and t.category_id not in sync_categories:
  306. sync_categories.append(t.category_id)
  307. if new_category != old_category:
  308. for i, t in enumerate(threads):
  309. if t.category_id != old_category[i]:
  310. if t.category_id not in sync_categories:
  311. sync_categories.append(t.category_id)
  312. if old_category[i] not in sync_categories:
  313. sync_categories.append(old_category[i])
  314. if sync_categories:
  315. for category in Category.objects.filter(id__in=sync_categories):
  316. category.synchronize()
  317. category.save()
  318. return response
  319. def clean_threads_for_patch(request, viewmodel, threads_ids):
  320. threads = []
  321. for thread_id in sorted(set(threads_ids), reverse=True):
  322. threads.append(viewmodel(request, thread_id).unwrap())
  323. return threads
  324. class BulkPatchSerializer(serializers.Serializer):
  325. ids = serializers.ListField(
  326. child=serializers.IntegerField(min_value=1),
  327. max_length=PATCH_LIMIT,
  328. min_length=1,
  329. )
  330. ops = serializers.ListField(
  331. child=serializers.DictField(),
  332. min_length=1,
  333. max_length=10,
  334. )