firmware_check.py 29 KB

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