threadslist.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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.shortcuts import render
  7. from django.views.generic import View
  8. from django.utils import timezone
  9. from django.utils.translation import ugettext as _, ugettext_lazy
  10. from misago.categories.models import CATEGORIES_TREE_ID, Category
  11. from misago.categories.permissions import (
  12. allow_see_category, allow_browse_category)
  13. from misago.core.shortcuts import (
  14. get_object_or_404, paginate, pagination_dict, validate_slug)
  15. from misago.readtracker import threadstracker
  16. from misago.threads.models import Thread
  17. from misago.threads.permissions import exclude_invisible_threads
  18. from misago.threads.utils import add_categories_to_threads
  19. LISTS_NAMES = {
  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. }
  25. def filter_threads_queryset(user, categories, list_type, queryset):
  26. if list_type == 'my':
  27. return queryset.filter(starter=user)
  28. elif list_type == 'subscribed':
  29. return queryset # TODO: filter(id__in=[subscribed threads])
  30. else:
  31. # grab cutoffs for categories
  32. cutoff_date = timezone.now() - timedelta(
  33. days=settings.MISAGO_FRESH_CONTENT_PERIOD
  34. )
  35. if cutoff_date < user.reads_cutoff:
  36. cutoff_date = user.reads_cutoff
  37. categories_dict = {}
  38. for record in user.categoryread_set.filter(category__in=categories):
  39. if record.last_read_on > cutoff_date:
  40. categories_dict[record.category_id] = record.last_read_on
  41. if list_type == 'new':
  42. # new threads have no entry in reads table
  43. # AND were started after cutoff date
  44. read_threads = user.threadread_set.filter(
  45. category__in=categories
  46. ).values('thread_id')
  47. condition = Q(last_post_on__lte=cutoff_date)
  48. condition = condition | Q(id__in=read_threads)
  49. if categories_dict:
  50. for category_id, category_cutoff in categories_dict.items():
  51. condition = condition | Q(
  52. category_id=category_id,
  53. last_post_on__lte=category_cutoff,
  54. )
  55. return queryset.exclude(condition)
  56. elif list_type == 'unread':
  57. # unread threads were read in past but have new posts
  58. # after cutoff date
  59. read_threads = user.threadread_set.filter(
  60. category__in=categories,
  61. thread__last_post_on__gt=cutoff_date,
  62. last_read_on__lt=F('thread__last_post_on')
  63. ).values('thread_id')
  64. queryset = queryset.filter(id__in=read_threads)
  65. # unread threads have last reply after read/cutoff date
  66. if categories_dict:
  67. conditions = None
  68. for category_id, category_cutoff in categories_dict.items():
  69. condition = Q(
  70. category_id=category_id,
  71. last_post_on__lte=category_cutoff,
  72. )
  73. if conditions:
  74. conditions = conditions | condition
  75. else:
  76. conditions = condition
  77. return queryset.exclude(conditions)
  78. else:
  79. return queryset
  80. def get_threads_queryset(user, categories, list_type):
  81. queryset = Thread.objects
  82. queryset = exclude_invisible_threads(user, categories, queryset)
  83. if list_type == 'all':
  84. return queryset
  85. else:
  86. return filter_threads_queryset(user, categories, list_type, queryset)
  87. class BaseList(View):
  88. template_name = 'misago/threadslist/threads.html'
  89. preloaded_data_prefix = ''
  90. def allow_see_list(self, request, category, list_type):
  91. if request.user.is_anonymous():
  92. if list_type == 'my':
  93. raise PermissionDenied( _("You have to sign in to see list of "
  94. "threads that you have started."))
  95. if list_type == 'new':
  96. raise PermissionDenied(_("You have to sign in to see list of "
  97. "threads you haven't read."))
  98. if list_type == 'unread':
  99. raise PermissionDenied(_("You have to sign in to see list of "
  100. "threads with new replies."))
  101. if list_type == 'subscribed':
  102. raise PermissionDenied(_("You have to sign in to see list of "
  103. "threads you are subscribing."))
  104. def get_subcategories(self, request, category):
  105. if category.is_leaf_node():
  106. return []
  107. visible_categories = request.user.acl['visible_categories']
  108. queryset = category.get_descendants().filter(id__in=visible_categories)
  109. return list(queryset.order_by('lft'))
  110. def get_extra_context(self, request, category, subcategories, list_type):
  111. return {}
  112. def get(self, request, **kwargs):
  113. try:
  114. page = int(request.GET.get('page', 0))
  115. if page == 1:
  116. page = None
  117. except ValueError:
  118. raise Http404()
  119. list_type = kwargs['list_type']
  120. category = self.get_category(request, **kwargs)
  121. self.allow_see_list(request, category, list_type)
  122. subcategories = self.get_subcategories(request, category)
  123. categories = [category] + subcategories
  124. queryset = self.get_queryset(
  125. request, categories, list_type).order_by('-last_post_on')
  126. page = paginate(queryset, page, 24, 6)
  127. paginator = pagination_dict(page)
  128. if list_type in ('new', 'unread'):
  129. """we already know all threads on list are unread"""
  130. threadstracker.make_unread(page.object_list)
  131. else:
  132. threadstracker.make_threads_read_aware(
  133. request.user, page.object_list)
  134. add_categories_to_threads(categories, page.object_list)
  135. visible_subcategories = []
  136. for thread in page.object_list:
  137. if (thread.top_category and
  138. thread.top_category not in visible_subcategories):
  139. visible_subcategories.append(thread.top_category.pk)
  140. category.subcategories = []
  141. for subcategory in subcategories:
  142. if subcategory.pk in visible_subcategories:
  143. category.subcategories.append(subcategory)
  144. extra_context = self.get_extra_context(
  145. request, category, subcategories, list_type)
  146. show_toolbar = False
  147. if paginator['count']:
  148. if category.subcategories:
  149. show_toolbar = True
  150. if request.user.is_authenticated():
  151. show_toolbar = True
  152. return render(request, self.template_name, dict(
  153. category=category,
  154. show_toolbar=show_toolbar,
  155. list_type=list_type,
  156. list_name=LISTS_NAMES.get(list_type),
  157. threads=page.object_list,
  158. paginator=paginator,
  159. count=paginator['count'],
  160. **extra_context
  161. ))
  162. class ThreadsList(BaseList):
  163. template_name = 'misago/threadslist/threads.html'
  164. def get_category(self, request, **kwargs):
  165. return Category.objects.root_category()
  166. def get_queryset(self, request, categories, list_type):
  167. # [:1] cos we are cutting off root caregory on forum threads list
  168. # as it includes nedless extra condition to DB filter
  169. return get_threads_queryset(request.user, categories[1:], list_type)
  170. def get_extra_context(self, request, category, subcategories, list_type):
  171. return {
  172. 'is_index': not settings.MISAGO_CATEGORIES_ON_INDEX
  173. }
  174. class CategoryThreadsList(ThreadsList):
  175. template_name = 'misago/threadslist/category.html'
  176. preloaded_data_prefix = 'CATEGORY_'
  177. def get_category(self, request, **kwargs):
  178. category = get_object_or_404(Category.objects.select_related('parent'),
  179. tree_id=CATEGORIES_TREE_ID,
  180. id=kwargs['category_id'],
  181. )
  182. allow_see_category(request.user, category)
  183. allow_browse_category(request.user, category)
  184. validate_slug(category, kwargs['category_slug'])
  185. return category
  186. def get_queryset(self, request, categories, list_type):
  187. return get_threads_queryset(request.user, categories, list_type)
  188. class PrivateThreadsList(ThreadsList):
  189. template_name = 'misago/threadslist/private_threads.html'
  190. preloaded_data_prefix = 'PRIVATE_'
  191. def get_category(self, request, **kwargs):
  192. return Category.objects.private_threads()
  193. def get_subcategories(self, request, category):
  194. return []