utils.py 3.0 KB

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