utils.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. from misago.acl import add_acl
  2. from misago.core import threadstore
  3. from misago.readtracker import categoriestracker
  4. from .models import Category
  5. __all__ = [
  6. 'get_categories_tree',
  7. 'get_category_path',
  8. 'get_category_next_parent'
  9. ]
  10. def get_categories_tree(user, parent=None):
  11. if not user.acl['visible_categories']:
  12. return []
  13. if parent:
  14. queryset = parent.get_descendants().order_by('lft')
  15. else:
  16. queryset = Category.objects.all_categories()
  17. queryset_with_acl = queryset.filter(id__in=user.acl['visible_categories'])
  18. visible_categories = list(queryset_with_acl)
  19. categories_dict = {}
  20. categories_list = []
  21. parent_level = parent.level + 1 if parent else 1
  22. for category in visible_categories:
  23. category.subcategories = []
  24. categories_dict[category.pk] = category
  25. categories_list.append(category)
  26. if category.parent_id and category.level > parent_level:
  27. categories_dict[category.parent_id].subcategories.append(category)
  28. add_acl(user, categories_list)
  29. categoriestracker.make_read_aware(user, categories_list)
  30. for category in reversed(visible_categories):
  31. if category.acl['can_browse']:
  32. category.parent = categories_dict.get(category.parent_id)
  33. if category.parent:
  34. category.parent.threads += category.threads
  35. category.parent.posts += category.posts
  36. if category.parent.last_post_on and category.last_post_on:
  37. parent_last_post = category.parent.last_post_on
  38. category_last_post = category.last_post_on
  39. update_last_thead = parent_last_post < category_last_post
  40. elif not category.parent.last_post_on and category.last_post_on:
  41. update_last_thead = True
  42. else:
  43. update_last_thead = False
  44. if update_last_thead:
  45. category.parent.last_post_on = category.last_post_on
  46. category.parent.last_thread_id = category.last_thread_id
  47. category.parent.last_thread_title = category.last_thread_title
  48. category.parent.last_thread_slug = category.last_thread_slug
  49. category.parent.last_poster_name = category.last_poster_name
  50. category.parent.last_poster_slug = category.last_poster_slug
  51. if not category.is_read:
  52. category.parent.is_read = False
  53. flat_list = []
  54. for category in categories_list:
  55. if category.level == parent_level:
  56. flat_list.append(category)
  57. return flat_list
  58. def get_category_path(category):
  59. if category.special_role:
  60. return [category]
  61. categories_dict = Category.objects.get_cached_categories_dict()
  62. category_path = []
  63. while category and category.level > 0:
  64. category_path.append(category)
  65. category = category.parent
  66. return [f for f in reversed(category_path)]