privatethreads.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. from django.contrib import messages
  2. from django.contrib.auth import get_user_model
  3. from django.core.exceptions import PermissionDenied
  4. from django.db.transaction import atomic
  5. from django.http import Http404, JsonResponse
  6. from django.shortcuts import get_object_or_404, redirect
  7. from django.utils.translation import ugettext as _, ungettext
  8. from misago.acl import add_acl
  9. from misago.core.errorpages import not_allowed
  10. from misago.core.exceptions import AjaxError
  11. from misago.core.uiviews import uiview
  12. from misago.forums.models import Forum
  13. from misago.users.decorators import deny_guests
  14. from misago.threads import participants
  15. from misago.threads.events import record_event
  16. from misago.threads.forms.posting import ThreadParticipantsForm
  17. from misago.threads.models import Thread, ThreadParticipant
  18. from misago.threads.permissions import (allow_use_private_threads,
  19. allow_see_private_thread,
  20. allow_see_private_post,
  21. exclude_invisible_private_threads)
  22. from misago.threads.views import generic
  23. def private_threads_view(klass):
  24. """
  25. decorator for making views check allow_use_private_threads
  26. """
  27. def decorator(f):
  28. def dispatch(self, request, *args, **kwargs):
  29. allow_use_private_threads(request.user)
  30. return f(self, request, *args, **kwargs)
  31. return dispatch
  32. klass.dispatch = decorator(klass.dispatch)
  33. return klass
  34. class PrivateThreadsMixin(object):
  35. """
  36. Mixin is used to make views use different permission tests
  37. """
  38. def get_forum(self, request, lock=False, **kwargs):
  39. forum = Forum.objects.private_threads()
  40. add_acl(request.user, forum)
  41. return forum
  42. def check_forum_permissions(self, request, forum):
  43. add_acl(request.user, forum)
  44. allow_use_private_threads(request.user)
  45. def fetch_thread(self, request, lock=False, select_related=None,
  46. queryset=None, **kwargs):
  47. queryset = queryset or Thread.objects
  48. if lock:
  49. queryset = queryset.select_for_update()
  50. select_related = select_related or []
  51. if not 'forum' in select_related:
  52. select_related.append('forum')
  53. queryset = queryset.select_related(*select_related)
  54. where = {'id': kwargs.get('thread_id')}
  55. thread = get_object_or_404(queryset, **where)
  56. if thread.forum.special_role != 'private_threads':
  57. raise Http404()
  58. return thread
  59. def check_thread_permissions(self, request, thread):
  60. add_acl(request.user, thread.forum)
  61. add_acl(request.user, thread)
  62. participants.make_thread_participants_aware(request.user, thread)
  63. allow_see_private_thread(request.user, thread)
  64. allow_use_private_threads(request.user)
  65. def check_post_permissions(self, request, post):
  66. add_acl(request.user, post.forum)
  67. add_acl(request.user, post.thread)
  68. add_acl(request.user, post)
  69. participants.make_thread_participants_aware(request.user, thread)
  70. allow_see_private_post(request.user, post)
  71. allow_see_private_thread(request.user, post.thread)
  72. allow_use_private_threads(request.user)
  73. def exclude_invisible_posts(self, queryset, user, forum, thread):
  74. return queryset
  75. class PrivateThreads(generic.Threads):
  76. fetch_pinned_threads = False
  77. def get_queryset(self):
  78. threads_qs = Forum.objects.private_threads().thread_set
  79. return exclude_invisible_private_threads(threads_qs, self.user)
  80. class PrivateThreadsFiltering(generic.ThreadsFiltering):
  81. def get_available_filters(self):
  82. filters = super(PrivateThreadsFiltering, self).get_available_filters()
  83. if self.user.acl['can_moderate_private_threads']:
  84. filters.append({
  85. 'type': 'reported',
  86. 'name': _("With reported posts"),
  87. 'is_label': False,
  88. })
  89. return filters
  90. @private_threads_view
  91. class PrivateThreadsView(generic.ThreadsView):
  92. link_name = 'misago:private_threads'
  93. template = 'misago/privatethreads/list.html'
  94. Threads = PrivateThreads
  95. Filtering = PrivateThreadsFiltering
  96. class PrivateThreadActions(generic.ThreadActions):
  97. def get_available_actions(self, kwargs):
  98. user = kwargs['user']
  99. thread = kwargs['thread']
  100. is_moderator = user.acl['can_moderate_private_threads']
  101. if thread.participant and thread.participant.is_owner:
  102. is_owner = True
  103. else:
  104. is_owner = False
  105. actions = []
  106. if is_moderator and not is_owner:
  107. actions.append({
  108. 'action': 'takeover',
  109. 'icon': 'level-up',
  110. 'name': _("Take thread over")
  111. })
  112. if is_owner:
  113. actions.append({
  114. 'action': 'participants',
  115. 'icon': 'users',
  116. 'name': _("Edit participants"),
  117. 'is_button': True
  118. })
  119. for participant in thread.participants_list:
  120. if not participant.is_owner:
  121. actions.append({
  122. 'action': 'make_owner:%s' % participant.user_id,
  123. 'is_hidden': True
  124. })
  125. if is_moderator:
  126. if thread.is_closed:
  127. actions.append({
  128. 'action': 'open',
  129. 'icon': 'unlock-alt',
  130. 'name': _("Open thread")
  131. })
  132. else:
  133. actions.append({
  134. 'action': 'close',
  135. 'icon': 'lock',
  136. 'name': _("Close thread")
  137. })
  138. actions.append({
  139. 'action': 'delete',
  140. 'icon': 'times',
  141. 'name': _("Delete thread"),
  142. 'confirmation': _("Are you sure you want to delete this "
  143. "thread? This action can't be undone.")
  144. })
  145. return actions
  146. @atomic
  147. def action_takeover(self, request, thread):
  148. participants.set_thread_owner(thread, request.user)
  149. messages.success(request, _("You are now owner of this thread."))
  150. message = _("%(user)s took over this thread.")
  151. record_event(request.user, thread, 'user', message, {
  152. 'user': request.user,
  153. })
  154. thread.save(update_fields=['has_events'])
  155. @atomic
  156. def action_make_owner(self, request, thread, new_owner_id):
  157. new_owner_id = int(new_owner_id)
  158. new_owner = None
  159. for participant in thread.participants_list:
  160. if participant.user.id == int(new_owner_id):
  161. new_owner = participant.user
  162. break
  163. if new_owner:
  164. participants.set_thread_owner(thread, new_owner)
  165. message = _("You have passed thread ownership to %(user)s.")
  166. messages.success(request, message % {'user': new_owner.username})
  167. message = _("%(user)s passed thread ownership to %(participant)s.")
  168. record_event(request.user, thread, 'user', message, {
  169. 'user': request.user,
  170. 'participant': new_owner
  171. })
  172. thread.save(update_fields=['has_events'])
  173. @uiview("private_threads")
  174. @deny_guests
  175. def event_sender(request, resolver_match):
  176. if request.user.unread_private_threads:
  177. message = ungettext("%(threads)s unread private thread",
  178. "%(threads)s unread private threads",
  179. request.user.unread_private_threads)
  180. message = message % {'threads': request.user.unread_private_threads}
  181. else:
  182. message = _("Private threads")
  183. return {
  184. 'count': request.user.unread_private_threads,
  185. 'message': message,
  186. }
  187. return request.user.unread_private_threads
  188. @private_threads_view
  189. class ThreadView(PrivateThreadsMixin, generic.ThreadView):
  190. template = 'misago/privatethreads/thread.html'
  191. ThreadActions = PrivateThreadActions
  192. @private_threads_view
  193. class ThreadParticipantsView(PrivateThreadsMixin, generic.ViewBase):
  194. template = 'misago/privatethreads/participants.html'
  195. def dispatch(self, request, *args, **kwargs):
  196. if not request.is_ajax():
  197. return not_allowed(request)
  198. thread = self.get_thread(request, **kwargs)
  199. participants_qs = thread.threadparticipant_set
  200. participants_qs = participants_qs.select_related('user', 'user__rank')
  201. return self.render(request, {
  202. 'forum': thread.forum,
  203. 'thread': thread,
  204. 'participants': participants_qs.order_by('-is_owner', 'user__slug')
  205. })
  206. @private_threads_view
  207. class EditThreadParticipantsView(ThreadParticipantsView):
  208. template = 'misago/privatethreads/participants_modal.html'
  209. @private_threads_view
  210. class BaseEditThreadParticipantView(PrivateThreadsMixin, generic.ViewBase):
  211. @atomic
  212. def dispatch(self, request, *args, **kwargs):
  213. if not request.is_ajax():
  214. return not_allowed(request)
  215. if not request.method == "POST":
  216. raise AjaxError(_("Wrong action received."))
  217. thread = self.get_thread(request, lock=True, **kwargs)
  218. if not thread.participant or not thread.participant.is_owner:
  219. raise AjaxError(_("Only thread owner can add or "
  220. "remove participants from thread."))
  221. return self.action(request, thread, kwargs)
  222. def action(self, request, thread, kwargs):
  223. raise NotImplementedError("views extending EditThreadParticipantView "
  224. "need to define custom action method")
  225. @private_threads_view
  226. class AddThreadParticipantsView(BaseEditThreadParticipantView):
  227. template = 'misago/privatethreads/participants_modal_list.html'
  228. def action(self, request, thread, kwargs):
  229. form = ThreadParticipantsForm(request.POST, user=request.user)
  230. if not form.is_valid():
  231. errors = []
  232. for field_errors in form.errors.as_data().values():
  233. errors.extend([unicode(e[0]) for e in field_errors])
  234. return JsonResponse({'message': errors[0], 'is_error': True})
  235. event_message = _("%(user)s added %(participant)s to this thread.")
  236. participants_list = [p.user for p in thread.participants_list]
  237. for user in form.users_cache:
  238. if user not in participants_list:
  239. participants.add_participant(request, thread, user)
  240. record_event(request.user, thread, 'user', event_message, {
  241. 'user': request.user,
  242. 'participant': user
  243. })
  244. thread.save(update_fields=['has_events'])
  245. participants_qs = thread.threadparticipant_set
  246. participants_qs = participants_qs.select_related('user', 'user__rank')
  247. participants_qs = participants_qs.order_by('-is_owner', 'user__slug')
  248. participants_list = [p for p in participants_qs]
  249. participants_list_html = self.render(request, {
  250. 'forum': thread.forum,
  251. 'thread': thread,
  252. 'participants': participants_list,
  253. }).content
  254. message = ungettext("%(users)s participant",
  255. "%(users)s participants",
  256. len(participants_list))
  257. message = message % {'users': len(participants_list)}
  258. return JsonResponse({
  259. 'is_error': False,
  260. 'message': message,
  261. 'list_html': participants_list_html
  262. })
  263. @private_threads_view
  264. class RemoveThreadParticipantView(BaseEditThreadParticipantView):
  265. def action(self, request, thread, kwargs):
  266. user_qs = thread.threadparticipant_set.select_related('user')
  267. try:
  268. participant = user_qs.get(user_id=kwargs['user_id'])
  269. except ThreadParticipant.DoesNotExist:
  270. return JsonResponse({
  271. 'message': _("Requested participant couldn't be found."),
  272. 'is_error': True,
  273. })
  274. if participant.user == request.user:
  275. return JsonResponse({
  276. 'message': _('To leave thread use "Leave thread" option.'),
  277. 'is_error': True,
  278. })
  279. participants_count = len(thread.participants_list) - 1
  280. if participants_count == 0:
  281. return JsonResponse({
  282. 'message': _("You can't remove last thread participant."),
  283. 'is_error': True,
  284. })
  285. participants.remove_participant(thread, participant.user)
  286. if not participants.thread_has_participants(thread):
  287. thread.delete()
  288. else:
  289. message = _("%(user)s removed %(participant)s from this thread.")
  290. record_event(request.user, thread, 'user', message, {
  291. 'user': request.user,
  292. 'participant': participant.user
  293. })
  294. thread.save(update_fields=['has_events'])
  295. participants_count = len(thread.participants_list) - 1
  296. message = ungettext("%(users)s participant",
  297. "%(users)s participants",
  298. participants_count)
  299. message = message % {'users': participants_count}
  300. return JsonResponse({'is_error': False, 'message': message})
  301. @private_threads_view
  302. class LeaveThreadView(BaseEditThreadParticipantView):
  303. @atomic
  304. def dispatch(self, request, *args, **kwargs):
  305. thread = self.get_thread(request, lock=True, **kwargs)
  306. try:
  307. if not request.method == "POST":
  308. raise RuntimeError(_("Wrong action received."))
  309. if not thread.participant:
  310. raise RuntimeError(_("You have to be thread participant in "
  311. "order to be able to leave thread."))
  312. user_qs = thread.threadparticipant_set.select_related('user')
  313. try:
  314. participant = user_qs.get(user_id=request.user.id)
  315. except ThreadParticipant.DoesNotExist:
  316. raise RuntimeError(_("You need to be thread "
  317. "participant to leave it."))
  318. except RuntimeError as e:
  319. messages.error(request, unicode(e))
  320. return redirect(thread.get_absolute_url())
  321. participants.remove_participant(thread, request.user)
  322. if not thread.threadparticipant_set.exists():
  323. thread.delete()
  324. elif thread.participant.is_owner:
  325. new_owner = user_qs.order_by('id')[:1][0].user
  326. participants.set_thread_owner(thread, new_owner)
  327. message = _("%(user)s left this thread. "
  328. "%(new_owner)s is now thread owner.")
  329. record_event(request.user, thread, 'user', message, {
  330. 'user': request.user,
  331. 'new_owner': new_owner
  332. })
  333. thread.save(update_fields=['has_events'])
  334. else:
  335. message = _("%(user)s left this thread.")
  336. record_event(request.user, thread, 'user', message, {
  337. 'user': request.user,
  338. })
  339. thread.save(update_fields=['has_events'])
  340. message = _('You have left "%(thread)s" thread.')
  341. message = message % {'thread': thread.title}
  342. messages.info(request, message)
  343. return redirect('misago:private_threads')
  344. @private_threads_view
  345. class PostingView(PrivateThreadsMixin, generic.PostingView):
  346. def allow_reply(self, user, thread):
  347. super(PostingView, self).allow_reply(user, thread)
  348. if user.acl['can_moderate_private_threads']:
  349. can_reply = not thread.participant
  350. else:
  351. can_reply = len(thread.participants_list) > 1
  352. if not can_reply:
  353. message = _("You have to add new participants to thread "
  354. "before you will be able to reply to it.")
  355. raise PermissionDenied(message)
  356. """
  357. Generics
  358. """
  359. @private_threads_view
  360. class GotoLastView(PrivateThreadsMixin, generic.GotoLastView):
  361. pass
  362. @private_threads_view
  363. class GotoNewView(PrivateThreadsMixin, generic.GotoNewView):
  364. pass
  365. @private_threads_view
  366. class GotoPostView(PrivateThreadsMixin, generic.GotoPostView):
  367. pass
  368. @private_threads_view
  369. class ReportedPostsListView(PrivateThreadsMixin, generic.ReportedPostsListView):
  370. pass
  371. @private_threads_view
  372. class QuotePostView(PrivateThreadsMixin, generic.QuotePostView):
  373. pass
  374. @private_threads_view
  375. class UnhidePostView(PrivateThreadsMixin, generic.UnhidePostView):
  376. pass
  377. @private_threads_view
  378. class HidePostView(PrivateThreadsMixin, generic.HidePostView):
  379. pass
  380. @private_threads_view
  381. class DeletePostView(PrivateThreadsMixin, generic.DeletePostView):
  382. pass
  383. @private_threads_view
  384. class ReportPostView(generic.ReportPostView):
  385. pass
  386. @private_threads_view
  387. class EventsView(PrivateThreadsMixin, generic.EventsView):
  388. pass