threads.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. from datetime import timedelta
  2. from django.conf import settings
  3. from django.core.exceptions import PermissionDenied
  4. from django.db.models import F, Q
  5. from django.http import Http404
  6. from django.utils import timezone
  7. from django.utils.translation import ugettext as _
  8. from django.utils.translation import ugettext_lazy
  9. from misago.acl import add_acl
  10. from misago.core.shortcuts import paginate, pagination_dict
  11. from misago.readtracker import threadstracker
  12. from ..models import Thread
  13. from ..permissions import exclude_invisible_threads
  14. from ..serializers import ThreadsListSerializer
  15. from ..subscriptions import make_subscription_aware
  16. from ..utils import add_categories_to_items
  17. __all__ = ['ForumThreads', 'PrivateThreads']
  18. LISTS_NAMES = {
  19. 'all': None,
  20. 'my': ugettext_lazy("Your threads"),
  21. 'new': ugettext_lazy("New threads"),
  22. 'unread': ugettext_lazy("Unread threads"),
  23. 'subscribed': ugettext_lazy("Subscribed threads"),
  24. 'unapproved': ugettext_lazy("Unapproved content"),
  25. }
  26. LIST_DENIED_MESSAGES = {
  27. 'my': ugettext_lazy("You have to sign in to see list of threads that you have started."),
  28. 'new': ugettext_lazy("You have to sign in to see list of threads you haven't read."),
  29. 'unread': ugettext_lazy("You have to sign in to see list of threads with new replies."),
  30. 'subscribed': ugettext_lazy("You have to sign in to see list of threads you are subscribing."),
  31. 'unapproved': ugettext_lazy("You have to sign in to see list of threads with unapproved posts."),
  32. }
  33. class ViewModel(object):
  34. def __init__(self, request, category, list_type, page):
  35. self.allow_see_list(request, category, list_type)
  36. category_model = category.unwrap()
  37. base_queryset = self.get_base_queryset(request, category.categories, list_type)
  38. threads_categories = [category_model] + category.subcategories
  39. threads_queryset = self.get_remaining_threads_queryset(base_queryset, category_model, threads_categories)
  40. list_page = paginate(threads_queryset, page, settings.MISAGO_THREADS_PER_PAGE, settings.MISAGO_THREADS_TAIL)
  41. paginator = pagination_dict(list_page, include_page_range=False)
  42. if list_page.number > 1:
  43. threads = list(list_page.object_list)
  44. else:
  45. pinned_threads = list(self.get_pinned_threads(base_queryset, category_model, threads_categories))
  46. threads = list(pinned_threads) + list(list_page.object_list)
  47. if list_type in ('new', 'unread'):
  48. # we already know all threads on list are unread
  49. threadstracker.make_unread(threads)
  50. else:
  51. threadstracker.make_threads_read_aware(request.user, threads)
  52. add_categories_to_items(category_model, category.categories, threads)
  53. add_acl(request.user, threads)
  54. make_subscription_aware(request.user, threads)
  55. # set state on object for easy access from hooks
  56. self.category = category
  57. self.threads = threads
  58. self.list_type = list_type
  59. self.paginator = paginator
  60. def allow_see_list(self, request, category, list_type):
  61. if list_type not in LISTS_NAMES:
  62. raise Http404()
  63. if request.user.is_anonymous():
  64. if list_type in LIST_DENIED_MESSAGES:
  65. raise PermissionDenied(LIST_DENIED_MESSAGES[list_type])
  66. else:
  67. if list_type == 'unapproved' and not request.user.acl['can_see_unapproved_content_lists']:
  68. raise PermissionDenied(_("You don't have permission to see unapproved content lists."))
  69. def get_list_name(self, list_type):
  70. return LISTS_NAMES[list_type]
  71. def get_base_queryset(self, request, threads_categories, list_type):
  72. return get_threads_queryset(request.user, threads_categories, list_type).order_by('-last_post_id')
  73. def get_pinned_threads(self, queryset, category, threads_categories):
  74. return []
  75. def get_remaining_threads_queryset(self, queryset, category, threads_categories):
  76. return []
  77. def get_frontend_context(self):
  78. context = {
  79. 'THREADS': {
  80. 'results': ThreadsListSerializer(self.threads, many=True).data,
  81. 'subcategories': [c.pk for c in self.category.children]
  82. },
  83. }
  84. context['THREADS'].update(self.paginator)
  85. return context
  86. def get_template_context(self):
  87. return {
  88. 'list_name': self.get_list_name(self.list_type),
  89. 'list_type': self.list_type,
  90. 'threads': self.threads,
  91. 'paginator': self.paginator
  92. }
  93. class ForumThreads(ViewModel):
  94. def get_pinned_threads(self, queryset, category, threads_categories):
  95. if category.level:
  96. return list(queryset.filter(weight=2)) + list(queryset.filter(
  97. weight=1,
  98. category__in=threads_categories
  99. ))
  100. else:
  101. return queryset.filter(weight=2)
  102. def get_remaining_threads_queryset(self, queryset, category, threads_categories):
  103. if category.level:
  104. return queryset.filter(
  105. weight=0,
  106. category__in=threads_categories,
  107. )
  108. else:
  109. return queryset.filter(
  110. weight__lt=2,
  111. category__in=threads_categories,
  112. )
  113. class PrivateThreads(ViewModel):
  114. def get_remaining_threads_queryset(self, queryset, category, threads_categories):
  115. return queryset.filter(category__in=threads_categories)
  116. """
  117. Thread queryset utils
  118. """
  119. def get_threads_queryset(user, categories, list_type):
  120. queryset = exclude_invisible_threads(user, categories, Thread.objects)
  121. if list_type == 'all':
  122. return queryset
  123. else:
  124. return filter_threads_queryset(user, categories, list_type, queryset)
  125. def filter_threads_queryset(user, categories, list_type, queryset):
  126. if list_type == 'my':
  127. return queryset.filter(starter=user)
  128. elif list_type == 'subscribed':
  129. subscribed_threads = user.subscription_set.values('thread_id')
  130. return queryset.filter(id__in=subscribed_threads)
  131. elif list_type == 'unapproved':
  132. return queryset.filter(has_unapproved_posts=True)
  133. elif list_type in ('new', 'unread'):
  134. return filter_read_threads_queryset(user, categories, list_type, queryset)
  135. else:
  136. return queryset
  137. def filter_read_threads_queryset(user, categories, list_type, queryset):
  138. # grab cutoffs for categories
  139. cutoff_date = timezone.now() - timedelta(days=settings.MISAGO_READTRACKER_CUTOFF)
  140. if cutoff_date < user.joined_on:
  141. cutoff_date = user.joined_on
  142. categories_dict = {}
  143. for record in user.categoryread_set.filter(category__in=categories):
  144. if record.last_read_on > cutoff_date:
  145. categories_dict[record.category_id] = record.last_read_on
  146. if list_type == 'new':
  147. # new threads have no entry in reads table
  148. # AND were started after cutoff date
  149. read_threads = user.threadread_set.filter(
  150. category__in=categories
  151. ).values('thread_id')
  152. condition = Q(last_post_on__lte=cutoff_date)
  153. condition = condition | Q(id__in=read_threads)
  154. if categories_dict:
  155. for category_id, category_cutoff in categories_dict.items():
  156. condition = condition | Q(
  157. category_id=category_id,
  158. last_post_on__lte=category_cutoff,
  159. )
  160. return queryset.exclude(condition)
  161. elif list_type == 'unread':
  162. # unread threads were read in past but have new posts
  163. # after cutoff date
  164. read_threads = user.threadread_set.filter(
  165. category__in=categories,
  166. thread__last_post_on__gt=cutoff_date,
  167. last_read_on__lt=F('thread__last_post_on')
  168. ).values('thread_id')
  169. queryset = queryset.filter(id__in=read_threads)
  170. # unread threads have last reply after read/cutoff date
  171. if categories_dict:
  172. conditions = None
  173. for category_id, category_cutoff in categories_dict.items():
  174. condition = Q(
  175. category_id=category_id,
  176. last_post_on__lte=category_cutoff,
  177. )
  178. if conditions:
  179. conditions = conditions | condition
  180. else:
  181. conditions = condition
  182. return queryset.exclude(conditions)
  183. else:
  184. return queryset