updates.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. """Update checking and management routes."""
  2. import asyncio
  3. import logging
  4. import os
  5. import re
  6. import shutil
  7. import sys
  8. import httpx
  9. from fastapi import APIRouter, BackgroundTasks, Depends
  10. from sqlalchemy import select
  11. from sqlalchemy.ext.asyncio import AsyncSession
  12. from backend.app.core.auth import RequirePermissionIfAuthEnabled
  13. from backend.app.core.config import APP_VERSION, GITHUB_REPO, settings
  14. from backend.app.core.database import get_db
  15. from backend.app.core.permissions import Permission
  16. from backend.app.models.settings import Settings
  17. from backend.app.models.user import User
  18. logger = logging.getLogger(__name__)
  19. router = APIRouter(prefix="/updates", tags=["updates"])
  20. # Global state for update progress
  21. _update_status = {
  22. "status": "idle", # idle, checking, downloading, installing, complete, error
  23. "progress": 0,
  24. "message": "",
  25. "error": None,
  26. }
  27. def _is_docker_environment() -> bool:
  28. """Detect if running inside a Docker container."""
  29. if os.path.exists("/.dockerenv"):
  30. return True
  31. try:
  32. with open("/proc/1/cgroup") as f:
  33. if "docker" in f.read():
  34. return True
  35. except (FileNotFoundError, PermissionError):
  36. pass # cgroup file unavailable; continue with other detection methods
  37. # Check container runtime hint (systemd sets this for Docker/podman,
  38. # but NOT for LXC/LXD — avoids false positives on Proxmox containers)
  39. try:
  40. with open("/run/systemd/container") as f:
  41. runtime = f.read().strip()
  42. if runtime in ("docker", "podman", "oci"):
  43. return True
  44. except (FileNotFoundError, PermissionError):
  45. pass
  46. return False
  47. def _is_ha_addon() -> bool:
  48. """Detect if running as a Home Assistant Supervisor addon.
  49. HA Supervisor injects ``SUPERVISOR_TOKEN`` into every addon container;
  50. the variable is not set in any other environment, so a single env-var
  51. check is sufficient with no false-positive surface.
  52. """
  53. return bool(os.environ.get("SUPERVISOR_TOKEN"))
  54. def _find_executable(name: str) -> str | None:
  55. """Find an executable in PATH or common locations."""
  56. # Try standard PATH first
  57. path = shutil.which(name)
  58. if path:
  59. return path
  60. # Common locations for executables (useful when running as systemd service)
  61. common_paths = [
  62. f"/usr/bin/{name}",
  63. f"/usr/local/bin/{name}",
  64. f"/opt/homebrew/bin/{name}",
  65. f"/home/linuxbrew/.linuxbrew/bin/{name}",
  66. f"{os.path.expanduser('~')}/.nvm/current/bin/{name}",
  67. f"{os.path.expanduser('~')}/.local/bin/{name}",
  68. ]
  69. for p in common_paths:
  70. if os.path.isfile(p) and os.access(p, os.X_OK):
  71. return p
  72. return None
  73. def _parse_github_remote(url: str) -> tuple[str, str] | None:
  74. """Extract `(owner, repo)` from a GitHub remote URL, or None if it isn't a
  75. GitHub URL we recognise.
  76. Handles the four forms `git remote -v` typically prints:
  77. - `git@github.com:owner/repo.git` (SSH, the dev default)
  78. - `git@github.com:owner/repo` (SSH without .git suffix)
  79. - `https://github.com/owner/repo.git` (HTTPS, what _perform_update sets)
  80. - `https://github.com/owner/repo` (HTTPS without .git)
  81. Anything else (a fork URL, a different host, a malformed value, the empty
  82. string from a missing origin) returns None so the caller treats it as
  83. "not pointing at our repo" and resets it.
  84. """
  85. s = url.strip()
  86. if not s:
  87. return None
  88. # SSH form: git@github.com:owner/repo[.git]
  89. ssh_prefix = "git@github.com:"
  90. https_prefix_a = "https://github.com/"
  91. https_prefix_b = "http://github.com/" # tolerated for legacy
  92. if s.startswith(ssh_prefix):
  93. path = s[len(ssh_prefix) :]
  94. elif s.startswith(https_prefix_a):
  95. path = s[len(https_prefix_a) :]
  96. elif s.startswith(https_prefix_b):
  97. path = s[len(https_prefix_b) :]
  98. else:
  99. return None
  100. if path.endswith(".git"):
  101. path = path[:-4]
  102. parts = path.strip("/").split("/")
  103. if len(parts) != 2 or not parts[0] or not parts[1]:
  104. return None
  105. return (parts[0], parts[1])
  106. async def _origin_points_at_repo(git_path: str, git_config: list[str], base_dir, expected_repo: str) -> bool:
  107. """Return True iff the working tree's `origin` already resolves to
  108. `<owner>/<repo>` matching `expected_repo` (e.g. "maziggy/bambuddy"),
  109. regardless of whether it's the SSH or HTTPS form. Used to skip the
  110. `git remote set-url origin https://...` rewrite when the developer's
  111. SSH origin is already correct — see `_perform_update` for context."""
  112. try:
  113. process = await asyncio.create_subprocess_exec(
  114. git_path,
  115. *git_config,
  116. "remote",
  117. "get-url",
  118. "origin",
  119. cwd=str(base_dir),
  120. stdout=asyncio.subprocess.PIPE,
  121. stderr=asyncio.subprocess.PIPE,
  122. )
  123. stdout, _ = await process.communicate()
  124. except (OSError, asyncio.CancelledError):
  125. # Fail closed: let the caller go through the rewrite branch if we
  126. # can't even invoke git. The unconditional set-url is the safer
  127. # fallback, only mildly destructive.
  128. return False
  129. if process.returncode != 0:
  130. # Most likely cause: no `origin` defined yet (fresh clone-style
  131. # checkout). Caller will set it.
  132. return False
  133. parsed = _parse_github_remote(stdout.decode().strip())
  134. if parsed is None:
  135. return False
  136. owner, repo = parsed
  137. expected_owner, expected_repo_name = expected_repo.split("/", 1)
  138. return owner == expected_owner and repo == expected_repo_name
  139. def parse_version(version: str) -> tuple:
  140. """Parse version string into tuple for comparison.
  141. Returns (major, minor, patch, micro, is_prerelease, prerelease_num)
  142. where is_prerelease is 0 for release, 1 for prerelease.
  143. This ensures releases sort higher than prereleases of same version.
  144. Examples:
  145. "0.1.5" -> (0, 1, 5, 0, 0, 0) # release
  146. "0.1.5b7" -> (0, 1, 5, 0, 1, 7) # beta 7
  147. "0.1.5b10" -> (0, 1, 5, 0, 1, 10) # beta 10
  148. "0.1.8.1" -> (0, 1, 8, 1, 0, 0) # patch release
  149. """
  150. # Remove 'v' prefix if present
  151. version = version.lstrip("v")
  152. # Strip daily build suffix (e.g., "0.2.2b4-daily.20260313" -> "0.2.2b4")
  153. version = re.sub(r"-daily\.\d+$", "", version)
  154. # Match version pattern: major.minor.patch[.micro][b|beta|alpha|rc]N
  155. match = re.match(r"(\d+)\.(\d+)\.(\d+)(?:\.(\d+))?(?:b|beta|alpha|rc)?(\d+)?", version)
  156. if match:
  157. major = int(match.group(1))
  158. minor = int(match.group(2))
  159. patch = int(match.group(3))
  160. micro = int(match.group(4)) if match.group(4) else 0
  161. prerelease_num = int(match.group(5)) if match.group(5) else 0
  162. # Check if this is a prerelease (has b/beta/alpha/rc/daily suffix anywhere)
  163. is_prerelease = 1 if re.search(r"[a-zA-Z]", version) else 0
  164. return (major, minor, patch, micro, is_prerelease, prerelease_num)
  165. # Fallback: try simple split
  166. parts = []
  167. for part in version.split("."):
  168. try:
  169. parts.append(int(part))
  170. except ValueError:
  171. num = "".join(c for c in part if c.isdigit())
  172. parts.append(int(num) if num else 0)
  173. return tuple(parts) + (0, 0, 0)
  174. def is_newer_version(latest: str, current: str) -> bool:
  175. """Check if latest version is newer than current.
  176. Properly handles prerelease versions:
  177. - 0.1.5 > 0.1.5b7 (release is newer than any beta)
  178. - 0.1.5b8 > 0.1.5b7 (later beta is newer)
  179. - 0.1.6b1 > 0.1.5 (next version beta is newer than current release)
  180. """
  181. try:
  182. latest_parsed = parse_version(latest)
  183. current_parsed = parse_version(current)
  184. # Compare (major, minor, patch, micro) first
  185. latest_base = latest_parsed[:4]
  186. current_base = current_parsed[:4]
  187. if latest_base > current_base:
  188. return True
  189. elif latest_base < current_base:
  190. return False
  191. # Same base version - compare prerelease status
  192. # is_prerelease: 0 = release, 1 = prerelease
  193. # Release (0) should be "greater" than prerelease (1)
  194. latest_is_prerelease = latest_parsed[4] if len(latest_parsed) > 4 else 0
  195. current_is_prerelease = current_parsed[4] if len(current_parsed) > 4 else 0
  196. if latest_is_prerelease < current_is_prerelease:
  197. # latest is release, current is prerelease -> latest is newer
  198. return True
  199. elif latest_is_prerelease > current_is_prerelease:
  200. # latest is prerelease, current is release -> latest is NOT newer
  201. return False
  202. # Both are same type (both release or both prerelease)
  203. # Compare prerelease numbers
  204. latest_prerelease_num = latest_parsed[5] if len(latest_parsed) > 5 else 0
  205. current_prerelease_num = current_parsed[5] if len(current_parsed) > 5 else 0
  206. return latest_prerelease_num > current_prerelease_num
  207. except Exception:
  208. return False
  209. @router.get("/version")
  210. async def get_version():
  211. """Get current application version.
  212. Note: Unauthenticated - needed to display version in UI without login.
  213. """
  214. return {
  215. "version": APP_VERSION,
  216. "repo": GITHUB_REPO,
  217. }
  218. @router.get("/check")
  219. async def check_for_updates(
  220. db: AsyncSession = Depends(get_db),
  221. _: User | None = RequirePermissionIfAuthEnabled(Permission.SYSTEM_READ),
  222. ):
  223. """Check GitHub for available updates."""
  224. global _update_status
  225. # Respect the check_updates setting
  226. result = await db.execute(select(Settings).where(Settings.key == "check_updates"))
  227. setting = result.scalar_one_or_none()
  228. if setting and setting.value.lower() == "false":
  229. return {
  230. "update_available": False,
  231. "current_version": APP_VERSION,
  232. "latest_version": None,
  233. "message": "Update checks are disabled",
  234. }
  235. # Check if beta updates should be included
  236. result = await db.execute(select(Settings).where(Settings.key == "include_beta_updates"))
  237. beta_setting = result.scalar_one_or_none()
  238. include_beta = beta_setting and beta_setting.value.lower() == "true"
  239. _update_status = {
  240. "status": "checking",
  241. "progress": 0,
  242. "message": "Checking for updates...",
  243. "error": None,
  244. }
  245. try:
  246. async with httpx.AsyncClient() as client:
  247. response = await client.get(
  248. f"https://api.github.com/repos/{GITHUB_REPO}/releases?per_page=20",
  249. headers={"Accept": "application/vnd.github.v3+json"},
  250. timeout=10.0,
  251. )
  252. if response.status_code == 404:
  253. # No releases yet
  254. _update_status = {
  255. "status": "idle",
  256. "progress": 100,
  257. "message": "No releases found",
  258. "error": None,
  259. }
  260. return {
  261. "update_available": False,
  262. "current_version": APP_VERSION,
  263. "latest_version": None,
  264. "message": "No releases found",
  265. }
  266. response.raise_for_status()
  267. releases = response.json()
  268. # Find the appropriate release based on beta setting
  269. release_data = None
  270. for release in releases:
  271. tag = release.get("tag_name", "")
  272. if include_beta:
  273. # Accept any release (first = newest)
  274. release_data = release
  275. break
  276. else:
  277. # Skip prereleases (based on version parsing, not GitHub flag)
  278. parsed = parse_version(tag)
  279. if parsed[4] == 0: # is_prerelease == 0
  280. release_data = release
  281. break
  282. if not release_data:
  283. _update_status = {
  284. "status": "idle",
  285. "progress": 100,
  286. "message": "No releases found",
  287. "error": None,
  288. }
  289. return {
  290. "update_available": False,
  291. "current_version": APP_VERSION,
  292. "latest_version": None,
  293. "message": "No releases found",
  294. }
  295. latest_version = release_data.get("tag_name", "").lstrip("v")
  296. release_name = release_data.get("name", latest_version)
  297. release_notes = release_data.get("body", "")
  298. release_url = release_data.get("html_url", "")
  299. published_at = release_data.get("published_at", "")
  300. update_available = is_newer_version(latest_version, APP_VERSION)
  301. _update_status = {
  302. "status": "idle",
  303. "progress": 100,
  304. "message": "Update available" if update_available else "Up to date",
  305. "error": None,
  306. }
  307. is_docker = _is_docker_environment()
  308. is_ha_addon = _is_ha_addon()
  309. if is_ha_addon:
  310. update_method = "ha_addon"
  311. elif is_docker:
  312. update_method = "docker"
  313. else:
  314. update_method = "git"
  315. return {
  316. "update_available": update_available,
  317. "current_version": APP_VERSION,
  318. "latest_version": latest_version,
  319. "release_name": release_name,
  320. "release_notes": release_notes,
  321. "release_url": release_url,
  322. "published_at": published_at,
  323. "is_docker": is_docker,
  324. "is_ha_addon": is_ha_addon,
  325. "update_method": update_method,
  326. }
  327. except httpx.HTTPError as e:
  328. logger.error("Failed to check for updates: %s", e)
  329. _update_status = {
  330. "status": "error",
  331. "progress": 0,
  332. "message": "Failed to check for updates",
  333. "error": "Failed to check for updates",
  334. }
  335. return {
  336. "update_available": False,
  337. "current_version": APP_VERSION,
  338. "latest_version": None,
  339. "error": "Failed to check for updates",
  340. }
  341. async def _discover_target_release(db: AsyncSession) -> str | None:
  342. """Look up the tag we should install from GitHub releases.
  343. Same selection logic the GUI's update-check uses: respect
  344. `include_beta_updates`, skip prereleases when the user opted out, take
  345. the first matching release. Returns the raw tag name (e.g. `v0.2.4b1`)
  346. so the git ref is unambiguous, or None if there's no release to install.
  347. The previous in-app updater path was hardcoded to `git fetch origin main
  348. && git reset --hard origin/main`, which silently no-ops whenever main
  349. isn't where the latest release lives — e.g. during a beta release cycle
  350. where the next stable hasn't been merged to main yet. Anchoring to the
  351. release tag instead lets the GUI install whatever GitHub says is latest.
  352. """
  353. result = await db.execute(select(Settings).where(Settings.key == "include_beta_updates"))
  354. beta_setting = result.scalar_one_or_none()
  355. include_beta = beta_setting and beta_setting.value.lower() == "true"
  356. try:
  357. async with httpx.AsyncClient() as client:
  358. response = await client.get(
  359. f"https://api.github.com/repos/{GITHUB_REPO}/releases?per_page=20",
  360. headers={"Accept": "application/vnd.github.v3+json"},
  361. timeout=10.0,
  362. )
  363. response.raise_for_status()
  364. releases = response.json()
  365. except (httpx.HTTPError, ValueError) as exc:
  366. logger.error("Could not fetch GitHub releases for update target: %s", exc)
  367. return None
  368. for release in releases:
  369. tag = release.get("tag_name", "")
  370. if not tag:
  371. continue
  372. if include_beta:
  373. return tag
  374. # Skip prereleases (parsed from version, not GitHub flag — GitHub's
  375. # is_prerelease flag isn't always set on dailies).
  376. parsed = parse_version(tag)
  377. if parsed[4] == 0:
  378. return tag
  379. return None
  380. async def _perform_update(target_ref: str):
  381. """Perform the actual update using git fetch and reset.
  382. `target_ref` is whatever git ref the caller wants to land on — typically
  383. a release tag like `v0.2.4b1` resolved by `_discover_target_release`,
  384. but accepts any ref `git reset --hard` understands (`origin/main`, a
  385. branch, a sha). Tag-based refs are the production path because they pin
  386. the install to a specific release artifact instead of whatever happens
  387. to be on a moving branch.
  388. """
  389. global _update_status
  390. try:
  391. base_dir = settings.base_dir
  392. # Find git executable (may not be in PATH when running as systemd service)
  393. git_path = _find_executable("git")
  394. if not git_path:
  395. _update_status = {
  396. "status": "error",
  397. "progress": 0,
  398. "message": "Git not found",
  399. "error": "Could not find git executable. Please ensure git is installed.",
  400. }
  401. return
  402. logger.info("Using git at: %s", git_path)
  403. # Git config to avoid safe.directory issues
  404. git_config = ["-c", f"safe.directory={base_dir}"]
  405. _update_status = {
  406. "status": "downloading",
  407. "progress": 10,
  408. "message": "Configuring git...",
  409. "error": None,
  410. }
  411. # Ensure remote points at the expected repo. We previously rewrote
  412. # origin to HTTPS unconditionally on the assumption that systemd
  413. # service users wouldn't have SSH keys configured — which is fine
  414. # for that case, but stomps on developer checkouts where origin is
  415. # legitimately `git@github.com:maziggy/bambuddy.git` and the user
  416. # auths via SSH keys. After the rewrite, `git push` prompts for
  417. # HTTPS credentials and fails.
  418. # New behaviour: read the current origin, parse out the
  419. # `<owner>/<repo>` pair, and only rewrite if it doesn't already
  420. # resolve to the right GitHub repo. SSH origins pointing at the
  421. # correct repo are preserved; only missing / wrong / corrupted
  422. # origins get reset to HTTPS.
  423. https_url = f"https://github.com/{GITHUB_REPO}.git"
  424. if not await _origin_points_at_repo(git_path, git_config, base_dir, GITHUB_REPO):
  425. process = await asyncio.create_subprocess_exec(
  426. git_path,
  427. *git_config,
  428. "remote",
  429. "set-url",
  430. "origin",
  431. https_url,
  432. cwd=str(base_dir),
  433. stdout=asyncio.subprocess.PIPE,
  434. stderr=asyncio.subprocess.PIPE,
  435. )
  436. await process.communicate()
  437. _update_status = {
  438. "status": "downloading",
  439. "progress": 20,
  440. "message": "Fetching latest changes...",
  441. "error": None,
  442. }
  443. # Fetch branches AND tags from origin so any ref the caller passes
  444. # (release tag like `v0.2.4b1`, a branch like `main`, or a sha) is
  445. # locally resolvable for the reset below. `--tags` is required —
  446. # plain `git fetch origin` doesn't bring tags by default, so a
  447. # release tag would not be resolvable.
  448. #
  449. # `--force` lets a moved tag on the remote overwrite the local copy.
  450. # Without it, any tag that was re-tagged upstream (e.g. v0.2.1 being
  451. # re-pointed after a hotfix re-tag) makes `git fetch --tags` return
  452. # a non-zero exit even though every other ref fetched cleanly —
  453. # which we'd then surface as "Failed to fetch updates" to the user.
  454. # The in-app updater's contract is "sync me to the remote"; force-
  455. # overwriting a stale local tag matches that intent.
  456. process = await asyncio.create_subprocess_exec(
  457. git_path,
  458. *git_config,
  459. "fetch",
  460. "--prune",
  461. "--tags",
  462. "--force",
  463. "origin",
  464. cwd=str(base_dir),
  465. stdout=asyncio.subprocess.PIPE,
  466. stderr=asyncio.subprocess.PIPE,
  467. )
  468. stdout, stderr = await process.communicate()
  469. if process.returncode != 0:
  470. error_msg = stderr.decode() if stderr else "Git fetch failed"
  471. logger.error("Git fetch failed: %s", error_msg)
  472. _update_status = {
  473. "status": "error",
  474. "progress": 0,
  475. "message": "Failed to fetch updates",
  476. "error": error_msg,
  477. }
  478. return
  479. _update_status = {
  480. "status": "downloading",
  481. "progress": 40,
  482. "message": "Applying updates...",
  483. "error": None,
  484. }
  485. # Hard reset to the target ref (clean update, no merge conflicts).
  486. # `target_ref` is typically a release tag like `v0.2.4b1` resolved
  487. # from the GitHub releases API by `_discover_target_release`. The
  488. # local branch name doesn't change — only HEAD moves. Falling back
  489. # to `origin/main` here was the source of the "in-app updater can't
  490. # reach beta releases" bug.
  491. process = await asyncio.create_subprocess_exec(
  492. git_path,
  493. *git_config,
  494. "reset",
  495. "--hard",
  496. target_ref,
  497. cwd=str(base_dir),
  498. stdout=asyncio.subprocess.PIPE,
  499. stderr=asyncio.subprocess.PIPE,
  500. )
  501. stdout, stderr = await process.communicate()
  502. if process.returncode != 0:
  503. error_msg = stderr.decode() if stderr else "Git reset failed"
  504. logger.error("Git reset failed: %s", error_msg)
  505. _update_status = {
  506. "status": "error",
  507. "progress": 0,
  508. "message": "Failed to apply updates",
  509. "error": error_msg,
  510. }
  511. return
  512. _update_status = {
  513. "status": "installing",
  514. "progress": 50,
  515. "message": "Installing dependencies...",
  516. "error": None,
  517. }
  518. # Install Python dependencies — must run from the source-code directory
  519. # (where requirements.txt lives), not the data dir. On native installs
  520. # systemd sets DATA_DIR=INSTALL_PATH/data, so `base_dir` is the data dir,
  521. # not the working tree. `git reset` above worked from base_dir because
  522. # git walks up looking for .git, but `pip install -r requirements.txt`
  523. # needs the file in cwd literally.
  524. app_dir = settings.app_dir
  525. process = await asyncio.create_subprocess_exec(
  526. sys.executable,
  527. "-m",
  528. "pip",
  529. "install",
  530. "-r",
  531. "requirements.txt",
  532. "-q",
  533. cwd=str(app_dir),
  534. stdout=asyncio.subprocess.PIPE,
  535. stderr=asyncio.subprocess.PIPE,
  536. )
  537. stdout, stderr = await process.communicate()
  538. if process.returncode != 0:
  539. logger.warning("pip install warning: %s", stderr.decode() if stderr else "unknown")
  540. # Try to build frontend if npm is available (optional - static files are pre-built)
  541. npm_path = _find_executable("npm")
  542. frontend_dir = app_dir / "frontend"
  543. if npm_path and frontend_dir.exists():
  544. _update_status = {
  545. "status": "installing",
  546. "progress": 70,
  547. "message": "Building frontend...",
  548. "error": None,
  549. }
  550. # npm install
  551. process = await asyncio.create_subprocess_exec(
  552. npm_path,
  553. "install",
  554. cwd=str(frontend_dir),
  555. stdout=asyncio.subprocess.PIPE,
  556. stderr=asyncio.subprocess.PIPE,
  557. )
  558. await process.communicate()
  559. # npm run build
  560. process = await asyncio.create_subprocess_exec(
  561. npm_path,
  562. "run",
  563. "build",
  564. cwd=str(frontend_dir),
  565. stdout=asyncio.subprocess.PIPE,
  566. stderr=asyncio.subprocess.PIPE,
  567. )
  568. stdout, stderr = await process.communicate()
  569. if process.returncode != 0:
  570. logger.warning("Frontend build warning: %s", stderr.decode() if stderr else "unknown")
  571. else:
  572. logger.info("npm not found or frontend dir missing - using pre-built static files")
  573. _update_status = {
  574. "status": "complete",
  575. "progress": 100,
  576. "message": "Update complete! Please restart the application.",
  577. "error": None,
  578. }
  579. logger.info("Update completed successfully")
  580. except Exception as e:
  581. logger.error("Update failed: %s", e)
  582. _update_status = {
  583. "status": "error",
  584. "progress": 0,
  585. "message": "Update failed",
  586. "error": "Update failed unexpectedly",
  587. }
  588. @router.post("/apply")
  589. async def apply_update(
  590. background_tasks: BackgroundTasks,
  591. db: AsyncSession = Depends(get_db),
  592. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  593. ):
  594. """Apply available update (git pull + rebuild)."""
  595. global _update_status
  596. if _update_status["status"] in ["downloading", "installing"]:
  597. return {
  598. "success": False,
  599. "message": "Update already in progress",
  600. "status": _update_status,
  601. }
  602. # Check for managed deployment shapes that own the update lifecycle.
  603. # HA addons are also Docker, so check HA first to surface the more
  604. # specific message.
  605. if _is_ha_addon():
  606. return {
  607. "success": False,
  608. "is_ha_addon": True,
  609. "is_docker": True,
  610. "message": (
  611. "Bambuddy is running as a Home Assistant addon. "
  612. "Updates are managed by the Home Assistant Supervisor "
  613. "(Settings → Add-ons → Bambuddy → Update)."
  614. ),
  615. }
  616. if _is_docker_environment():
  617. return {
  618. "success": False,
  619. "is_docker": True,
  620. "message": (
  621. "Docker installations cannot be updated in-app. "
  622. "Please update via Docker Compose: "
  623. "git pull && docker compose build --pull && docker compose up -d"
  624. ),
  625. }
  626. # Discover which release tag to install. Resolved here (where we have
  627. # a DB session) and passed into the background task; the BG task can't
  628. # reuse this request's session since FastAPI closes it on response.
  629. target_ref = await _discover_target_release(db)
  630. if target_ref is None:
  631. return {
  632. "success": False,
  633. "message": (
  634. "Could not determine a release to install. Either GitHub is "
  635. "unreachable or no release matches your update channel "
  636. "(check the include_beta_updates setting)."
  637. ),
  638. }
  639. # Start update in background
  640. background_tasks.add_task(_perform_update, target_ref)
  641. _update_status = {
  642. "status": "downloading",
  643. "progress": 10,
  644. "message": "Starting update...",
  645. "error": None,
  646. }
  647. return {
  648. "success": True,
  649. "message": "Update started",
  650. "status": _update_status,
  651. }
  652. @router.get("/status")
  653. async def get_update_status(
  654. _: User | None = RequirePermissionIfAuthEnabled(Permission.SYSTEM_READ),
  655. ):
  656. """Get current update status."""
  657. return _update_status