firmware_check.py 31 KB

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