patch.py 15 KB

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