updates.py 26 KB

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