firmware_check.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. """
  2. Firmware Check Service
  3. Checks for firmware updates by fetching from Bambu Lab's official wiki and firmware
  4. download page. The wiki is used as the primary version source (always up-to-date),
  5. while the download page provides firmware file URLs for offline updates.
  6. """
  7. import json
  8. import logging
  9. import re
  10. import time
  11. from collections.abc import Callable
  12. from dataclasses import dataclass
  13. from pathlib import Path
  14. import httpx
  15. from backend.app.core.config import _data_dir
  16. logger = logging.getLogger(__name__)
  17. # Cloudflare on bambulab.com now gates the firmware-download page behind a
  18. # JA3/TLS-fingerprint challenge (cf-mitigated=challenge) that plain Python
  19. # TLS can't pass (#1666). curl_cffi replays Chrome's actual ClientHello
  20. # bytes so the handshake clears CF; we override the HTTP User-Agent back to
  21. # the honest Bambuddy/1.0 string so the application-layer identity stays
  22. # truthful (TLS fingerprint matches Chrome because Python's TLS is the
  23. # signal CF gates on; everything above TLS is still Bambuddy).
  24. #
  25. # Soft dependency — if curl_cffi isn't importable on the running platform,
  26. # firmware_check degrades to httpx (which will likely 403) and wiki-based
  27. # version detection continues to work for the badge; only the in-app
  28. # firmware-download URL stops resolving.
  29. try:
  30. from curl_cffi.requests import AsyncSession as _CurlCffiAsyncSession
  31. _CURL_CFFI_AVAILABLE = True
  32. except ImportError: # pragma: no cover — exercised only on platforms without wheels
  33. _CurlCffiAsyncSession = None # type: ignore[misc,assignment]
  34. _CURL_CFFI_AVAILABLE = False
  35. # Bambu Lab firmware download page (for download URLs)
  36. BAMBU_FIRMWARE_BASE = "https://bambulab.com"
  37. FIRMWARE_PAGE = "/en/support/firmware-download/all"
  38. # Bambu Lab wiki (primary source for latest version detection)
  39. BAMBU_WIKI_BASE = "https://wiki.bambulab.com"
  40. # Cache TTL in seconds (1 hour)
  41. CACHE_TTL = 3600
  42. # Map Bambuddy model names to Bambu Lab API keys
  43. MODEL_TO_API_KEY = {
  44. "X1": "x1",
  45. "X1C": "x1",
  46. "X1-Carbon": "x1",
  47. "X1 Carbon": "x1",
  48. "P1P": "p1",
  49. "P1S": "p1",
  50. "A1": "a1",
  51. "A1 Mini": "a1-mini",
  52. "A1-Mini": "a1-mini",
  53. "A1mini": "a1-mini",
  54. "H2D": "h2d",
  55. "H2C": "h2c",
  56. "H2S": "h2s",
  57. "P2S": "p2s",
  58. "X1E": "x1e",
  59. "X2D": "x2d",
  60. "H2D Pro": "h2d-pro",
  61. "H2D-Pro": "h2d-pro",
  62. "H2DPRO": "h2d-pro",
  63. # SSDP model codes (DevModel header) — in case raw codes are stored
  64. "O1D": "h2d",
  65. "O1E": "h2d-pro",
  66. "O2D": "h2d-pro",
  67. "O1C": "h2c",
  68. "O1C2": "h2c",
  69. "O1S": "h2s",
  70. "BL-P001": "x1",
  71. "BL-P002": "x1",
  72. "BL-P003": "x1e",
  73. "C11": "p1",
  74. "C12": "p1",
  75. "C13": "p2s",
  76. "N2S": "a1",
  77. "N1": "a1-mini",
  78. "N6": "x2d",
  79. "N7": "p2s",
  80. }
  81. # Reverse mapping: API key to model codes
  82. API_KEY_TO_DEV_MODEL = {
  83. "x1": "BL-P001",
  84. "p1": "C11",
  85. "a1": "N2S",
  86. "a1-mini": "N1",
  87. "h2d": "O1D",
  88. "h2c": "O1C",
  89. "h2s": "O1S",
  90. "p2s": "N7",
  91. "x1e": "C13",
  92. "x2d": "N6",
  93. "h2d-pro": "O1E",
  94. }
  95. # Wiki firmware release history pages (primary version source)
  96. API_KEY_TO_WIKI_PATH = {
  97. "x1": "/en/x1/manual/X1-X1C-firmware-release-history",
  98. "x1e": "/en/x1/manual/X1E-firmware-release-history",
  99. "p1": "/en/p1/manual/p1p-firmware-release-history",
  100. "a1": "/en/a1/manual/a1-firmware-release-history",
  101. "a1-mini": "/en/a1-mini/manual/a1-mini-firmware-release-history",
  102. "h2d": "/en/h2d/manual/h2d-firmware-release-history",
  103. "h2c": "/en/h2c/manual/h2c-firmware-release-history",
  104. "h2s": "/en/h2s/manual/h2s-firmware-release-history",
  105. "p2s": "/en/p2s/manual/p2s-firmware-release-history",
  106. "x2d": "/en/x2d/manual/x2d-firmware-release-history",
  107. "h2d-pro": "/en/h2d-pro/manual/firmware-release-history",
  108. }
  109. @dataclass
  110. class FirmwareVersion:
  111. """Firmware version information."""
  112. version: str
  113. download_url: str
  114. release_notes: str | None = None
  115. release_time: str | None = None
  116. class FirmwareCheckService:
  117. """Service for checking firmware updates from Bambu Lab."""
  118. def __init__(self):
  119. self._build_id: str | None = None
  120. self._build_id_time: float = 0
  121. self._download_page_unreachable: bool = False
  122. self._version_cache: dict[str, FirmwareVersion] = {}
  123. self._versions_list_cache: dict[str, list[FirmwareVersion]] = {}
  124. self._cache_time: float = 0
  125. # Plain httpx client for the Bambu Lab wiki (no CF fingerprint check)
  126. # and other endpoints. Honest UA throughout.
  127. self._client = httpx.AsyncClient(
  128. timeout=30.0,
  129. headers={
  130. "User-Agent": "Bambuddy/1.0 (+https://github.com/maziggy/bambuddy)",
  131. "Accept": "text/html,application/json,*/*;q=0.8",
  132. "Accept-Language": "en-US,en;q=0.9",
  133. },
  134. )
  135. # curl_cffi session for bambulab.com (lazily initialised on first use).
  136. # See module-level note on why this is needed.
  137. self._bambulab_client: object | None = None
  138. if not _CURL_CFFI_AVAILABLE:
  139. logger.warning(
  140. "curl_cffi not installed — bambulab.com firmware-download page "
  141. "will likely return Cloudflare 403 (#1666). Wiki-based version "
  142. "detection still works; install curl_cffi to also resolve "
  143. "in-app firmware download URLs."
  144. )
  145. def _get_bambulab_client(self) -> object | None:
  146. """Lazy-init curl_cffi async session for bambulab.com.
  147. Chrome TLS impersonation is required to pass Cloudflare's JA3
  148. challenge. The HTTP `User-Agent` is overridden back to the honest
  149. Bambuddy string so application-layer identity stays truthful.
  150. Returns None when curl_cffi is unavailable.
  151. """
  152. if not _CURL_CFFI_AVAILABLE:
  153. return None
  154. if self._bambulab_client is None:
  155. assert _CurlCffiAsyncSession is not None # type-narrow for mypy
  156. self._bambulab_client = _CurlCffiAsyncSession(
  157. impersonate="chrome",
  158. headers={
  159. "User-Agent": "Bambuddy/1.0 (+https://github.com/maziggy/bambuddy)",
  160. "Accept": "text/html,application/json,*/*;q=0.8",
  161. "Accept-Language": "en-US,en;q=0.9",
  162. },
  163. timeout=30,
  164. )
  165. return self._bambulab_client
  166. async def _bambulab_get(self, url: str) -> tuple[int, str]:
  167. """GET against bambulab.com. Returns (status_code, body_text).
  168. Routes through curl_cffi when available (passes the CF JA3 gate);
  169. falls back to httpx otherwise (will likely 403 but worth the try
  170. in case CF eases the check). status 0 indicates a transport error.
  171. """
  172. client = self._get_bambulab_client()
  173. if client is not None:
  174. try:
  175. response = await client.get(url) # type: ignore[attr-defined]
  176. return response.status_code, response.text
  177. except Exception as e:
  178. logger.error("curl_cffi error fetching %s: %s", url, e)
  179. return 0, ""
  180. try:
  181. response = await self._client.get(url)
  182. return response.status_code, response.text
  183. except Exception as e:
  184. logger.error("httpx error fetching %s: %s", url, e)
  185. return 0, ""
  186. def _build_id_cache_path(self) -> Path:
  187. cache_dir = _data_dir / "firmware"
  188. cache_dir.mkdir(parents=True, exist_ok=True)
  189. return cache_dir / "build_id.json"
  190. def _load_build_id_from_disk(self) -> tuple[str | None, float]:
  191. """Load the last-known buildId from disk, returning (build_id, fetched_at)."""
  192. path = self._build_id_cache_path()
  193. try:
  194. if not path.exists():
  195. return None, 0.0
  196. data = json.loads(path.read_text())
  197. build_id = data.get("build_id")
  198. fetched_at = float(data.get("fetched_at", 0))
  199. if isinstance(build_id, str) and build_id:
  200. return build_id, fetched_at
  201. except (OSError, ValueError, TypeError) as e:
  202. logger.debug("Could not read cached buildId: %s", e)
  203. return None, 0.0
  204. def _save_build_id_to_disk(self, build_id: str) -> None:
  205. try:
  206. self._build_id_cache_path().write_text(json.dumps({"build_id": build_id, "fetched_at": time.time()}))
  207. except OSError as e:
  208. logger.debug("Could not persist buildId: %s", e)
  209. async def _get_build_id(self) -> str | None:
  210. """Fetch the Next.js build ID from Bambu Lab's firmware page.
  211. Cache layers (fresh → stale → none):
  212. 1. In-memory (1 hour TTL) — fast path for repeated checks in a session
  213. 2. Disk-cached buildId (any age) — survives restarts, lets us recover
  214. from upstream Cloudflare 403s. The buildId is treated as
  215. "probably still valid" because Bambu rebuilds the page only every
  216. few weeks; if the JSON fetch later fails, the caller falls back.
  217. 3. Live fetch from bambulab.com — only when both caches miss
  218. """
  219. # 1. In-memory cache (fresh)
  220. if self._build_id and (time.time() - self._build_id_time) < CACHE_TTL:
  221. return self._build_id
  222. # 2. Disk cache: load if we don't have one in memory yet (first call
  223. # after restart). We still try the live fetch below to refresh.
  224. if not self._build_id:
  225. disk_id, disk_time = self._load_build_id_from_disk()
  226. if disk_id:
  227. self._build_id = disk_id
  228. self._build_id_time = disk_time
  229. # 3. Live fetch
  230. status, body = await self._bambulab_get(f"{BAMBU_FIRMWARE_BASE}{FIRMWARE_PAGE}")
  231. if status == 200:
  232. match = re.search(r'"buildId":"([^"]+)"', body)
  233. if match:
  234. new_build_id = match.group(1)
  235. if new_build_id != self._build_id:
  236. logger.info("Got Bambu Lab build ID: %s", new_build_id)
  237. self._build_id = new_build_id
  238. self._build_id_time = time.time()
  239. self._download_page_unreachable = False
  240. self._save_build_id_to_disk(new_build_id)
  241. return self._build_id
  242. elif status == 0:
  243. # Transport-level error already logged by _bambulab_get.
  244. self._download_page_unreachable = True
  245. else:
  246. # 403/5xx — keep stale cached buildId if we have one (#1350).
  247. # Without curl_cffi this is the expected outcome on Cloudflare
  248. # JA3-gated zones (#1666).
  249. logger.warning(
  250. "Failed to get Bambu Lab page: %s (will try cached buildId if available)",
  251. status,
  252. )
  253. self._download_page_unreachable = True
  254. # Return whatever we have — even a stale buildId beats nothing.
  255. return self._build_id
  256. @property
  257. def download_page_unreachable(self) -> bool:
  258. """True if the most recent attempt to reach bambulab.com firmware page failed.
  259. Used by callers (e.g. the firmware update prepare flow) to render a
  260. clearer error message when a wiki-listed version has no download URL
  261. because we couldn't reach Bambu Lab, vs the version genuinely not
  262. being on the catalog (#1350).
  263. """
  264. return self._download_page_unreachable
  265. async def _fetch_version_from_wiki(self, api_key: str) -> str | None:
  266. """Fetch the latest firmware version from Bambu Lab's wiki release history page."""
  267. versions = await self._fetch_all_versions_from_wiki(api_key)
  268. if versions:
  269. logger.debug("Wiki firmware for %s: %s", api_key, versions[0][0])
  270. return versions[0][0]
  271. return None
  272. async def _fetch_all_versions_from_wiki(self, api_key: str) -> list[tuple[str, str | None]]:
  273. """
  274. Fetch all firmware versions from the wiki release history page.
  275. Only extracts versions that appear in section-heading anchors
  276. (e.g. `id="h-01030000-20260303"` or `id="h-0102000020260409"`) —
  277. this excludes version-like numbers mentioned incidentally in
  278. release-note text. The dash separator between version and date is
  279. optional: H2D/X1/H2C/H2S still use it, but P2S and X2D publish
  280. anchors without the dash.
  281. Returns list of (version, release_date_YYYYMMDD | None) tuples, newest first.
  282. """
  283. wiki_path = API_KEY_TO_WIKI_PATH.get(api_key)
  284. if not wiki_path:
  285. return []
  286. try:
  287. url = f"{BAMBU_WIKI_BASE}{wiki_path}"
  288. response = await self._client.get(url, follow_redirects=True)
  289. if response.status_code != 200:
  290. return []
  291. # Primary: heading anchor ids like id="h-01030000-20260303" (dash)
  292. # or id="h-0102000020260409" (no dash, P2S/X2D-style).
  293. anchor_matches = re.findall(r'id="h-(\d{2})(\d{2})(\d{2})(\d{2})-?(\d{8})"', response.text)
  294. seen: set[str] = set()
  295. versions: list[tuple[str, str | None]] = []
  296. for a, b, c, d, date in anchor_matches:
  297. v = f"{a}.{b}.{c}.{d}"
  298. if v in seen:
  299. continue
  300. seen.add(v)
  301. versions.append((v, date))
  302. if versions:
  303. return versions
  304. # Fallback: heading text with "XX.XX.XX.XX (YYYYMMDD)" —
  305. # accept both ASCII "()" and full-width "()" (U+FF08/U+FF09)
  306. # which some pages (A1, A1-mini, P2S) use.
  307. text_matches = re.findall(
  308. r"(\d{2}\.\d{2}\.\d{2}\.\d{2})\s*[(\uff08](\d{8})[)\uff09]",
  309. response.text,
  310. )
  311. for v, date in text_matches:
  312. if v in seen:
  313. continue
  314. seen.add(v)
  315. versions.append((v, date))
  316. return versions
  317. except Exception as e:
  318. logger.debug("Error fetching wiki firmware list for %s: %s", api_key, e)
  319. return []
  320. async def _fetch_all_versions_from_download_page(self, api_key: str) -> list[FirmwareVersion]:
  321. """Fetch all firmware versions from Bambu Lab's download page (newest first).
  322. If we have a stale (disk-cached) buildId and it returns 404 (Bambu
  323. rebuilt the page), retry once with a fresh fetch — this only kicks in
  324. when the in-memory cache thinks it's still valid but the upstream has
  325. moved on.
  326. """
  327. build_id = await self._get_build_id()
  328. if not build_id:
  329. return []
  330. for attempt in range(2):
  331. url = f"{BAMBU_FIRMWARE_BASE}/_next/data/{build_id}/en/support/firmware-download/{api_key}.json"
  332. status, body = await self._bambulab_get(url)
  333. if status == 200:
  334. try:
  335. data = json.loads(body)
  336. except ValueError as e:
  337. logger.debug("Download-page JSON for %s parse error: %s", api_key, e)
  338. return []
  339. page_props = data.get("pageProps", {})
  340. printer_map = page_props.get("printerMap", {})
  341. printer_data = printer_map.get(api_key, {})
  342. versions = printer_data.get("versions", [])
  343. return [
  344. FirmwareVersion(
  345. version=v.get("version", ""),
  346. download_url=v.get("url", ""),
  347. release_notes=v.get("release_notes_en"),
  348. release_time=v.get("release_time"),
  349. )
  350. for v in versions
  351. if v.get("version")
  352. ]
  353. # 404 with cached buildId → Bambu rebuilt the page; invalidate
  354. # and retry once. Other status codes (403, 5xx) are upstream
  355. # blocks — don't churn.
  356. if status == 404 and attempt == 0:
  357. logger.info("Cached Bambu buildId stale (404), refreshing")
  358. self._build_id = None
  359. self._build_id_time = 0
  360. build_id = await self._get_build_id()
  361. if not build_id:
  362. return []
  363. continue
  364. # 403 from the JSON endpoint is the same Cloudflare block
  365. # signal as on the index page (#1350, #1666).
  366. if status == 403:
  367. self._download_page_unreachable = True
  368. logger.debug("Download-page JSON for %s returned status %s", api_key, status)
  369. return []
  370. return []
  371. async def _fetch_from_download_page(self, api_key: str) -> FirmwareVersion | None:
  372. """Fetch the latest firmware info from Bambu Lab's download page (has download URLs)."""
  373. versions = await self._fetch_all_versions_from_download_page(api_key)
  374. return versions[0] if versions else None
  375. async def _fetch_firmware_versions(self, api_key: str) -> FirmwareVersion | None:
  376. """Fetch firmware version info, using wiki as primary source and download page as fallback."""
  377. # Try wiki first (always has the latest version)
  378. wiki_version = await self._fetch_version_from_wiki(api_key)
  379. # Try download page (has download URLs, may lag behind wiki)
  380. download_info = await self._fetch_from_download_page(api_key)
  381. if wiki_version:
  382. # Wiki has the latest version — use it, attach download URL if available
  383. download_url = ""
  384. release_notes = None
  385. if download_info and download_info.version == wiki_version:
  386. download_url = download_info.download_url
  387. release_notes = download_info.release_notes
  388. return FirmwareVersion(
  389. version=wiki_version,
  390. download_url=download_url,
  391. release_notes=release_notes,
  392. )
  393. if download_info:
  394. return download_info
  395. logger.warning("Could not fetch firmware info for %s from wiki or download page", api_key)
  396. return None
  397. async def get_latest_version(self, model: str) -> FirmwareVersion | None:
  398. """
  399. Get the latest firmware version for a printer model.
  400. Args:
  401. model: Bambuddy printer model name (e.g., "X1C", "P1S", "H2D")
  402. Returns:
  403. FirmwareVersion if found, None otherwise
  404. """
  405. # Normalize model name
  406. model_upper = model.upper().replace(" ", "").replace("-", "")
  407. # Find the API key for this model
  408. api_key = None
  409. for model_name, key in MODEL_TO_API_KEY.items():
  410. if model_name.upper().replace(" ", "").replace("-", "") == model_upper:
  411. api_key = key
  412. break
  413. if not api_key:
  414. # Try direct lookup with original model
  415. api_key = MODEL_TO_API_KEY.get(model)
  416. if not api_key:
  417. logger.debug("Unknown printer model: %s", model)
  418. return None
  419. # Check cache
  420. cache_key = api_key
  421. if cache_key in self._version_cache and (time.time() - self._cache_time) < CACHE_TTL:
  422. return self._version_cache[cache_key]
  423. # Fetch from API
  424. version = await self._fetch_firmware_versions(api_key)
  425. if version:
  426. self._version_cache[cache_key] = version
  427. self._cache_time = time.time()
  428. return version
  429. def _resolve_api_key(self, model: str) -> str | None:
  430. """Resolve a model name to its Bambu API key."""
  431. model_upper = model.upper().replace(" ", "").replace("-", "")
  432. for name, key in MODEL_TO_API_KEY.items():
  433. if name.upper().replace(" ", "").replace("-", "") == model_upper:
  434. return key
  435. return MODEL_TO_API_KEY.get(model)
  436. @staticmethod
  437. def _version_tuple(v: str) -> tuple[int, ...]:
  438. parts = [int(x) for x in v.split(".")]
  439. while len(parts) < 4:
  440. parts.append(0)
  441. return tuple(parts)
  442. async def get_available_versions(self, model: str) -> list[FirmwareVersion]:
  443. """
  444. Get all announced firmware versions for a model, newest first.
  445. Merges the wiki release history (list of version strings) with the
  446. download page JSON (which provides download URLs + release notes).
  447. Versions present only on the wiki have an empty download_url and
  448. should be treated as "unavailable" for file-based installation.
  449. """
  450. api_key = self._resolve_api_key(model)
  451. if not api_key:
  452. return []
  453. if api_key in self._versions_list_cache and (time.time() - self._cache_time) < CACHE_TTL:
  454. return self._versions_list_cache[api_key]
  455. wiki_versions = await self._fetch_all_versions_from_wiki(api_key)
  456. download_versions = await self._fetch_all_versions_from_download_page(api_key)
  457. by_version: dict[str, FirmwareVersion] = {d.version: d for d in download_versions if d.version}
  458. merged: list[FirmwareVersion] = []
  459. seen: set[str] = set()
  460. for v, wiki_date in wiki_versions:
  461. if v in seen:
  462. continue
  463. seen.add(v)
  464. if v in by_version:
  465. merged.append(by_version[v])
  466. else:
  467. merged.append(FirmwareVersion(version=v, download_url="", release_time=wiki_date))
  468. for d in download_versions:
  469. if d.version and d.version not in seen:
  470. seen.add(d.version)
  471. merged.append(d)
  472. try:
  473. merged.sort(key=lambda fv: self._version_tuple(fv.version), reverse=True)
  474. except (ValueError, AttributeError):
  475. pass
  476. self._versions_list_cache[api_key] = merged
  477. self._cache_time = time.time()
  478. return merged
  479. async def get_version_info(self, model: str, version: str) -> FirmwareVersion | None:
  480. """Find a specific version's info (including download URL) for a model."""
  481. for v in await self.get_available_versions(model):
  482. if v.version == version:
  483. return v
  484. return None
  485. async def check_for_update(self, model: str, current_version: str) -> dict:
  486. """
  487. Check if a firmware update is available for a printer.
  488. Args:
  489. model: Printer model name
  490. current_version: Currently installed firmware version
  491. Returns:
  492. Dict with update info:
  493. - update_available: bool
  494. - current_version: str
  495. - latest_version: str or None
  496. - download_url: str or None
  497. - release_notes: str or None
  498. """
  499. result = {
  500. "update_available": False,
  501. "current_version": current_version,
  502. "latest_version": None,
  503. "download_url": None,
  504. "release_notes": None,
  505. "available_versions": [],
  506. }
  507. available = await self.get_available_versions(model)
  508. result["available_versions"] = [
  509. {
  510. "version": v.version,
  511. "download_url": v.download_url or None,
  512. "file_available": bool(v.download_url),
  513. "release_notes": v.release_notes,
  514. "release_time": v.release_time,
  515. }
  516. for v in available
  517. ]
  518. if not current_version:
  519. return result
  520. latest = available[0] if available else await self.get_latest_version(model)
  521. if not latest:
  522. return result
  523. result["latest_version"] = latest.version
  524. result["download_url"] = latest.download_url or None
  525. result["release_notes"] = latest.release_notes
  526. # Compare versions (format: XX.XX.XX.XX)
  527. try:
  528. current_parts = [int(x) for x in current_version.split(".")]
  529. latest_parts = [int(x) for x in latest.version.split(".")]
  530. # Pad to same length
  531. while len(current_parts) < 4:
  532. current_parts.append(0)
  533. while len(latest_parts) < 4:
  534. latest_parts.append(0)
  535. result["update_available"] = latest_parts > current_parts
  536. except (ValueError, AttributeError):
  537. logger.warning("Could not compare versions: %s vs %s", current_version, latest.version)
  538. return result
  539. async def get_all_latest_versions(self) -> dict[str, FirmwareVersion]:
  540. """
  541. Fetch latest firmware versions for all known printer models.
  542. Returns:
  543. Dict mapping API key to FirmwareVersion
  544. """
  545. results = {}
  546. for api_key in API_KEY_TO_DEV_MODEL:
  547. version = await self._fetch_firmware_versions(api_key)
  548. if version:
  549. results[api_key] = version
  550. return results
  551. def _get_firmware_cache_dir(self) -> Path:
  552. """Get the firmware cache directory, creating it if needed."""
  553. cache_dir = _data_dir / "firmware"
  554. cache_dir.mkdir(parents=True, exist_ok=True)
  555. return cache_dir
  556. async def get_firmware_file_info(self, model: str, version: str | None = None) -> dict | None:
  557. """
  558. Get information about a firmware file for a model.
  559. If `version` is provided, returns info for that specific version (must be
  560. available on the download page). Otherwise returns info for the latest version.
  561. """
  562. if version:
  563. target = await self.get_version_info(model, version)
  564. else:
  565. target = await self.get_latest_version(model)
  566. if not target or not target.download_url:
  567. return None
  568. url_parts = target.download_url.split("/")
  569. filename = url_parts[-1] if url_parts else f"firmware_{model}.bin"
  570. return {
  571. "download_url": target.download_url,
  572. "version": target.version,
  573. "filename": filename,
  574. "release_notes": target.release_notes,
  575. }
  576. async def download_firmware(
  577. self,
  578. model: str,
  579. progress_callback: Callable[[int, int, str], None] | None = None,
  580. version: str | None = None,
  581. ) -> Path | None:
  582. """
  583. Download firmware file for a printer model.
  584. Args:
  585. model: Printer model name (e.g., "X1C", "P1S", "H2D")
  586. progress_callback: Optional callback(bytes_downloaded, total_bytes, status_message)
  587. Returns:
  588. Path to downloaded firmware file, or None on failure
  589. """
  590. if version:
  591. latest = await self.get_version_info(model, version)
  592. else:
  593. latest = await self.get_latest_version(model)
  594. if not latest or not latest.download_url:
  595. logger.warning("No firmware download URL available for model %s version %s", model, version)
  596. return None
  597. # Extract original filename from URL (must preserve for SD card update)
  598. url_parts = latest.download_url.split("/")
  599. original_filename = url_parts[-1] if url_parts else f"firmware_{model}.bin"
  600. # Check if already cached (using original filename so SD card gets the right name)
  601. cached_path = self._get_firmware_cache_dir() / original_filename
  602. if cached_path.exists():
  603. logger.info("Using cached firmware: %s", cached_path)
  604. return cached_path
  605. # Download to temp file first
  606. temp_path = self._get_firmware_cache_dir() / f".downloading_{original_filename}"
  607. try:
  608. logger.info("Downloading firmware from %s", latest.download_url)
  609. if progress_callback:
  610. progress_callback(0, 0, "Starting download...")
  611. async with self._client.stream("GET", latest.download_url) as response:
  612. if response.status_code != 200:
  613. logger.error("Firmware download failed with status %s", response.status_code)
  614. return None
  615. total_size = int(response.headers.get("content-length", 0))
  616. downloaded = 0
  617. with open(temp_path, "wb") as f:
  618. async for chunk in response.aiter_bytes(chunk_size=65536):
  619. f.write(chunk)
  620. downloaded += len(chunk)
  621. if progress_callback:
  622. progress_callback(downloaded, total_size, "Downloading firmware...")
  623. # Move temp to final path, preserving original filename
  624. temp_path.rename(cached_path)
  625. logger.info("Firmware downloaded successfully: %s", cached_path)
  626. if progress_callback:
  627. progress_callback(downloaded, total_size, "Download complete")
  628. return cached_path
  629. except Exception as e:
  630. logger.error("Firmware download failed: %s", e)
  631. if temp_path.exists():
  632. try:
  633. temp_path.unlink()
  634. except OSError:
  635. pass # Best-effort cleanup of failed download temp file
  636. return None
  637. async def close(self):
  638. """Close the HTTP client."""
  639. await self._client.aclose()
  640. # Singleton instance
  641. _firmware_service: FirmwareCheckService | None = None
  642. def get_firmware_service() -> FirmwareCheckService:
  643. """Get the singleton firmware check service instance."""
  644. global _firmware_service
  645. if _firmware_service is None:
  646. _firmware_service = FirmwareCheckService()
  647. return _firmware_service