utils.py 2.6 KB

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