moderation.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. from rest_framework import serializers
  2. from django.core.exceptions import PermissionDenied, ValidationError
  3. from django.http import Http404
  4. from django.utils.translation import ugettext as _, ugettext_lazy, ungettext
  5. from misago.acl import add_acl
  6. from misago.categories import THREADS_ROOT_NAME
  7. from misago.conf import settings
  8. from misago.threads.mergeconflict import MergeConflict
  9. from misago.threads.models import Thread
  10. from misago.threads.permissions import (
  11. allow_delete_best_answer, allow_delete_event, allow_delete_post, allow_delete_thread,
  12. allow_merge_post, allow_merge_thread,
  13. allow_move_post, allow_split_post,
  14. can_reply_thread, can_see_thread,
  15. can_start_thread, exclude_invisible_posts)
  16. from misago.threads.threadtypes import trees_map
  17. from misago.threads.utils import get_thread_id_from_url
  18. from misago.threads.validators import validate_category, validate_title
  19. POSTS_LIMIT = settings.MISAGO_POSTS_PER_PAGE + settings.MISAGO_POSTS_TAIL
  20. THREADS_LIMIT = settings.MISAGO_THREADS_PER_PAGE + settings.MISAGO_THREADS_TAIL
  21. __all__ = [
  22. 'DeletePostsSerializer',
  23. 'DeleteThreadsSerializer',
  24. 'MergePostsSerializer',
  25. 'MergeThreadSerializer',
  26. 'MergeThreadsSerializer',
  27. 'MovePostsSerializer',
  28. 'NewThreadSerializer',
  29. 'SplitPostsSerializer',
  30. ]
  31. class DeletePostsSerializer(serializers.Serializer):
  32. error_empty_or_required = ugettext_lazy("You have to specify at least one post to delete.")
  33. posts = serializers.ListField(
  34. allow_empty=False,
  35. child=serializers.IntegerField(
  36. error_messages={
  37. 'invalid': ugettext_lazy("One or more post ids received were invalid."),
  38. },
  39. ),
  40. error_messages={
  41. 'required': error_empty_or_required,
  42. 'null': error_empty_or_required,
  43. 'empty': error_empty_or_required,
  44. },
  45. )
  46. def validate_posts(self, data):
  47. if len(data) > POSTS_LIMIT:
  48. message = ungettext(
  49. "No more than %(limit)s post can be deleted at single time.",
  50. "No more than %(limit)s posts can be deleted at single time.",
  51. POSTS_LIMIT,
  52. )
  53. raise ValidationError(message % {'limit': POSTS_LIMIT})
  54. user = self.context['user']
  55. thread = self.context['thread']
  56. posts_queryset = exclude_invisible_posts(user, thread.category, thread.post_set)
  57. posts_queryset = posts_queryset.filter(id__in=data).order_by('id')
  58. posts = []
  59. for post in posts_queryset:
  60. post.category = thread.category
  61. post.thread = thread
  62. if post.is_event:
  63. allow_delete_event(user, post)
  64. else:
  65. allow_delete_best_answer(user, post)
  66. allow_delete_post(user, post)
  67. posts.append(post)
  68. if len(posts) != len(data):
  69. raise PermissionDenied(_("One or more posts to delete could not be found."))
  70. return posts
  71. class MergePostsSerializer(serializers.Serializer):
  72. error_empty_or_required = ugettext_lazy("You have to select at least two posts to merge.")
  73. posts = serializers.ListField(
  74. child=serializers.IntegerField(
  75. error_messages={
  76. 'invalid': ugettext_lazy("One or more post ids received were invalid."),
  77. },
  78. ),
  79. error_messages={
  80. 'null': error_empty_or_required,
  81. 'required': error_empty_or_required,
  82. },
  83. )
  84. def validate_posts(self, data):
  85. data = list(set(data))
  86. if len(data) < 2:
  87. raise serializers.ValidationError(self.error_empty_or_required)
  88. if len(data) > POSTS_LIMIT:
  89. message = ungettext(
  90. "No more than %(limit)s post can be merged at single time.",
  91. "No more than %(limit)s posts can be merged at single time.",
  92. POSTS_LIMIT,
  93. )
  94. raise serializers.ValidationError(message % {'limit': POSTS_LIMIT})
  95. user = self.context['user']
  96. thread = self.context['thread']
  97. posts_queryset = exclude_invisible_posts(user, thread.category, thread.post_set)
  98. posts_queryset = posts_queryset.filter(id__in=data).order_by('id')
  99. posts = []
  100. for post in posts_queryset:
  101. post.category = thread.category
  102. post.thread = thread
  103. try:
  104. allow_merge_post(user, post)
  105. except PermissionDenied as e:
  106. raise serializers.ValidationError(e)
  107. if not posts:
  108. posts.append(post)
  109. continue
  110. authorship_error = _("Posts made by different users can't be merged.")
  111. if post.poster_id != posts[0].poster_id:
  112. raise serializers.ValidationError(authorship_error)
  113. elif (post.poster_id is None and posts[0].poster_id is None and
  114. post.poster_name != posts[0].poster_name):
  115. raise serializers.ValidationError(authorship_error)
  116. if posts[0].is_first_post and post.is_best_answer:
  117. raise serializers.ValidationError(
  118. _("Post marked as best answer can't be merged with thread's first post.")
  119. )
  120. if not posts[0].is_first_post:
  121. if (posts[0].is_hidden != post.is_hidden or
  122. posts[0].is_unapproved != post.is_unapproved):
  123. raise serializers.ValidationError(
  124. _("Posts with different visibility can't be merged.")
  125. )
  126. posts.append(post)
  127. if len(posts) != len(data):
  128. raise serializers.ValidationError(_("One or more posts to merge could not be found."))
  129. return posts
  130. class MovePostsSerializer(serializers.Serializer):
  131. error_empty_or_required = ugettext_lazy("You have to specify at least one post to move.")
  132. new_thread = serializers.CharField(
  133. error_messages={
  134. 'required': ugettext_lazy("Enter link to new thread."),
  135. },
  136. )
  137. posts = serializers.ListField(
  138. allow_empty=False,
  139. child=serializers.IntegerField(
  140. error_messages={
  141. 'invalid': ugettext_lazy("One or more post ids received were invalid."),
  142. },
  143. ),
  144. error_messages={
  145. 'empty': error_empty_or_required,
  146. 'null': error_empty_or_required,
  147. 'required': error_empty_or_required,
  148. },
  149. )
  150. def validate_new_thread(self, data):
  151. request = self.context['request']
  152. thread = self.context['thread']
  153. viewmodel = self.context['viewmodel']
  154. new_thread_id = get_thread_id_from_url(request, data)
  155. if not new_thread_id:
  156. raise serializers.ValidationError(_("This is not a valid thread link."))
  157. if new_thread_id == thread.pk:
  158. raise serializers.ValidationError(_("Thread to move posts to is same as current one."))
  159. try:
  160. new_thread = viewmodel(request, new_thread_id).unwrap()
  161. except Http404:
  162. raise serializers.ValidationError(
  163. _(
  164. "The thread you have entered link to doesn't "
  165. "exist or you don't have permission to see it."
  166. )
  167. )
  168. if not new_thread.acl['can_reply']:
  169. raise serializers.ValidationError(_("You can't move posts to threads you can't reply."))
  170. return new_thread
  171. def validate_posts(self, data):
  172. data = list(set(data))
  173. if len(data) > POSTS_LIMIT:
  174. message = ungettext(
  175. "No more than %(limit)s post can be moved at single time.",
  176. "No more than %(limit)s posts can be moved at single time.",
  177. POSTS_LIMIT,
  178. )
  179. raise serializers.ValidationError(message % {'limit': POSTS_LIMIT})
  180. request = self.context['request']
  181. thread = self.context['thread']
  182. posts_queryset = exclude_invisible_posts(request.user, thread.category, thread.post_set)
  183. posts_queryset = posts_queryset.filter(id__in=data).order_by('id')
  184. posts = []
  185. for post in posts_queryset:
  186. post.category = thread.category
  187. post.thread = thread
  188. try:
  189. allow_move_post(request.user, post)
  190. posts.append(post)
  191. except PermissionDenied as e:
  192. raise serializers.ValidationError(e)
  193. if len(posts) != len(data):
  194. raise serializers.ValidationError(_("One or more posts to move could not be found."))
  195. return posts
  196. class NewThreadSerializer(serializers.Serializer):
  197. title = serializers.CharField()
  198. category = serializers.IntegerField()
  199. weight = serializers.IntegerField(
  200. required=False,
  201. allow_null=True,
  202. max_value=Thread.WEIGHT_GLOBAL,
  203. min_value=Thread.WEIGHT_DEFAULT,
  204. )
  205. is_hidden = serializers.NullBooleanField(required=False)
  206. is_closed = serializers.NullBooleanField(required=False)
  207. def validate_title(self, title):
  208. return validate_title(title)
  209. def validate_category(self, category_id):
  210. self.category = validate_category(self.context['user'], category_id)
  211. if not can_start_thread(self.context['user'], self.category):
  212. raise ValidationError(_("You can't create new threads in selected category."))
  213. return self.category
  214. def validate_weight(self, weight):
  215. try:
  216. add_acl(self.context['user'], self.category)
  217. except AttributeError:
  218. return weight # don't validate weight further if category failed
  219. if weight > self.category.acl.get('can_pin_threads', 0):
  220. if weight == 2:
  221. raise ValidationError(
  222. _("You don't have permission to pin threads globally in this category.")
  223. )
  224. else:
  225. raise ValidationError(
  226. _("You don't have permission to pin threads in this category.")
  227. )
  228. return weight
  229. def validate_is_hidden(self, is_hidden):
  230. try:
  231. add_acl(self.context['user'], self.category)
  232. except AttributeError:
  233. return is_hidden # don't validate hidden further if category failed
  234. if is_hidden and not self.category.acl.get('can_hide_threads'):
  235. raise ValidationError(_("You don't have permission to hide threads in this category."))
  236. return is_hidden
  237. def validate_is_closed(self, is_closed):
  238. try:
  239. add_acl(self.context['user'], self.category)
  240. except AttributeError:
  241. return is_closed # don't validate closed further if category failed
  242. if is_closed and not self.category.acl.get('can_close_threads'):
  243. raise ValidationError(
  244. _("You don't have permission to close threads in this category.")
  245. )
  246. return is_closed
  247. class SplitPostsSerializer(NewThreadSerializer):
  248. error_empty_or_required = ugettext_lazy("You have to specify at least one post to split.")
  249. posts = serializers.ListField(
  250. allow_empty=False,
  251. child=serializers.IntegerField(
  252. error_messages={
  253. 'invalid': ugettext_lazy("One or more post ids received were invalid."),
  254. },
  255. ),
  256. error_messages={
  257. 'empty': error_empty_or_required,
  258. 'null': error_empty_or_required,
  259. 'required': error_empty_or_required,
  260. },
  261. )
  262. def validate_posts(self, data):
  263. if len(data) > POSTS_LIMIT:
  264. message = ungettext(
  265. "No more than %(limit)s post can be split at single time.",
  266. "No more than %(limit)s posts can be split at single time.",
  267. POSTS_LIMIT,
  268. )
  269. raise ValidationError(message % {'limit': POSTS_LIMIT})
  270. thread = self.context['thread']
  271. user = self.context['user']
  272. posts_queryset = exclude_invisible_posts(user, thread.category, thread.post_set)
  273. posts_queryset = posts_queryset.filter(id__in=data).order_by('id')
  274. posts = []
  275. for post in posts_queryset:
  276. post.category = thread.category
  277. post.thread = thread
  278. try:
  279. allow_split_post(user, post)
  280. except PermissionDenied as e:
  281. raise ValidationError(e)
  282. posts.append(post)
  283. if len(posts) != len(data):
  284. raise ValidationError(_("One or more posts to split could not be found."))
  285. return posts
  286. class DeleteThreadsSerializer(serializers.Serializer):
  287. error_empty_or_required = ugettext_lazy("You have to specify at least one thread to delete.")
  288. threads = serializers.ListField(
  289. allow_empty=False,
  290. child=serializers.IntegerField(
  291. error_messages={
  292. 'invalid': ugettext_lazy("One or more thread ids received were invalid."),
  293. },
  294. ),
  295. error_messages={
  296. 'required': error_empty_or_required,
  297. 'null': error_empty_or_required,
  298. 'empty': error_empty_or_required,
  299. },
  300. )
  301. def validate_threads(self, data):
  302. if len(data) > THREADS_LIMIT:
  303. message = ungettext(
  304. "No more than %(limit)s thread can be deleted at single time.",
  305. "No more than %(limit)s threads can be deleted at single time.",
  306. THREADS_LIMIT,
  307. )
  308. raise ValidationError(message % {'limit': THREADS_LIMIT})
  309. request = self.context['request']
  310. viewmodel = self.context['viewmodel']
  311. threads = []
  312. errors = []
  313. for thread_id in data:
  314. try:
  315. thread = viewmodel(request, thread_id).unwrap()
  316. allow_delete_thread(request.user, thread)
  317. threads.append(thread)
  318. except PermissionDenied as e:
  319. errors.append({
  320. 'thread': {
  321. 'id': thread.id,
  322. 'title': thread.title
  323. },
  324. 'error': str(e)
  325. })
  326. except Http404 as e:
  327. pass # skip invisible threads
  328. if errors:
  329. raise serializers.ValidationError({'details': errors})
  330. if len(threads) != len(data):
  331. raise ValidationError(_("One or more threads to delete could not be found."))
  332. return threads
  333. class MergeThreadSerializer(serializers.Serializer):
  334. other_thread = serializers.CharField(
  335. error_messages={
  336. 'required': ugettext_lazy("Enter link to new thread."),
  337. },
  338. )
  339. best_answer = serializers.IntegerField(
  340. required=False,
  341. error_messages={
  342. 'invalid': ugettext_lazy("Invalid choice."),
  343. },
  344. )
  345. poll = serializers.IntegerField(
  346. required=False,
  347. error_messages={
  348. 'invalid': ugettext_lazy("Invalid choice."),
  349. },
  350. )
  351. def validate_other_thread(self, data):
  352. request = self.context['request']
  353. thread = self.context['thread']
  354. viewmodel = self.context['viewmodel']
  355. other_thread_id = get_thread_id_from_url(request, data)
  356. if not other_thread_id:
  357. raise ValidationError(_("This is not a valid thread link."))
  358. if other_thread_id == thread.pk:
  359. raise ValidationError(_("You can't merge thread with itself."))
  360. try:
  361. other_thread = viewmodel(request, other_thread_id).unwrap()
  362. allow_merge_thread(request.user, other_thread, otherthread=True)
  363. except PermissionDenied as e:
  364. raise serializers.ValidationError(e)
  365. except Http404:
  366. raise ValidationError(
  367. _(
  368. "The thread you have entered link to doesn't "
  369. "exist or you don't have permission to see it."
  370. )
  371. )
  372. if not can_reply_thread(request.user, other_thread):
  373. raise ValidationError(_("You can't merge this thread into thread you can't reply."))
  374. return other_thread
  375. def validate(self, data):
  376. thread = self.context['thread']
  377. other_thread = data['other_thread']
  378. merge_conflict = MergeConflict(data, [thread, other_thread])
  379. merge_conflict.is_valid(raise_exception=True)
  380. data.update(merge_conflict.get_resolution())
  381. self.merge_conflict = merge_conflict.get_conflicting_fields()
  382. return data
  383. class MergeThreadsSerializer(NewThreadSerializer):
  384. error_empty_or_required = ugettext_lazy("You have to select at least two threads to merge.")
  385. threads = serializers.ListField(
  386. allow_empty=False,
  387. min_length=2,
  388. child=serializers.IntegerField(
  389. error_messages={
  390. 'invalid': ugettext_lazy("One or more thread ids received were invalid."),
  391. },
  392. ),
  393. error_messages={
  394. 'empty': error_empty_or_required,
  395. 'null': error_empty_or_required,
  396. 'required': error_empty_or_required,
  397. 'min_length': error_empty_or_required,
  398. },
  399. )
  400. best_answer = serializers.IntegerField(
  401. required=False,
  402. error_messages={
  403. 'invalid': ugettext_lazy("Invalid choice."),
  404. },
  405. )
  406. poll = serializers.IntegerField(
  407. required=False,
  408. error_messages={
  409. 'invalid': ugettext_lazy("Invalid choice."),
  410. },
  411. )
  412. def validate_threads(self, data):
  413. if len(data) > THREADS_LIMIT:
  414. message = ungettext(
  415. "No more than %(limit)s thread can be merged at single time.",
  416. "No more than %(limit)s threads can be merged at single time.",
  417. POSTS_LIMIT,
  418. )
  419. raise ValidationError(message % {'limit': THREADS_LIMIT})
  420. threads_tree_id = trees_map.get_tree_id_for_root(THREADS_ROOT_NAME)
  421. threads_queryset = Thread.objects.filter(
  422. id__in=data,
  423. category__tree_id=threads_tree_id,
  424. ).select_related('category').order_by('-id')
  425. user = self.context['user']
  426. threads = []
  427. for thread in threads_queryset:
  428. add_acl(user, thread)
  429. if can_see_thread(user, thread):
  430. threads.append(thread)
  431. if len(threads) != len(data):
  432. raise ValidationError(_("One or more threads to merge could not be found."))
  433. return threads