utils.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. from urllib.parse import urlparse
  2. from django.urls import Resolver404, resolve
  3. from .models import PostLike
  4. def add_categories_to_items(root_category, categories, items):
  5. categories_dict = {}
  6. for category in categories:
  7. categories_dict[category.pk] = category
  8. if category.parent_id:
  9. category.parent = categories_dict[category.parent_id]
  10. for item in items:
  11. item.category = categories_dict[item.category_id]
  12. def add_likes_to_posts(user, posts):
  13. if user.is_anonymous:
  14. return
  15. posts_map = {}
  16. for post in posts:
  17. posts_map[post.id] = post
  18. post.is_liked = False
  19. queryset = PostLike.objects.filter(liker=user, post_id__in=posts_map.keys())
  20. for like in queryset.values("post_id"):
  21. posts_map[like["post_id"]].is_liked = True
  22. SUPPORTED_THREAD_ROUTES = {
  23. "misago:thread": "pk",
  24. "misago:thread-post": "pk",
  25. "misago:thread-last": "pk",
  26. "misago:thread-new": "pk",
  27. "misago:thread-unapproved": "pk",
  28. }
  29. def get_thread_id_from_url(request, url): # pylint: disable=too-many-return-statements
  30. clean_url = str(url).strip()
  31. url_bits = urlparse(clean_url)
  32. if url_bits.netloc and url_bits.netloc != request.get_host():
  33. return None
  34. if url_bits.path.startswith(request.get_host()):
  35. clean_path = url_bits.path.lstrip(request.get_host())
  36. else:
  37. clean_path = url_bits.path
  38. wsgi_alias = request.path[: len(request.path_info) * -1]
  39. if wsgi_alias and not clean_path.startswith(wsgi_alias):
  40. return None
  41. try:
  42. resolution = resolve(clean_path[len(wsgi_alias) :])
  43. except Resolver404:
  44. return None
  45. if not resolution.namespaces:
  46. return None
  47. url_name = "%s:%s" % (":".join(resolution.namespaces), resolution.url_name)
  48. kwargname = SUPPORTED_THREAD_ROUTES.get(url_name)
  49. if not kwargname:
  50. return None
  51. try:
  52. return int(resolution.kwargs.get(kwargname))
  53. except (TypeError, ValueError):
  54. return None