utils.py 1.9 KB

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