utils.py 2.8 KB

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