threads.py 9.2 KB

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