moderation.py 18 KB

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