4
0

updateSquidStats.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. import os
  2. import re
  3. import shutil
  4. import subprocess
  5. import tempfile
  6. import time
  7. import requests
  8. from dotenv import load_dotenv
  9. from loguru import logger
  10. load_dotenv()
  11. _DEB_INSTALL_PATHS = {"/opt/SquidStats/app", "/usr/share/squidstats"}
  12. def is_deb_installation() -> bool:
  13. """Return True when the app is running from a .deb-managed installation path."""
  14. install_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  15. return install_dir in _DEB_INSTALL_PATHS
  16. def _get_git_binary():
  17. git_bin = shutil.which("git")
  18. if not git_bin:
  19. logger.error("git executable not found on PATH")
  20. return git_bin
  21. def _run_git_command(args, cwd, env, capture_output=True, timeout=120):
  22. git_bin = _get_git_binary()
  23. if not git_bin:
  24. return subprocess.CompletedProcess(
  25. ["git", *args], 1, "", "git executable not found"
  26. )
  27. return subprocess.run( # noqa: S603
  28. [git_bin, *args],
  29. cwd=cwd,
  30. env=env,
  31. stdout=subprocess.PIPE if capture_output else None,
  32. stderr=subprocess.PIPE if capture_output else None,
  33. text=True,
  34. timeout=timeout,
  35. )
  36. def _repo_has_head(install_dir, env):
  37. result = _run_git_command(["rev-parse", "--verify", "HEAD"], install_dir, env)
  38. return result.returncode == 0
  39. def _detect_remote_branch(install_dir, env):
  40. for branch in ("main", "master"):
  41. result = _run_git_command(
  42. ["ls-remote", "--heads", "origin", branch], install_dir, env
  43. )
  44. if result.returncode == 0 and result.stdout.strip():
  45. return branch
  46. return None
  47. def _prepare_deb_git_repo(install_dir, env):
  48. git_dir = os.path.join(install_dir, ".git")
  49. repo_initialized = False
  50. if not os.path.isdir(git_dir):
  51. logger.info(
  52. "Initializing git repository in deb-installed path: %s", install_dir
  53. )
  54. result = _run_git_command(["init"], install_dir, env)
  55. if result.returncode != 0:
  56. logger.error(
  57. "Failed to initialize git repository: %s", result.stderr.strip()
  58. )
  59. return False
  60. repo_initialized = True
  61. result = _run_git_command(["remote", "get-url", "origin"], install_dir, env)
  62. origin_url = result.stdout.strip() if result.returncode == 0 else None
  63. if origin_url != "https://github.com/kaelthasmanu/SquidStats.git":
  64. if origin_url:
  65. logger.info(
  66. "Updating git origin remote URL from %s to %s",
  67. origin_url,
  68. "https://github.com/kaelthasmanu/SquidStats.git",
  69. )
  70. result = _run_git_command(
  71. [
  72. "remote",
  73. "set-url",
  74. "origin",
  75. "https://github.com/kaelthasmanu/SquidStats.git",
  76. ],
  77. install_dir,
  78. env,
  79. )
  80. else:
  81. logger.info(
  82. "Adding git origin remote: %s",
  83. "https://github.com/kaelthasmanu/SquidStats.git",
  84. )
  85. result = _run_git_command(
  86. [
  87. "remote",
  88. "add",
  89. "origin",
  90. "https://github.com/kaelthasmanu/SquidStats.git",
  91. ],
  92. install_dir,
  93. env,
  94. )
  95. if result.returncode != 0:
  96. logger.error(
  97. "Failed to configure git origin remote: %s", result.stderr.strip()
  98. )
  99. return False
  100. result = _run_git_command(["fetch", "--tags", "origin"], install_dir, env)
  101. if result.returncode != 0:
  102. logger.error("Failed to fetch from origin: %s", result.stderr.strip())
  103. return False
  104. branch = _detect_remote_branch(install_dir, env)
  105. if not branch:
  106. logger.error("No supported remote branch found on origin")
  107. return False
  108. if repo_initialized or not _repo_has_head(install_dir, env):
  109. logger.info("Checking out branch %s from origin", branch)
  110. result = _run_git_command(
  111. ["checkout", "-B", branch, f"origin/{branch}"], install_dir, env
  112. )
  113. if result.returncode != 0:
  114. logger.error(
  115. "Failed to checkout branch %s from origin: %s",
  116. branch,
  117. result.stderr.strip(),
  118. )
  119. return False
  120. return True
  121. def _update_deb_installation(install_dir, env):
  122. if not _prepare_deb_git_repo(install_dir, env):
  123. return False
  124. branch = _detect_remote_branch(install_dir, env)
  125. if not branch:
  126. return False
  127. result = _run_git_command(["pull", "--ff-only", "origin", branch], install_dir, env)
  128. if result.returncode == 0:
  129. logger.info("Git pull succeeded on deb installation")
  130. return True
  131. status = _run_git_command(["status", "--porcelain"], install_dir, env)
  132. if status.returncode == 0 and status.stdout.strip():
  133. logger.error(
  134. "Git pull failed because the working tree has modified files:\n%s",
  135. status.stdout.strip(),
  136. )
  137. else:
  138. logger.error(
  139. "Git pull failed: %s",
  140. result.stderr.strip() or result.stdout.strip(),
  141. )
  142. return False
  143. def updateSquidStats():
  144. logger.info("Starting SquidStats web update process")
  145. install_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  146. env = os.environ.copy()
  147. proxy_url = os.getenv("HTTP_PROXY", "")
  148. https_proxy_url = os.getenv("HTTPS_PROXY", proxy_url)
  149. if proxy_url:
  150. logger.debug("HTTP proxy configured")
  151. env["http_proxy"] = proxy_url
  152. if https_proxy_url:
  153. logger.debug("HTTPS proxy configured")
  154. env["https_proxy"] = https_proxy_url
  155. if is_deb_installation():
  156. logger.info("Detected deb-installed SquidStats; updating via git pull")
  157. return _update_deb_installation(install_dir, env)
  158. if not os.path.isdir(os.path.join(install_dir, ".git")):
  159. logger.error(
  160. "No git repository found in %s. Cannot perform automatic update.",
  161. install_dir,
  162. )
  163. return False
  164. try:
  165. proxies = None
  166. if proxy_url or https_proxy_url:
  167. proxies = {
  168. "http": proxy_url or None,
  169. "https": https_proxy_url or None,
  170. }
  171. try:
  172. # Fetch the latest release tag from GitHub API to always use the current version
  173. api_response = requests.get(
  174. "https://api.github.com/repos/kaelthasmanu/SquidStats/releases/latest",
  175. proxies=proxies,
  176. timeout=30,
  177. )
  178. api_response.raise_for_status()
  179. latest_tag = api_response.json().get("tag_name", "")
  180. if not latest_tag:
  181. logger.error("No se pudo obtener la última versión desde GitHub API")
  182. return False
  183. logger.info(f"Latest release tag resolved: {latest_tag}")
  184. script_url = f"https://github.com/kaelthasmanu/SquidStats/releases/download/{latest_tag}/install.sh"
  185. logger.info(f"Downloading update script from {script_url}")
  186. response = requests.get(
  187. script_url,
  188. proxies=proxies,
  189. timeout=30,
  190. )
  191. response.raise_for_status()
  192. sh_bin = "/bin/sh" if os.path.exists("/bin/sh") else shutil.which("sh")
  193. if not sh_bin:
  194. logger.error("sh no encontrado en el sistema")
  195. return False
  196. with tempfile.NamedTemporaryFile(delete=False, suffix=".sh") as tmp_script:
  197. tmp_script.write(response.content)
  198. tmp_script_path = tmp_script.name
  199. logger.debug(f"Written update script to temporary file: {tmp_script_path}")
  200. os.chmod(tmp_script_path, 0o700)
  201. args = [sh_bin, tmp_script_path, "--update"]
  202. logger.info(f"Executing update script with command: {args}")
  203. try:
  204. # The external update script is downloaded from the official GitHub
  205. # release feed, then written to a temporary file and executed.
  206. # This is intentionally executing remote installer content.
  207. subprocess.run(args, env=env, check=True, timeout=600) # noqa: S603
  208. logger.info("Update script executed successfully")
  209. finally:
  210. try:
  211. os.remove(tmp_script_path)
  212. except OSError:
  213. logger.warning(
  214. f"Unable to remove temporary update script: {tmp_script_path}"
  215. )
  216. return True
  217. except Exception:
  218. logger.exception("Error descargando el script de actualización")
  219. return False
  220. except Exception:
  221. logger.exception("Error crítico en updateSquidStats")
  222. return False
  223. _WEB_UPDATE_CACHE = {"data": None, "timestamp": 0}
  224. _WEB_CACHE_TTL = 300 # 5 minutos
  225. _GITHUB_WEB_API = "https://api.github.com/repos/kaelthasmanu/SquidStats/releases/latest"
  226. def _parse_web_version(version_str):
  227. """Extrae la tupla numérica de una versión, ignorando prefijos como 'v'."""
  228. if not version_str:
  229. return (0, 0, 0)
  230. cleaned = re.sub(r"^[vV]", "", version_str.strip())
  231. parts = re.split(r"[.-]", cleaned)
  232. nums = []
  233. for part in parts:
  234. try:
  235. nums.append(int(part))
  236. except ValueError:
  237. break
  238. return tuple(nums) if nums else (0, 0, 0)
  239. def _web_version_is_newer(current, latest):
  240. """Devuelve True si latest es mayor que current."""
  241. return _parse_web_version(latest) > _parse_web_version(current)
  242. def check_web_update(current_version, force_refresh=False):
  243. """Verifica si existe una versión más reciente de SquidStats en GitHub.
  244. Args:
  245. current_version (str): Versión actual de la aplicación (p. ej. Config.VERSION).
  246. force_refresh (bool): Ignora el caché y consulta GitHub nuevamente.
  247. Retorna un dict con:
  248. - available (bool)
  249. - current (str): versión actual proporcionada
  250. - latest (str): última versión en GitHub o None
  251. - error (str|None): mensaje de error si falló la consulta
  252. """
  253. global _WEB_UPDATE_CACHE
  254. now = time.time()
  255. if (
  256. not force_refresh
  257. and _WEB_UPDATE_CACHE["data"]
  258. and (now - _WEB_UPDATE_CACHE["timestamp"] < _WEB_CACHE_TTL)
  259. ):
  260. return _WEB_UPDATE_CACHE["data"]
  261. try:
  262. proxy_url = os.getenv("HTTP_PROXY", "") or os.getenv("HTTPS_PROXY", "")
  263. proxies = None
  264. if proxy_url:
  265. proxies = {"http": proxy_url, "https": proxy_url}
  266. response = requests.get(
  267. _GITHUB_WEB_API,
  268. proxies=proxies,
  269. timeout=30,
  270. )
  271. response.raise_for_status()
  272. latest_version = response.json().get("tag_name", "")
  273. if not latest_version:
  274. result = {
  275. "available": False,
  276. "current": current_version,
  277. "latest": None,
  278. "error": "No se pudo obtener la última versión desde GitHub",
  279. }
  280. _WEB_UPDATE_CACHE = {"data": result, "timestamp": now}
  281. return result
  282. available = _web_version_is_newer(current_version or "0", latest_version)
  283. result = {
  284. "available": available,
  285. "current": current_version,
  286. "latest": latest_version,
  287. "error": None,
  288. }
  289. _WEB_UPDATE_CACHE = {"data": result, "timestamp": now}
  290. return result
  291. except Exception:
  292. logger.exception("Error verificando actualización de SquidStats")
  293. result = {
  294. "available": False,
  295. "current": current_version,
  296. "latest": None,
  297. "error": "No se pudo verificar la actualización de SquidStats",
  298. }
  299. _WEB_UPDATE_CACHE = {"data": result, "timestamp": now}
  300. return result