utils.py 2.9 KB

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