updateSquidStats.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import os
  2. import shutil
  3. import subprocess
  4. import tempfile
  5. import requests
  6. from dotenv import load_dotenv
  7. from loguru import logger
  8. load_dotenv()
  9. _DEB_INSTALL_PATHS = {"/opt/SquidStats/app", "/usr/share/squidstats"}
  10. def is_deb_installation() -> bool:
  11. """Return True when the app is running from a .deb-managed installation path."""
  12. install_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  13. return install_dir in _DEB_INSTALL_PATHS
  14. def updateSquidStats():
  15. logger.info("Starting SquidStats web update process")
  16. install_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  17. if is_deb_installation():
  18. logger.error(
  19. "Deb-based installation detected in %s. "
  20. "This installation cannot be updated with this script. "
  21. "Please use the .deb package to update: dpkg -i squidstats_<version>.deb",
  22. install_dir,
  23. )
  24. return False
  25. if not os.path.isdir(os.path.join(install_dir, ".git")):
  26. logger.error(
  27. "No git repository found in %s. Cannot perform automatic update.",
  28. install_dir,
  29. )
  30. return False
  31. try:
  32. proxy_url = os.getenv("HTTP_PROXY", "")
  33. https_proxy_url = os.getenv("HTTPS_PROXY", proxy_url)
  34. env = os.environ.copy()
  35. if proxy_url:
  36. logger.debug("HTTP proxy configured")
  37. env["http_proxy"] = proxy_url
  38. if https_proxy_url:
  39. logger.debug("HTTPS proxy configured")
  40. env["https_proxy"] = https_proxy_url
  41. proxies = None
  42. if proxy_url or https_proxy_url:
  43. proxies = {
  44. "http": proxy_url or None,
  45. "https": https_proxy_url or None,
  46. }
  47. try:
  48. # Fetch the latest release tag from GitHub API to always use the current version
  49. api_response = requests.get(
  50. "https://api.github.com/repos/kaelthasmanu/SquidStats/releases/latest",
  51. proxies=proxies,
  52. timeout=30,
  53. )
  54. api_response.raise_for_status()
  55. latest_tag = api_response.json().get("tag_name", "")
  56. if not latest_tag:
  57. logger.error("No se pudo obtener la última versión desde GitHub API")
  58. return False
  59. logger.info(f"Latest release tag resolved: {latest_tag}")
  60. script_url = f"https://github.com/kaelthasmanu/SquidStats/releases/download/{latest_tag}/install.sh"
  61. logger.info(f"Downloading update script from {script_url}")
  62. response = requests.get(
  63. script_url,
  64. proxies=proxies,
  65. timeout=30,
  66. )
  67. response.raise_for_status()
  68. sh_bin = "/bin/sh" if os.path.exists("/bin/sh") else shutil.which("sh")
  69. if not sh_bin:
  70. logger.error("sh no encontrado en el sistema")
  71. return False
  72. with tempfile.NamedTemporaryFile(delete=False, suffix=".sh") as tmp_script:
  73. tmp_script.write(response.content)
  74. tmp_script_path = tmp_script.name
  75. logger.debug(f"Written update script to temporary file: {tmp_script_path}")
  76. os.chmod(tmp_script_path, 0o700)
  77. args = [sh_bin, tmp_script_path, "--update"]
  78. logger.info(f"Executing update script with command: {args}")
  79. try:
  80. # The external update script is downloaded from the official GitHub
  81. # release feed, then written to a temporary file and executed.
  82. # This is intentionally executing remote installer content.
  83. subprocess.run(args, env=env, check=True, timeout=600) # noqa: S603
  84. logger.info("Update script executed successfully")
  85. finally:
  86. try:
  87. os.remove(tmp_script_path)
  88. except OSError:
  89. logger.warning(
  90. f"Unable to remove temporary update script: {tmp_script_path}"
  91. )
  92. return True
  93. except Exception:
  94. logger.exception("Error descargando el script de actualización")
  95. return False
  96. except Exception:
  97. logger.exception("Error crítico en updateSquidStats")
  98. return False