threads.py 9.5 KB

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