patch.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. from django.contrib.auth import get_user_model
  2. from django.core.exceptions import PermissionDenied, ValidationError
  3. from django.http import Http404
  4. from django.shortcuts import get_object_or_404
  5. from django.utils.translation import gettext as _
  6. from rest_framework import serializers
  7. from rest_framework.response import Response
  8. from ....acl import useracl
  9. from ....acl.objectacl import add_acl_to_obj
  10. from ....categories.models import Category
  11. from ....categories.permissions import allow_browse_category, allow_see_category
  12. from ....categories.serializers import CategorySerializer
  13. from ....conf import settings
  14. from ....core.apipatch import ApiPatch
  15. from ....core.shortcuts import get_int_or_404
  16. from ...moderation import threads as moderation
  17. from ...participants import (
  18. add_participant,
  19. change_owner,
  20. make_participants_aware,
  21. remove_participant,
  22. )
  23. from ...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_hide_thread,
  31. allow_mark_as_best_answer,
  32. allow_mark_best_answer,
  33. allow_move_thread,
  34. allow_pin_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 ...serializers import ThreadParticipantSerializer
  42. from ...validators import validate_thread_title
  43. PATCH_LIMIT = settings.MISAGO_THREADS_PER_PAGE + settings.MISAGO_THREADS_TAIL
  44. User = 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. return {"acl": None}
  52. thread_patch_dispatcher.add("acl", patch_acl)
  53. def patch_title(request, thread, value):
  54. try:
  55. value_cleaned = str(value).strip()
  56. except (TypeError, ValueError):
  57. raise PermissionDenied(_("Not a valid string."))
  58. try:
  59. validate_thread_title(request.settings, value_cleaned)
  60. except ValidationError as e:
  61. raise PermissionDenied(e.args[0])
  62. allow_edit_thread(request.user_acl, thread)
  63. moderation.change_thread_title(request, thread, value_cleaned)
  64. return {"title": thread.title}
  65. thread_patch_dispatcher.replace("title", patch_title)
  66. def patch_weight(request, thread, value):
  67. allow_pin_thread(request.user_acl, thread)
  68. if not thread.acl.get("can_pin_globally") and thread.weight == 2:
  69. raise PermissionDenied(
  70. _("You can't change globally pinned threads weights in this category.")
  71. )
  72. if value == 2:
  73. if thread.acl.get("can_pin_globally"):
  74. moderation.pin_thread_globally(request, thread)
  75. else:
  76. raise PermissionDenied(
  77. _("You can't pin threads globally in this category.")
  78. )
  79. elif value == 1:
  80. moderation.pin_thread_locally(request, thread)
  81. elif value == 0:
  82. moderation.unpin_thread(request, thread)
  83. return {"weight": thread.weight}
  84. thread_patch_dispatcher.replace("weight", patch_weight)
  85. def patch_move(request, thread, value):
  86. allow_move_thread(request.user_acl, thread)
  87. category_pk = get_int_or_404(value)
  88. new_category = get_object_or_404(
  89. Category.objects.all_categories().select_related("parent"), pk=category_pk
  90. )
  91. add_acl_to_obj(request.user_acl, new_category)
  92. allow_see_category(request.user_acl, new_category)
  93. allow_browse_category(request.user_acl, new_category)
  94. allow_start_thread(request.user_acl, new_category)
  95. if new_category == thread.category:
  96. raise PermissionDenied(
  97. _("You can't move thread to the category it's already in.")
  98. )
  99. moderation.move_thread(request, thread, new_category)
  100. return {"category": CategorySerializer(new_category).data}
  101. thread_patch_dispatcher.replace("category", patch_move)
  102. def patch_flatten_categories(request, thread, value):
  103. try:
  104. return {"category": thread.category_id}
  105. except AttributeError:
  106. return {"category": thread.category_id}
  107. thread_patch_dispatcher.replace("flatten-categories", patch_flatten_categories)
  108. def patch_is_unapproved(request, thread, value):
  109. allow_approve_thread(request.user_acl, thread)
  110. if value:
  111. raise PermissionDenied(_("Content approval can't be reversed."))
  112. moderation.approve_thread(request, thread)
  113. return {
  114. "is_unapproved": thread.is_unapproved,
  115. "has_unapproved_posts": thread.has_unapproved_posts,
  116. }
  117. thread_patch_dispatcher.replace("is-unapproved", patch_is_unapproved)
  118. def patch_is_closed(request, thread, value):
  119. if thread.acl.get("can_close"):
  120. if value:
  121. moderation.close_thread(request, thread)
  122. else:
  123. moderation.open_thread(request, thread)
  124. return {"is_closed": thread.is_closed}
  125. else:
  126. if value:
  127. raise PermissionDenied(_("You don't have permission to close this thread."))
  128. else:
  129. raise PermissionDenied(_("You don't have permission to open this thread."))
  130. thread_patch_dispatcher.replace("is-closed", patch_is_closed)
  131. def patch_is_hidden(request, thread, value):
  132. if value:
  133. allow_hide_thread(request.user_acl, thread)
  134. moderation.hide_thread(request, thread)
  135. else:
  136. allow_unhide_thread(request.user_acl, thread)
  137. moderation.unhide_thread(request, thread)
  138. return {"is_hidden": thread.is_hidden}
  139. thread_patch_dispatcher.replace("is-hidden", patch_is_hidden)
  140. def patch_subscription(request, thread, value):
  141. request.user.subscription_set.filter(thread=thread).delete()
  142. if value == "notify":
  143. thread.subscription = request.user.subscription_set.create(
  144. thread=thread,
  145. category=thread.category,
  146. last_read_on=thread.last_post_on,
  147. send_email=False,
  148. )
  149. return {"subscription": False}
  150. if value == "email":
  151. thread.subscription = request.user.subscription_set.create(
  152. thread=thread,
  153. category=thread.category,
  154. last_read_on=thread.last_post_on,
  155. send_email=True,
  156. )
  157. return {"subscription": True}
  158. return {"subscription": None}
  159. thread_patch_dispatcher.replace("subscription", patch_subscription)
  160. def patch_best_answer(request, thread, value):
  161. try:
  162. post_id = int(value)
  163. except (TypeError, ValueError):
  164. raise PermissionDenied(_("A valid integer is required."))
  165. allow_mark_best_answer(request.user_acl, thread)
  166. post = get_object_or_404(thread.post_set, id=post_id)
  167. post.category = thread.category
  168. post.thread = thread
  169. allow_see_post(request.user_acl, post)
  170. allow_mark_as_best_answer(request.user_acl, post)
  171. if post.is_best_answer:
  172. raise PermissionDenied(
  173. _("This post is already marked as thread's best answer.")
  174. )
  175. if thread.has_best_answer:
  176. allow_change_best_answer(request.user_acl, thread)
  177. thread.set_best_answer(request.user, post)
  178. thread.save()
  179. return {
  180. "best_answer": thread.best_answer_id,
  181. "best_answer_is_protected": thread.best_answer_is_protected,
  182. "best_answer_marked_on": thread.best_answer_marked_on,
  183. "best_answer_marked_by": thread.best_answer_marked_by_id,
  184. "best_answer_marked_by_name": thread.best_answer_marked_by_name,
  185. "best_answer_marked_by_slug": thread.best_answer_marked_by_slug,
  186. }
  187. thread_patch_dispatcher.replace("best-answer", patch_best_answer)
  188. def patch_unmark_best_answer(request, thread, value):
  189. try:
  190. post_id = int(value)
  191. except (TypeError, ValueError):
  192. raise PermissionDenied(_("A valid integer is required."))
  193. post = get_object_or_404(thread.post_set, id=post_id)
  194. post.category = thread.category
  195. post.thread = thread
  196. if not post.is_best_answer:
  197. raise PermissionDenied(
  198. _(
  199. "This post can't be unmarked because "
  200. "it's not currently marked as best answer."
  201. )
  202. )
  203. allow_unmark_best_answer(request.user_acl, thread)
  204. thread.clear_best_answer()
  205. thread.save()
  206. return {
  207. "best_answer": None,
  208. "best_answer_is_protected": False,
  209. "best_answer_marked_on": None,
  210. "best_answer_marked_by": None,
  211. "best_answer_marked_by_name": None,
  212. "best_answer_marked_by_slug": None,
  213. }
  214. thread_patch_dispatcher.remove("best-answer", patch_unmark_best_answer)
  215. def patch_add_participant(request, thread, value):
  216. allow_add_participants(request.user_acl, thread)
  217. try:
  218. username = str(value).strip().lower()
  219. if not username:
  220. raise PermissionDenied(_("You have to enter new participant's username."))
  221. participant = User.objects.get(slug=username)
  222. except User.DoesNotExist:
  223. raise PermissionDenied(_("No user with such name exists."))
  224. if participant in [p.user for p in thread.participants_list]:
  225. raise PermissionDenied(_("This user is already thread participant."))
  226. participant_acl = useracl.get_user_acl(participant, request.cache_versions)
  227. allow_add_participant(request.user_acl, participant, participant_acl)
  228. add_participant(request, thread, participant)
  229. make_participants_aware(request.user, thread)
  230. participants = ThreadParticipantSerializer(thread.participants_list, many=True)
  231. return {"participants": participants.data}
  232. thread_patch_dispatcher.add("participants", patch_add_participant)
  233. def patch_remove_participant(request, thread, value):
  234. # pylint: disable=undefined-loop-variable
  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. make_participants_aware(request.user, thread)
  249. participants = ThreadParticipantSerializer(thread.participants_list, many=True)
  250. return {"deleted": False, "participants": participants.data}
  251. thread_patch_dispatcher.remove("participants", patch_remove_participant)
  252. def patch_replace_owner(request, thread, value):
  253. # pylint: disable=undefined-loop-variable
  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(
  297. request, viewmodel
  298. ): # pylint: disable=too-many-branches, too-many-locals
  299. serializer = BulkPatchSerializer(data=request.data)
  300. if not serializer.is_valid():
  301. return Response(serializer.errors, status=400)
  302. threads = clean_threads_for_patch(request, viewmodel, serializer.data["ids"])
  303. old_titles = [t.title for t in threads]
  304. old_is_hidden = [t.is_hidden for t in threads]
  305. old_is_unapproved = [t.is_unapproved for t in threads]
  306. old_category = [t.category_id for t in threads]
  307. response = thread_patch_dispatcher.dispatch_bulk(request, threads)
  308. new_titles = [t.title for t in threads]
  309. new_is_hidden = [t.is_hidden for t in threads]
  310. new_is_unapproved = [t.is_unapproved for t in threads]
  311. new_category = [t.category_id for t in threads]
  312. # sync titles
  313. if new_titles != old_titles:
  314. for i, t in enumerate(threads):
  315. if t.title != old_titles[i] and t.category.last_thread_id == t.pk:
  316. t.category.last_thread_title = t.title
  317. t.category.last_thread_slug = t.slug
  318. t.category.save(update_fields=["last_thread_title", "last_thread_slug"])
  319. # sync categories
  320. sync_categories = []
  321. if new_is_hidden != old_is_hidden:
  322. for i, t in enumerate(threads):
  323. if t.is_hidden != old_is_hidden[i] and t.category_id not in sync_categories:
  324. sync_categories.append(t.category_id)
  325. if new_is_unapproved != old_is_unapproved:
  326. for i, t in enumerate(threads):
  327. if (
  328. t.is_unapproved != old_is_unapproved[i]
  329. and t.category_id not in sync_categories
  330. ):
  331. sync_categories.append(t.category_id)
  332. if new_category != old_category:
  333. for i, t in enumerate(threads):
  334. if t.category_id != old_category[i]:
  335. if t.category_id not in sync_categories:
  336. sync_categories.append(t.category_id)
  337. if old_category[i] not in sync_categories:
  338. sync_categories.append(old_category[i])
  339. if sync_categories:
  340. for category in Category.objects.filter(id__in=sync_categories):
  341. category.synchronize()
  342. category.save()
  343. return response
  344. def clean_threads_for_patch(request, viewmodel, threads_ids):
  345. threads = []
  346. for thread_id in sorted(set(threads_ids), reverse=True):
  347. try:
  348. threads.append(viewmodel(request, thread_id).unwrap())
  349. except (Http404, PermissionDenied):
  350. raise PermissionDenied(
  351. _("One or more threads to update could not be found.")
  352. )
  353. return threads
  354. class BulkPatchSerializer(serializers.Serializer):
  355. ids = serializers.ListField(
  356. child=serializers.IntegerField(min_value=1),
  357. max_length=PATCH_LIMIT,
  358. min_length=1,
  359. )
  360. ops = serializers.ListField(
  361. child=serializers.DictField(), min_length=1, max_length=10
  362. )