index.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import requests
  2. from django.contrib.auth import get_user_model
  3. from django.core.cache import cache
  4. from django.http import Http404, JsonResponse
  5. from django.utils.translation import gettext as _
  6. from requests.exceptions import RequestException
  7. from . import render
  8. from ... import __version__
  9. from ...conf import settings
  10. from ...threads.models import Post, Thread
  11. VERSION_CHECK_CACHE_KEY = "misago_version_check"
  12. User = get_user_model()
  13. def admin_index(request):
  14. inactive_users_queryset = User.objects.exclude(
  15. requires_activation=User.ACTIVATION_NONE
  16. )
  17. db_stats = {
  18. "threads": Thread.objects.count(),
  19. "posts": Post.objects.count(),
  20. "users": User.objects.count(),
  21. "inactive_users": inactive_users_queryset.count(),
  22. }
  23. return render(
  24. request,
  25. "misago/admin/index.html",
  26. {
  27. "db_stats": db_stats,
  28. "address_check": check_misago_address(request),
  29. "version_check": cache.get(VERSION_CHECK_CACHE_KEY),
  30. },
  31. )
  32. def check_misago_address(request):
  33. set_address = settings.MISAGO_ADDRESS
  34. correct_address = request.build_absolute_uri("/")
  35. return {
  36. "is_correct": set_address == correct_address,
  37. "set_address": set_address,
  38. "correct_address": correct_address,
  39. }
  40. def check_version(request):
  41. if request.method != "POST":
  42. raise Http404()
  43. version = cache.get(VERSION_CHECK_CACHE_KEY, "nada")
  44. if version == "nada":
  45. try:
  46. api_url = "https://pypi.org/pypi/Misago/json"
  47. r = requests.get(api_url)
  48. r.raise_for_status()
  49. latest_version = r.json()["info"]["version"]
  50. if latest_version == __version__:
  51. version = {
  52. "is_error": False,
  53. "message": _("Up to date! (%(current)s)")
  54. % {"current": __version__},
  55. }
  56. else:
  57. version = {
  58. "is_error": True,
  59. "message": _("Outdated: %(current)s! (latest: %(latest)s)")
  60. % {"latest": latest_version, "current": __version__},
  61. }
  62. cache.set(VERSION_CHECK_CACHE_KEY, version, 180)
  63. except (RequestException, IndexError, KeyError, ValueError):
  64. version = {
  65. "is_error": True,
  66. "message": _("Failed to connect to pypi.org API. Try again later."),
  67. }
  68. return JsonResponse(version)