thread.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. from django.shortcuts import get_object_or_404
  2. from django.utils.translation import gettext as _
  3. from misago.acl import add_acl
  4. from misago.categories.models import Category
  5. from misago.core.shortcuts import validate_slug
  6. from misago.readtracker.threadstracker import make_read_aware
  7. from ..models import Thread
  8. from ..permissions.threads import allow_see_thread
  9. from ..serializers import ThreadSerializer
  10. from ..subscriptions import make_subscription_aware
  11. BASE_QUERYSET = Thread.objects.select_related(
  12. 'category', 'starter', 'starter__rank', 'starter__ban_cache', 'starter__online_tracker')
  13. class ViewModel(object):
  14. def __init__(self, request, pk, slug=None, read_aware=False, subscription_aware=False):
  15. thread = self.get_thread(request, pk, slug)
  16. thread.path = self.get_thread_path(thread.category)
  17. add_acl(request.user, thread.category)
  18. add_acl(request.user, thread)
  19. if read_aware:
  20. make_read_aware(request.user, thread)
  21. if subscription_aware:
  22. make_subscription_aware(request.user, thread)
  23. self.thread = thread
  24. self.category = thread.category
  25. self.path = thread.path
  26. def get_thread(self, request, pk, slug=None):
  27. raise NotImplementedError('Thread view model has to implement get_thread(request, pk, slug=None)')
  28. def get_thread_path(self, category):
  29. thread_path = []
  30. if category.level:
  31. categories = Category.objects.filter(
  32. tree_id=category.tree_id,
  33. lft__lte=category.lft,
  34. rght__gte=category.rght
  35. ).order_by('level')
  36. thread_path = list(categories)
  37. else:
  38. thread_path = [category]
  39. thread_path[0].name = self.get_root_name()
  40. return thread_path
  41. def get_root_name(self):
  42. raise NotImplementedError('Thread view model has to implement get_root_name()')
  43. def get_frontend_context(self):
  44. return ThreadSerializer(self.thread).data
  45. def get_template_context(self):
  46. return {
  47. 'thread': self.thread,
  48. 'category': self.category,
  49. 'breadcrumbs': self.path
  50. }
  51. class ForumThread(ViewModel):
  52. def get_thread(self, request, pk, slug=None):
  53. thread = get_object_or_404(
  54. BASE_QUERYSET,
  55. pk=pk,
  56. category__tree_id=Category.objects.root_category().tree_id,
  57. )
  58. allow_see_thread(request.user, thread)
  59. if slug:
  60. validate_slug(thread, slug)
  61. return thread
  62. def get_root_name(self):
  63. return _("Threads")