index.py 2.6 KB

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