patch.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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 it's not currently marked as best answer."
  200. )
  201. )
  202. allow_unmark_best_answer(request.user_acl, thread)
  203. thread.clear_best_answer()
  204. thread.save()
  205. return {
  206. "best_answer": None,
  207. "best_answer_is_protected": False,
  208. "best_answer_marked_on": None,
  209. "best_answer_marked_by": None,
  210. "best_answer_marked_by_name": None,
  211. "best_answer_marked_by_slug": None,
  212. }
  213. thread_patch_dispatcher.remove("best-answer", patch_unmark_best_answer)
  214. def patch_add_participant(request, thread, value):
  215. allow_add_participants(request.user_acl, thread)
  216. try:
  217. username = str(value).strip().lower()
  218. if not username:
  219. raise PermissionDenied(_("You have to enter new participant's username."))
  220. participant = User.objects.get(slug=username)
  221. except User.DoesNotExist:
  222. raise PermissionDenied(_("No user with such name exists."))
  223. if participant in [p.user for p in thread.participants_list]:
  224. raise PermissionDenied(_("This user is already thread participant."))
  225. participant_acl = useracl.get_user_acl(participant, request.cache_versions)
  226. allow_add_participant(request.user_acl, participant, participant_acl)
  227. add_participant(request, thread, participant)
  228. make_participants_aware(request.user, thread)
  229. participants = ThreadParticipantSerializer(thread.participants_list, many=True)
  230. return {"participants": participants.data}
  231. thread_patch_dispatcher.add("participants", patch_add_participant)
  232. def patch_remove_participant(request, thread, value):
  233. try:
  234. user_id = int(value)
  235. except (ValueError, TypeError):
  236. raise PermissionDenied(_("A valid integer is required."))
  237. for participant in thread.participants_list:
  238. if participant.user_id == user_id:
  239. break
  240. else:
  241. raise PermissionDenied(_("Participant doesn't exist."))
  242. allow_remove_participant(request.user_acl, thread, participant.user)
  243. remove_participant(request, thread, participant.user)
  244. if len(thread.participants_list) == 1:
  245. return {"deleted": True}
  246. make_participants_aware(request.user, thread)
  247. participants = ThreadParticipantSerializer(thread.participants_list, many=True)
  248. return {"deleted": False, "participants": participants.data}
  249. thread_patch_dispatcher.remove("participants", patch_remove_participant)
  250. def patch_replace_owner(request, thread, value):
  251. try:
  252. user_id = int(value)
  253. except (ValueError, TypeError):
  254. raise PermissionDenied(_("A valid integer is required."))
  255. for participant in thread.participants_list:
  256. if participant.user_id == user_id:
  257. if participant.is_owner:
  258. raise PermissionDenied(_("This user already is thread owner."))
  259. else:
  260. break
  261. else:
  262. raise PermissionDenied(_("Participant doesn't exist."))
  263. allow_change_owner(request.user_acl, thread)
  264. change_owner(request, thread, participant.user)
  265. make_participants_aware(request.user, thread)
  266. participants = ThreadParticipantSerializer(thread.participants_list, many=True)
  267. return {"participants": participants.data}
  268. thread_patch_dispatcher.replace("owner", patch_replace_owner)
  269. def thread_patch_endpoint(request, thread):
  270. old_title = thread.title
  271. old_is_hidden = thread.is_hidden
  272. old_is_unapproved = thread.is_unapproved
  273. old_category = thread.category
  274. response = thread_patch_dispatcher.dispatch(request, thread)
  275. # diff thread's state against pre-patch and resync category if necessary
  276. hidden_changed = old_is_hidden != thread.is_hidden
  277. unapproved_changed = old_is_unapproved != thread.is_unapproved
  278. category_changed = old_category != thread.category
  279. title_changed = old_title != thread.title
  280. if thread.category.last_thread_id != thread.pk:
  281. title_changed = False # don't trigger resync on simple title change
  282. if hidden_changed or unapproved_changed or category_changed:
  283. thread.category.synchronize()
  284. thread.category.save()
  285. if category_changed:
  286. old_category.synchronize()
  287. old_category.save()
  288. elif title_changed:
  289. thread.category.last_thread_title = thread.title
  290. thread.category.last_thread_slug = thread.slug
  291. thread.category.save(update_fields=["last_thread_title", "last_thread_slug"])
  292. return response
  293. def bulk_patch_endpoint(request, viewmodel):
  294. serializer = BulkPatchSerializer(data=request.data)
  295. if not serializer.is_valid():
  296. return Response(serializer.errors, status=400)
  297. threads = clean_threads_for_patch(request, viewmodel, serializer.data["ids"])
  298. old_titles = [t.title for t in threads]
  299. old_is_hidden = [t.is_hidden for t in threads]
  300. old_is_unapproved = [t.is_unapproved for t in threads]
  301. old_category = [t.category_id for t in threads]
  302. response = thread_patch_dispatcher.dispatch_bulk(request, threads)
  303. new_titles = [t.title for t in threads]
  304. new_is_hidden = [t.is_hidden for t in threads]
  305. new_is_unapproved = [t.is_unapproved for t in threads]
  306. new_category = [t.category_id for t in threads]
  307. # sync titles
  308. if new_titles != old_titles:
  309. for i, t in enumerate(threads):
  310. if t.title != old_titles[i] and t.category.last_thread_id == t.pk:
  311. t.category.last_thread_title = t.title
  312. t.category.last_thread_slug = t.slug
  313. t.category.save(update_fields=["last_thread_title", "last_thread_slug"])
  314. # sync categories
  315. sync_categories = []
  316. if new_is_hidden != old_is_hidden:
  317. for i, t in enumerate(threads):
  318. if t.is_hidden != old_is_hidden[i] and t.category_id not in sync_categories:
  319. sync_categories.append(t.category_id)
  320. if new_is_unapproved != old_is_unapproved:
  321. for i, t in enumerate(threads):
  322. if (
  323. t.is_unapproved != old_is_unapproved[i]
  324. and t.category_id not in sync_categories
  325. ):
  326. sync_categories.append(t.category_id)
  327. if new_category != old_category:
  328. for i, t in enumerate(threads):
  329. if t.category_id != old_category[i]:
  330. if t.category_id not in sync_categories:
  331. sync_categories.append(t.category_id)
  332. if old_category[i] not in sync_categories:
  333. sync_categories.append(old_category[i])
  334. if sync_categories:
  335. for category in Category.objects.filter(id__in=sync_categories):
  336. category.synchronize()
  337. category.save()
  338. return response
  339. def clean_threads_for_patch(request, viewmodel, threads_ids):
  340. threads = []
  341. for thread_id in sorted(set(threads_ids), reverse=True):
  342. try:
  343. threads.append(viewmodel(request, thread_id).unwrap())
  344. except (Http404, PermissionDenied):
  345. raise PermissionDenied(
  346. _("One or more threads to update could not be found.")
  347. )
  348. return threads
  349. class BulkPatchSerializer(serializers.Serializer):
  350. ids = serializers.ListField(
  351. child=serializers.IntegerField(min_value=1),
  352. max_length=PATCH_LIMIT,
  353. min_length=1,
  354. )
  355. ops = serializers.ListField(
  356. child=serializers.DictField(), min_length=1, max_length=10
  357. )