moderation.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. from rest_framework import serializers
  2. from django.core.exceptions import PermissionDenied, ValidationError
  3. from django.http import Http404
  4. from django.utils import six
  5. from django.utils.translation import ugettext as _, ugettext_lazy, ungettext
  6. from misago.acl import add_acl
  7. from misago.categories import THREADS_ROOT_NAME
  8. from misago.conf import settings
  9. from misago.threads.models import Thread
  10. from misago.threads.permissions import (
  11. 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.pollmergehandler import PollMergeHandler
  17. from misago.threads.threadtypes import trees_map
  18. from misago.threads.utils import get_thread_id_from_url
  19. from misago.threads.validators import validate_category, validate_title
  20. POSTS_LIMIT = settings.MISAGO_POSTS_PER_PAGE + settings.MISAGO_POSTS_TAIL
  21. THREADS_LIMIT = settings.MISAGO_THREADS_PER_PAGE + settings.MISAGO_THREADS_TAIL
  22. __all__ = [
  23. 'DeletePostsSerializer',
  24. 'DeleteThreadsSerializer',
  25. 'MergePostsSerializer',
  26. 'MergeThreadSerializer',
  27. 'MergeThreadsSerializer',
  28. 'MovePostsSerializer',
  29. 'NewThreadSerializer',
  30. 'SplitPostsSerializer',
  31. ]
  32. class DeletePostsSerializer(serializers.Serializer):
  33. error_empty_or_required = ugettext_lazy("You have to specify at least one post to delete.")
  34. posts = serializers.ListField(
  35. allow_empty=False,
  36. child=serializers.IntegerField(
  37. error_messages={
  38. 'invalid': ugettext_lazy("One or more post ids received were invalid."),
  39. },
  40. ),
  41. error_messages={
  42. 'required': error_empty_or_required,
  43. 'null': error_empty_or_required,
  44. 'empty': error_empty_or_required,
  45. },
  46. )
  47. def validate_posts(self, data):
  48. if len(data) > POSTS_LIMIT:
  49. message = ungettext(
  50. "No more than %(limit)s post can be deleted at single time.",
  51. "No more than %(limit)s posts can be deleted at single time.",
  52. POSTS_LIMIT,
  53. )
  54. raise ValidationError(message % {'limit': POSTS_LIMIT})
  55. user = self.context['user']
  56. thread = self.context['thread']
  57. posts_queryset = exclude_invisible_posts(user, thread.category, thread.post_set)
  58. posts_queryset = posts_queryset.filter(id__in=data).order_by('id')
  59. posts = []
  60. for post in posts_queryset:
  61. post.category = thread.category
  62. post.thread = thread
  63. if post.is_event:
  64. allow_delete_event(user, post)
  65. else:
  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': six.text_type(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. poll = serializers.IntegerField(
  340. required=False,
  341. error_messages={
  342. 'invalid': ugettext_lazy("Invalid choice."),
  343. },
  344. )
  345. def validate_other_thread(self, data):
  346. request = self.context['request']
  347. thread = self.context['thread']
  348. viewmodel = self.context['viewmodel']
  349. other_thread_id = get_thread_id_from_url(request, data)
  350. if not other_thread_id:
  351. raise ValidationError(_("This is not a valid thread link."))
  352. if other_thread_id == thread.pk:
  353. raise ValidationError(_("You can't merge thread with itself."))
  354. try:
  355. other_thread = viewmodel(request, other_thread_id).unwrap()
  356. allow_merge_thread(request.user, other_thread, otherthread=True)
  357. except PermissionDenied as e:
  358. raise serializers.ValidationError(e)
  359. except Http404:
  360. raise ValidationError(
  361. _(
  362. "The thread you have entered link to doesn't "
  363. "exist or you don't have permission to see it."
  364. )
  365. )
  366. if not can_reply_thread(request.user, other_thread):
  367. raise ValidationError(_("You can't merge this thread into thread you can't reply."))
  368. return other_thread
  369. def validate(self, data):
  370. thread = self.context['thread']
  371. other_thread = data['other_thread']
  372. polls_handler = PollMergeHandler([thread, other_thread])
  373. if len(polls_handler.polls) == 1:
  374. data['poll'] = polls_handler.polls[0]
  375. elif polls_handler.is_merge_conflict():
  376. if 'poll' in data:
  377. polls_handler.set_resolution(data['poll'])
  378. if polls_handler.is_valid():
  379. data['poll'] = polls_handler.get_resolution()
  380. else:
  381. raise serializers.ValidationError({'poll': _("Invalid choice.")})
  382. else:
  383. data['polls'] = polls_handler.get_available_resolutions()
  384. self.polls_handler = polls_handler
  385. return data
  386. class MergeThreadsSerializer(NewThreadSerializer):
  387. error_empty_or_required = ugettext_lazy("You have to select at least two threads to merge.")
  388. threads = serializers.ListField(
  389. allow_empty=False,
  390. min_length=2,
  391. child=serializers.IntegerField(
  392. error_messages={
  393. 'invalid': ugettext_lazy("One or more thread ids received were invalid."),
  394. },
  395. ),
  396. error_messages={
  397. 'empty': error_empty_or_required,
  398. 'null': error_empty_or_required,
  399. 'required': error_empty_or_required,
  400. 'min_length': error_empty_or_required,
  401. },
  402. )
  403. def validate_threads(self, data):
  404. if len(data) > THREADS_LIMIT:
  405. message = ungettext(
  406. "No more than %(limit)s thread can be merged at single time.",
  407. "No more than %(limit)s threads can be merged at single time.",
  408. POSTS_LIMIT,
  409. )
  410. raise ValidationError(message % {'limit': THREADS_LIMIT})
  411. threads_tree_id = trees_map.get_tree_id_for_root(THREADS_ROOT_NAME)
  412. threads_queryset = Thread.objects.filter(
  413. id__in=data,
  414. category__tree_id=threads_tree_id,
  415. ).select_related('category').order_by('-id')
  416. user = self.context['user']
  417. threads = []
  418. for thread in threads_queryset:
  419. add_acl(user, thread)
  420. if can_see_thread(user, thread):
  421. threads.append(thread)
  422. if len(threads) != len(data):
  423. raise ValidationError(_("One or more threads to merge could not be found."))
  424. return threads