utils.py 2.9 KB

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