patch.py 15 KB

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