utils.py 2.9 KB

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