versioncheck.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import requests
  2. from ariadne import QueryType
  3. from django.core.cache import cache
  4. from django.utils.translation import gettext as _
  5. from requests.exceptions import RequestException
  6. from ... import __released__, __version__
  7. from .status import Status
  8. CACHE_KEY = "misago_admin_version_check"
  9. CACHE_LENGTH = 3600 * 8 # 4 hours
  10. version_check = QueryType()
  11. @version_check.field("version")
  12. def resolve_version(*_):
  13. if not __released__:
  14. return get_unreleased_error()
  15. data = cache.get(CACHE_KEY)
  16. if not data:
  17. data = check_version_with_api()
  18. if data["status"] != Status.WARNING:
  19. cache.set(CACHE_KEY, data, CACHE_LENGTH)
  20. return data
  21. def get_unreleased_error():
  22. return {
  23. "status": Status.ERROR,
  24. "message": _("The site is running using unreleased version of Misago."),
  25. "description": _(
  26. "Unreleased versions of Misago can lack security features and there is "
  27. "no supported way to upgrade them to release versions later."
  28. ),
  29. }
  30. def check_version_with_api():
  31. try:
  32. latest_version = get_latest_version()
  33. return compare_versions(__version__, latest_version)
  34. except (RequestException, KeyError, ValueError):
  35. return {
  36. "status": Status.WARNING,
  37. "message": _("Failed to connect to pypi.org API. Try again later."),
  38. "description": _(
  39. "Version check feature relies on the API operated by the Python "
  40. "Package Index (pypi.org) API to retrieve latest Misago release "
  41. "version."
  42. ),
  43. }
  44. def get_latest_version():
  45. api_url = "https://pypi.org/pypi/Misago/json"
  46. r = requests.get(api_url)
  47. r.raise_for_status()
  48. return r.json()["info"]["version"]
  49. def compare_versions(current, latest):
  50. if latest == current:
  51. return {
  52. "status": Status.SUCCESS,
  53. "message": _("The site is running updated version of Misago."),
  54. "description": _("Misago %(version)s is latest release.")
  55. % {"version": current},
  56. }
  57. return {
  58. "status": Status.ERROR,
  59. "message": _("The site is running outdated version of Misago."),
  60. "description": _(
  61. "The site is running Misago version %(version)s while version %(latest)s "
  62. "is available."
  63. )
  64. % {"version": current, "latest": latest},
  65. }