threads.py 9.5 KB

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