utils.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. from django.core.urlresolvers import resolve
  2. from django.utils import six
  3. from django.utils.six.moves.urllib.parse import urlparse
  4. def add_categories_to_threads(root_category, categories, threads):
  5. categories_dict = {}
  6. for category in categories:
  7. categories_dict[category.pk] = category
  8. top_categories_map = {}
  9. for thread in threads:
  10. thread.top_category = None
  11. thread.category = categories_dict[thread.category_id]
  12. if thread.category == root_category:
  13. continue
  14. elif thread.category.parent_id == root_category.pk:
  15. thread.top_category = thread.category
  16. elif thread.category_id in top_categories_map:
  17. thread.top_category = top_categories_map[thread.category_id]
  18. elif root_category.has_child(thread.category):
  19. # thread in subcategory resolution
  20. for category in categories:
  21. if (category.parent_id == root_category.pk and
  22. category.has_child(thread.category)):
  23. top_categories_map[thread.category_id] = category
  24. thread.top_category = category
  25. else:
  26. # global thread in other category resolution
  27. for category in categories:
  28. if category.level == 1 and (
  29. category == thread.category or
  30. category.has_child(thread.category)):
  31. top_categories_map[thread.category_id] = category
  32. thread.top_category = category
  33. SUPPORTED_THREAD_ROUTES = {
  34. 'misago:thread': 'pk',
  35. 'misago:thread-post': 'pk',
  36. 'misago:thread-last': 'pk',
  37. 'misago:thread-new': 'pk',
  38. 'misago:thread-unapproved': 'pk',
  39. }
  40. def get_thread_id_from_url(request, url):
  41. try:
  42. clean_url = six.text_type(url).strip()
  43. bits = urlparse(clean_url)
  44. except:
  45. return None
  46. if bits.netloc and bits.netloc != request.get_host():
  47. return None
  48. if bits.path.startswith(request.get_host()):
  49. clean_path = bits.path.lstrip(request.get_host())
  50. else:
  51. clean_path = bits.path
  52. try:
  53. wsgi_alias = request.path[:len(request.path_info) * -1]
  54. resolution = resolve(clean_path[len(wsgi_alias):])
  55. except:
  56. return None
  57. if not resolution.namespaces:
  58. return None
  59. url_name = '{}:{}'.format(':'.join(resolution.namespaces), resolution.url_name)
  60. kwargname = SUPPORTED_THREAD_ROUTES.get(url_name)
  61. if not kwargname:
  62. return None
  63. try:
  64. return int(resolution.kwargs.get(kwargname))
  65. except (TypeError, ValueError):
  66. return None