bambu_cloud.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  1. """
  2. Bambu Lab Cloud API Service
  3. Handles authentication and profile management with Bambu Lab's cloud services.
  4. """
  5. import hashlib
  6. import logging
  7. import time
  8. from collections.abc import Awaitable, Callable
  9. from datetime import datetime, timezone
  10. import httpx
  11. logger = logging.getLogger(__name__)
  12. BAMBU_API_BASE = "https://api.bambulab.com"
  13. BAMBU_API_BASE_CN = "https://api.bambulab.cn"
  14. # How long a "Bambu still accepts this token" answer is trusted before we ask
  15. # again. ``/cloud/status`` is polled by several components, so validating on
  16. # every call would put a Bambu round-trip behind every settings render; a token
  17. # does not expire on a five-minute boundary, so caching that long is free.
  18. _VALIDATION_TTL_SECONDS = 300
  19. # token digest -> (monotonic deadline, accepted?). Keyed by digest so a token
  20. # never sits in a process-wide dict in the clear.
  21. _validation_cache: dict[str, tuple[float, bool]] = {}
  22. def _token_digest(token: str) -> str:
  23. return hashlib.sha256(token.encode("utf-8")).hexdigest()
  24. def is_expiry_401(response: httpx.Response) -> bool:
  25. """Whether a 401 is Bambu's genuine "token expired" signal.
  26. Bambu answers an expired/revoked token with ``{"code":4,"error":"Please
  27. login.","message":""}``. Not every 401 means that: individual endpoints
  28. return 401 for resource-, region- or scope-specific reasons, and a working
  29. token still draws the occasional transient 401 (Cloudflare edge, a brief
  30. backend blip). Treating *any* 401 as a dead credential signs the user out on
  31. a single stray rejection — the #2562 follow-up regression. We trust only the
  32. documented expiry body, so a benign 401 no longer nukes the whole cloud
  33. integration. An unparseable / unsigned 401 is deliberately NOT expiry.
  34. Shared by the Bambu Cloud and MakerWorld services — both carry the same
  35. token and see the same expiry body.
  36. """
  37. try:
  38. body = response.json()
  39. except Exception:
  40. return False
  41. if not isinstance(body, dict):
  42. return False
  43. if body.get("code") == 4:
  44. return True
  45. text = f"{body.get('error', '')} {body.get('message', '')}".lower()
  46. return "please login" in text
  47. def invalidate_validation_cache(token: str | None = None) -> None:
  48. """Drop cached validation verdicts.
  49. Called on login/logout so a fresh token isn't judged by the previous one's
  50. cached verdict, and so a re-login clears a cached rejection immediately
  51. rather than leaving the user staring at "sign-in expired" for five minutes.
  52. """
  53. if token is None:
  54. _validation_cache.clear()
  55. else:
  56. _validation_cache.pop(_token_digest(token), None)
  57. # Client identity sent to Bambu Lab's cloud services. We identify honestly as
  58. # Bambuddy — the URL in parens makes the source unambiguous so Bambu can
  59. # distinguish our traffic from impersonators. This is the opposite of what the
  60. # OrcaSlicer fork was called out for in the May 2026 Bambu Lab blog post
  61. # ("Setting the record straight on cloud access and community"): we do not
  62. # introduce ourselves as official Bambu Studio.
  63. _USER_AGENT = "Bambuddy/1.0 (+https://github.com/maziggy/bambuddy)"
  64. # Cloudflare protection on Bambu Lab's edge intermittently returns interstitials /
  65. # challenges instead of the JSON the API normally produces (issue #1575). The
  66. # parse error that results is opaque — these helpers detect the CF markers so
  67. # we can surface an actionable message instead of "Invalid response from Bambu Cloud".
  68. _CF_INTERSTITIAL_USER_MESSAGE = (
  69. "Bambu Cloud is temporarily blocking automated requests from your network. "
  70. "This is a Cloudflare protection on Bambu Lab's side, not a Bambuddy issue. "
  71. "Please wait a few minutes and try again. If it persists, signing in to "
  72. "bambulab.com once from a browser on the same network usually clears the "
  73. "challenge."
  74. )
  75. def _detect_cloudflare_challenge(response) -> str | None:
  76. """Return a user-actionable message when the response is a Cloudflare
  77. challenge / mitigation page instead of the JSON the API normally returns.
  78. Triggers on any of:
  79. - body contains "Just a moment..." (CF interactive challenge title)
  80. - body contains "challenges.cloudflare.com" (CF turnstile widget src)
  81. - HTTP 403 with a "cf-mitigated" response header (CF blocked)
  82. - HTTP 503 with a "cf-ray" response header (CF Under Attack mode)
  83. Returns None when the response doesn't look like a CF challenge — callers
  84. fall through to their existing error path.
  85. """
  86. try:
  87. body = response.text or ""
  88. except Exception:
  89. body = ""
  90. if "Just a moment..." in body or "challenges.cloudflare.com" in body:
  91. return _CF_INTERSTITIAL_USER_MESSAGE
  92. try:
  93. status = int(getattr(response, "status_code", 0) or 0)
  94. except (TypeError, ValueError):
  95. status = 0
  96. headers = getattr(response, "headers", {}) or {}
  97. if status == 403 and "cf-mitigated" in headers:
  98. return _CF_INTERSTITIAL_USER_MESSAGE
  99. if status == 503 and "cf-ray" in headers:
  100. return _CF_INTERSTITIAL_USER_MESSAGE
  101. return None
  102. # The `/v1/iot-service/api/slicer/setting` endpoint subtree — the plural GET
  103. # for the list, the singular GET/DELETE for a specific preset by setting_id, and
  104. # the POST for create — requires a `version` query parameter in the XX.YY.ZZ.WW
  105. # format Bambu Studio releases use. Without it the API returns HTTP 400
  106. # "field 'version' is not set"; non-matching formats like "bambuddy-1.0" return
  107. # HTTP 422 "Invalid input parameters". However, Bambu's server accepts ANY value
  108. # within that format — it doesn't validate against a release manifest. We
  109. # therefore use a neutral "1.0.0.0" placeholder that does not impersonate any
  110. # real Bambu Studio release. Our client identity is in the User-Agent header.
  111. _SLICER_API_VERSION = "1.0.0.0"
  112. class BambuCloudError(Exception):
  113. """Base exception for Bambu Cloud errors.
  114. ``status_code`` carries the upstream HTTP status when the failure came from
  115. a response rather than from the transport, so callers can tell an expected
  116. "this preset isn't in the catalog" 400 apart from an expired token or a
  117. cloud outage. It stays ``None`` for connection-level failures.
  118. """
  119. def __init__(self, message: str, *, status_code: int | None = None):
  120. super().__init__(message)
  121. self.status_code = status_code
  122. class BambuCloudAuthError(BambuCloudError):
  123. """Authentication related errors."""
  124. pass
  125. _shared_http_client: httpx.AsyncClient | None = None
  126. def set_shared_http_client(client: httpx.AsyncClient | None) -> None:
  127. """Register an app-scoped ``httpx.AsyncClient`` so per-request
  128. ``BambuCloudService`` instances can reuse its connection pool.
  129. Pass ``None`` during shutdown to unregister. The service only holds a
  130. reference (never closes a client it does not own), so region + token
  131. state still stays per-request — this only shares the transport pool.
  132. """
  133. global _shared_http_client
  134. _shared_http_client = client
  135. class BambuCloudService:
  136. """Service for interacting with Bambu Lab Cloud API."""
  137. def __init__(
  138. self,
  139. region: str = "global",
  140. client: httpx.AsyncClient | None = None,
  141. on_auth_failure: Callable[[], Awaitable[None]] | None = None,
  142. ):
  143. self.base_url = BAMBU_API_BASE if region == "global" else BAMBU_API_BASE_CN
  144. self.access_token: str | None = None
  145. self.refresh_token: str | None = None
  146. self.token_expiry: datetime | None = None
  147. # Fired once when Bambu answers 401 to a call we made with a stored
  148. # token — the credential is dead and the caller wants to record that.
  149. # ``build_authenticated_cloud`` wires this to the persisted flag, so
  150. # every route that builds a service through it gets invalidation for
  151. # free rather than each one having to notice 401s for itself.
  152. self._on_auth_failure = on_auth_failure
  153. self._auth_failure_reported = False
  154. # Prefer an explicitly-injected client (tests), else fall back to the
  155. # app-scoped shared client (production), and finally create our own so
  156. # scripts / tests that skip the lifespan still get a working service.
  157. if client is not None:
  158. self._client = client
  159. self._owns_client = False
  160. elif _shared_http_client is not None:
  161. self._client = _shared_http_client
  162. self._owns_client = False
  163. else:
  164. self._client = httpx.AsyncClient(timeout=30.0)
  165. self._owns_client = True
  166. @property
  167. def is_authenticated(self) -> bool:
  168. """Whether a credential is *loaded* — NOT whether Bambu accepts it.
  169. Bambu's access token is opaque (no JWT claims to read an expiry out
  170. of), so the only authority on whether it still works is Bambu. This
  171. used to pretend otherwise: ``set_token`` stamped ``token_expiry =
  172. now + 30 days`` every time a stored token was loaded, which made the
  173. expiry check reset on every request and this property incapable of
  174. ever returning False. The UI reported "connected" indefinitely while
  175. every cloud call 401'd (#2562 follow-up).
  176. ``token_expiry`` is now only set when we genuinely know it. Callers
  177. that need to know the token still *works* must ask Bambu — see
  178. :meth:`validate_token` — or react to the 401 that surfaces.
  179. """
  180. if not self.access_token:
  181. return False
  182. return not (self.token_expiry and datetime.now(timezone.utc) > self.token_expiry)
  183. async def _note_response(self, response: httpx.Response) -> bool:
  184. """Record Bambu's genuine token-expiry 401 as "this credential is dead".
  185. Returns ``True`` only for the real expiry signal (see
  186. :meth:`_is_expiry_401`); a plain/transient 401 returns ``False`` and is
  187. left alone so it can't durably sign the user out. The durable flag is
  188. written at most once per service instance so a route making several
  189. calls doesn't write it repeatedly.
  190. """
  191. if response.status_code != 401:
  192. return False
  193. if not is_expiry_401(response):
  194. logger.info(
  195. "Bambu Cloud returned 401 without the expiry signature — treating as transient, "
  196. "not signing the stored token out"
  197. )
  198. return False
  199. if self._on_auth_failure is None or self._auth_failure_reported:
  200. return True
  201. self._auth_failure_reported = True
  202. if self.access_token:
  203. _validation_cache[_token_digest(self.access_token)] = (
  204. time.monotonic() + _VALIDATION_TTL_SECONDS,
  205. False,
  206. )
  207. try:
  208. await self._on_auth_failure()
  209. except Exception:
  210. # Recording the failure is best-effort — the caller still needs the
  211. # real error (a 401) rather than a bookkeeping exception on top.
  212. logger.exception("Failed to record Bambu Cloud auth failure")
  213. return True
  214. async def validate_token(self) -> bool | None:
  215. """Ask Bambu whether the loaded token is still accepted.
  216. ``True`` accepted, ``False`` rejected (401), ``None`` unknown — Bambu
  217. was unreachable or answered 5xx.
  218. ``None`` must never be treated as "invalid": a Bambu outage or a
  219. Cloudflare interstitial would otherwise sign every user out of a
  220. perfectly good session. Callers report their last known state instead.
  221. """
  222. if not self.access_token:
  223. return False
  224. digest = _token_digest(self.access_token)
  225. cached = _validation_cache.get(digest)
  226. if cached and cached[0] > time.monotonic():
  227. return cached[1]
  228. try:
  229. response = await self._client.get(
  230. f"{self.base_url}/v1/design-user-service/my/preference",
  231. headers=self._get_headers(),
  232. timeout=15.0,
  233. )
  234. except httpx.HTTPError as exc:
  235. logger.info("Could not reach Bambu Cloud to validate the stored token: %s", exc)
  236. return None
  237. if response.status_code == 401:
  238. # Only a 401 carrying Bambu's expiry signature is a real sign-out.
  239. # A signature-less 401 here is transient/edge noise — report unknown
  240. # (last-known state) rather than expiring a working session.
  241. expired = await self._note_response(response)
  242. return False if expired else None
  243. if response.status_code >= 500:
  244. logger.info(
  245. "Bambu Cloud returned %s while validating the token — treating as unknown", response.status_code
  246. )
  247. return None
  248. if response.status_code != 200:
  249. # 4xx that isn't 401 (403, 418 Cloudflare challenge, 429): the token
  250. # itself was not rejected, so don't declare it dead.
  251. logger.info(
  252. "Bambu Cloud returned %s while validating the token — treating as unknown", response.status_code
  253. )
  254. return None
  255. _validation_cache[digest] = (time.monotonic() + _VALIDATION_TTL_SECONDS, True)
  256. return True
  257. def _get_headers(self) -> dict:
  258. """Get headers for authenticated requests."""
  259. headers = {
  260. "Content-Type": "application/json",
  261. "User-Agent": _USER_AGENT,
  262. }
  263. if self.access_token:
  264. headers["Authorization"] = f"Bearer {self.access_token}"
  265. return headers
  266. async def login_request(self, email: str, password: str) -> dict:
  267. """
  268. Initiate login - this will trigger either email verification or TOTP prompt.
  269. Returns dict with login status, verification type, and tfaKey if needed.
  270. """
  271. try:
  272. response = await self._client.post(
  273. f"{self.base_url}/v1/user-service/user/login",
  274. headers={"Content-Type": "application/json"},
  275. json={
  276. "account": email,
  277. "password": password,
  278. },
  279. )
  280. try:
  281. data = response.json()
  282. except Exception as json_err:
  283. logger.error("Failed to parse login response: %s, body: %s", json_err, response.text[:500])
  284. cf_message = _detect_cloudflare_challenge(response)
  285. return {
  286. "success": False,
  287. "needs_verification": False,
  288. "message": cf_message or "Invalid response from Bambu Cloud",
  289. }
  290. logger.debug(
  291. f"Login response: status={response.status_code}, loginType={data.get('loginType')}, hasTfaKey={'tfaKey' in data}"
  292. )
  293. if response.status_code == 200:
  294. login_type = data.get("loginType")
  295. tfa_key = data.get("tfaKey")
  296. # TOTP authentication required
  297. if login_type == "tfa" or (tfa_key and login_type != "verifyCode"):
  298. return {
  299. "success": False,
  300. "needs_verification": True,
  301. "verification_type": "totp",
  302. "tfa_key": tfa_key,
  303. "message": "Enter the code from your authenticator app",
  304. }
  305. # Email verification required
  306. if login_type == "verifyCode":
  307. return {
  308. "success": False,
  309. "needs_verification": True,
  310. "verification_type": "email",
  311. "tfa_key": None,
  312. "message": "Verification code sent to email",
  313. }
  314. # Direct login success (rare, usually needs 2FA)
  315. if "accessToken" in data:
  316. self._set_tokens(data)
  317. return {"success": True, "needs_verification": False, "message": "Login successful"}
  318. # Handle specific error codes
  319. error_msg = data.get("message") or data.get("error") or "Login failed"
  320. return {"success": False, "needs_verification": False, "message": error_msg}
  321. except Exception as e:
  322. logger.error("Login request failed: %s", e)
  323. raise BambuCloudAuthError(f"Login request failed: {e}")
  324. async def verify_code(self, email: str, code: str) -> dict:
  325. """
  326. Complete login with email verification code.
  327. """
  328. try:
  329. response = await self._client.post(
  330. f"{self.base_url}/v1/user-service/user/login",
  331. headers={"Content-Type": "application/json"},
  332. json={
  333. "account": email,
  334. "code": code,
  335. },
  336. )
  337. try:
  338. data = response.json()
  339. except Exception as json_err:
  340. logger.error("Failed to parse email-verify response: %s, body: %s", json_err, response.text[:500])
  341. cf_message = _detect_cloudflare_challenge(response)
  342. return {"success": False, "message": cf_message or "Invalid response from Bambu Cloud"}
  343. logger.debug("Email verify response: status=%s, hasToken=%s", response.status_code, "accessToken" in data)
  344. if response.status_code == 200 and "accessToken" in data:
  345. self._set_tokens(data)
  346. return {"success": True, "message": "Login successful"}
  347. return {"success": False, "message": data.get("message", "Verification failed")}
  348. except Exception as e:
  349. logger.error("Email verification failed: %s", e)
  350. raise BambuCloudAuthError(f"Verification failed: {e}")
  351. async def verify_totp(self, tfa_key: str, code: str) -> dict:
  352. """
  353. Complete login with TOTP code from authenticator app.
  354. Args:
  355. tfa_key: The tfaKey returned from initial login request
  356. code: 6-digit TOTP code from authenticator app
  357. """
  358. try:
  359. # TFA endpoint is on bambulab.com, NOT api.bambulab.com.
  360. # We previously sent a Chrome User-Agent plus Origin/Referer headers
  361. # under the assumption Cloudflare would block bot-identified
  362. # requests. Verified 2026-05-12 via curl that the endpoint accepts
  363. # honest "Bambuddy/X.Y.Z" identification cleanly (HTTP 400 with the
  364. # expected application-level "Login failed" JSON, no Cloudflare
  365. # interstitial). Browser-impersonation removed to stay clearly on
  366. # the right side of Bambu Lab's "no falsified client identity" line.
  367. tfa_url = "https://bambulab.com/api/sign-in/tfa"
  368. if "bambulab.cn" in self.base_url:
  369. tfa_url = "https://bambulab.cn/api/sign-in/tfa"
  370. response = await self._client.post(
  371. tfa_url,
  372. headers={
  373. "Content-Type": "application/json",
  374. "User-Agent": _USER_AGENT,
  375. "Accept": "application/json",
  376. },
  377. json={
  378. "tfaKey": tfa_key,
  379. "tfaCode": code,
  380. },
  381. )
  382. logger.debug(
  383. f"TOTP verify response: status={response.status_code}, body={response.text[:200] if response.text else '(empty)'}"
  384. )
  385. # Handle empty response
  386. if not response.text or not response.text.strip():
  387. logger.warning("TOTP verification returned empty response (status %s)", response.status_code)
  388. return {"success": False, "message": "Bambu Cloud returned empty response. Please try again."}
  389. try:
  390. data = response.json()
  391. except Exception as json_err:
  392. logger.error("Failed to parse TOTP response: %s, body: %s", json_err, response.text[:500])
  393. cf_message = _detect_cloudflare_challenge(response)
  394. return {"success": False, "message": cf_message or "Invalid response from Bambu Cloud"}
  395. # Token might be in accessToken, token field, or cookies
  396. access_token = data.get("accessToken") or data.get("token")
  397. # Also check cookies for token
  398. if not access_token:
  399. for cookie in response.cookies:
  400. if "token" in cookie.lower():
  401. access_token = response.cookies.get(cookie)
  402. break
  403. if response.status_code == 200 and access_token:
  404. self.access_token = access_token
  405. self.refresh_token = data.get("refreshToken")
  406. # Expiry left unset: Bambu does not tell us when the token dies
  407. # and the token is opaque, so any value here would be invented.
  408. self.token_expiry = None
  409. invalidate_validation_cache(access_token)
  410. return {"success": True, "message": "Login successful"}
  411. # Provide helpful error message
  412. error_msg = data.get("message", "")
  413. if "expired" in error_msg.lower():
  414. return {"success": False, "message": "TOTP session expired. Please try logging in again."}
  415. if not error_msg:
  416. error_msg = f"TOTP verification failed (status {response.status_code})"
  417. return {"success": False, "message": error_msg}
  418. except Exception as e:
  419. logger.error("TOTP verification failed: %s", e)
  420. # Return error instead of raising - don't trigger 401/500
  421. return {"success": False, "message": f"TOTP verification error: {e}"}
  422. def _set_tokens(self, data: dict):
  423. """Set tokens from a login response.
  424. No expiry is recorded. Bambu's login response carries no expiry, and
  425. the access token is opaque, so the old ``now + 30 days`` was a guess
  426. that outlived its own accuracy — see :attr:`is_authenticated`.
  427. """
  428. self.access_token = data.get("accessToken")
  429. self.refresh_token = data.get("refreshToken")
  430. self.token_expiry = None
  431. if self.access_token:
  432. invalidate_validation_cache(self.access_token)
  433. def set_token(self, access_token: str):
  434. """Load a stored access token.
  435. This used to stamp ``token_expiry = now + 30 days`` — re-derived from
  436. *now* on every request, for a token of entirely unknown age. That made
  437. ``is_authenticated`` a permanent True and is why Bambuddy went on
  438. reporting "connected" long after Bambu had stopped accepting the token.
  439. A stored token's remaining life is unknowable from the token alone, so
  440. we record no expiry and let Bambu be the authority.
  441. """
  442. self.access_token = access_token
  443. self.token_expiry = None
  444. def logout(self):
  445. """Clear authentication state."""
  446. self.access_token = None
  447. self.refresh_token = None
  448. self.token_expiry = None
  449. async def get_user_profile(self) -> dict:
  450. """Get user profile information."""
  451. if not self.is_authenticated:
  452. raise BambuCloudAuthError("Not authenticated")
  453. try:
  454. response = await self._client.get(
  455. f"{self.base_url}/v1/design-user-service/my/preference", headers=self._get_headers()
  456. )
  457. if response.status_code == 200:
  458. return response.json()
  459. raise BambuCloudError(f"Failed to get profile: {response.status_code}")
  460. except httpx.RequestError as e:
  461. raise BambuCloudError(f"Request failed: {e}")
  462. async def get_slicer_settings(self, version: str = _SLICER_API_VERSION) -> dict:
  463. """
  464. Get all slicer settings (filament, printer, process presets).
  465. Args:
  466. version: Slicer version string. Bambu's API requires the XX.YY.ZZ.WW
  467. format but does not validate against a release manifest — we
  468. default to the neutral _SLICER_API_VERSION placeholder so we
  469. never claim to be a specific Bambu Studio build. Callers should
  470. normally use the default.
  471. """
  472. if not self.is_authenticated:
  473. raise BambuCloudAuthError("Not authenticated")
  474. try:
  475. response = await self._client.get(
  476. f"{self.base_url}/v1/iot-service/api/slicer/setting",
  477. headers=self._get_headers(),
  478. params={"version": version},
  479. )
  480. data = response.json()
  481. await self._note_response(response)
  482. if response.status_code == 200:
  483. return data
  484. raise BambuCloudError(f"Failed to get settings: {response.status_code}")
  485. except httpx.RequestError as e:
  486. raise BambuCloudError(f"Request failed: {e}")
  487. async def get_setting_detail(self, setting_id: str) -> dict:
  488. """Get detailed information for a specific setting/preset."""
  489. if not self.is_authenticated:
  490. raise BambuCloudAuthError("Not authenticated")
  491. try:
  492. response = await self._client.get(
  493. f"{self.base_url}/v1/iot-service/api/slicer/setting/{setting_id}",
  494. headers=self._get_headers(),
  495. params={"version": _SLICER_API_VERSION},
  496. )
  497. await self._note_response(response)
  498. if response.status_code == 200:
  499. return response.json()
  500. # Include body so a future contract change is self-diagnostic from logs.
  501. body = (response.text or "")[:200]
  502. raise BambuCloudError(
  503. f"Failed to get setting detail: {response.status_code} {body}",
  504. status_code=response.status_code,
  505. )
  506. except httpx.RequestError as e:
  507. raise BambuCloudError(f"Request failed: {e}")
  508. async def create_setting(
  509. self, preset_type: str, name: str, base_id: str, setting: dict, version: str = "2.0.0.0"
  510. ) -> dict:
  511. """
  512. Create a new slicer preset/setting.
  513. Args:
  514. preset_type: Type of preset - "filament", "print", or "printer"
  515. name: Display name for the preset
  516. base_id: Base preset ID to inherit from (e.g., "GFSA00")
  517. setting: Dict of setting key-value pairs (only modified values from base)
  518. version: Version string for the preset (default: "2.0.0.0")
  519. Returns:
  520. Created preset data including the new setting_id
  521. """
  522. if not self.is_authenticated:
  523. raise BambuCloudAuthError("Not authenticated")
  524. try:
  525. # Add timestamp if not present
  526. import time
  527. if "updated_time" not in setting:
  528. setting["updated_time"] = str(int(time.time()))
  529. payload = {
  530. "type": preset_type,
  531. "name": name,
  532. "version": version,
  533. "base_id": base_id,
  534. "setting": setting,
  535. }
  536. response = await self._client.post(
  537. f"{self.base_url}/v1/iot-service/api/slicer/setting", headers=self._get_headers(), json=payload
  538. )
  539. data = response.json()
  540. await self._note_response(response)
  541. if response.status_code in (200, 201):
  542. return data
  543. error_msg = data.get("message") or data.get("error") or f"HTTP {response.status_code}"
  544. raise BambuCloudError(f"Failed to create setting: {error_msg}")
  545. except httpx.RequestError as e:
  546. raise BambuCloudError(f"Request failed: {e}")
  547. async def update_setting(self, setting_id: str, name: str | None = None, setting: dict | None = None) -> dict:
  548. """
  549. Update an existing slicer preset/setting.
  550. Note: Bambu Cloud API doesn't support true updates. Instead, we:
  551. 1. Fetch the current setting metadata (type, base_id, version)
  552. 2. Use the provided settings as the new complete settings (NOT merged)
  553. 3. Delete the old setting first (to avoid name conflicts)
  554. 4. Create a new setting via POST
  555. Args:
  556. setting_id: ID of the preset to update
  557. name: New display name (optional)
  558. setting: Dict of setting key-value pairs - this REPLACES the old settings entirely
  559. Returns:
  560. Updated preset data with new setting_id
  561. """
  562. if not self.is_authenticated:
  563. raise BambuCloudAuthError("Not authenticated")
  564. try:
  565. # Fetch current setting to get metadata (type, base_id, version)
  566. current = await self.get_setting_detail(setting_id)
  567. preset_type = current.get("type", "filament")
  568. # Use provided settings directly (complete replacement, not merge)
  569. # This allows the frontend to edit the full settings JSON
  570. if setting is not None:
  571. updated_setting = setting.copy()
  572. else:
  573. updated_setting = current.get("setting", {}).copy()
  574. # Extract name from settings_id field in the JSON, or use provided name, or fall back to current
  575. # The settings_id field contains the name in quotes, e.g., '"My Preset Name"'
  576. settings_id_key = {
  577. "filament": "filament_settings_id",
  578. "print": "print_settings_id",
  579. "printer": "printer_settings_id",
  580. }.get(preset_type, "filament_settings_id")
  581. settings_id_value = updated_setting.get(settings_id_key, "")
  582. if settings_id_value:
  583. # Remove surrounding quotes if present (e.g., '"foo"' -> 'foo')
  584. updated_name = settings_id_value.strip('"')
  585. elif name is not None:
  586. updated_name = name
  587. else:
  588. updated_name = current.get("name", "Untitled")
  589. # Update the timestamp
  590. import time
  591. updated_setting["updated_time"] = str(int(time.time()))
  592. # Ensure settings_id field matches the name
  593. updated_setting[settings_id_key] = f'"{updated_name}"'
  594. # Delete the old setting FIRST to avoid name conflicts
  595. await self.delete_setting(setting_id)
  596. # Create new setting via POST
  597. payload = {
  598. "type": preset_type,
  599. "name": updated_name,
  600. "version": current.get("version", "2.0.0.0"),
  601. "base_id": current.get("base_id", ""),
  602. "setting": updated_setting,
  603. }
  604. response = await self._client.post(
  605. f"{self.base_url}/v1/iot-service/api/slicer/setting", headers=self._get_headers(), json=payload
  606. )
  607. data = response.json()
  608. await self._note_response(response)
  609. if response.status_code == 200:
  610. return data
  611. error_msg = data.get("message") or data.get("error") or f"HTTP {response.status_code}"
  612. raise BambuCloudError(f"Failed to update setting: {error_msg}")
  613. except httpx.RequestError as e:
  614. raise BambuCloudError(f"Request failed: {e}")
  615. async def delete_setting(self, setting_id: str) -> dict:
  616. """
  617. Delete a slicer preset/setting.
  618. Args:
  619. setting_id: ID of the preset to delete
  620. Returns:
  621. Deletion confirmation
  622. """
  623. if not self.is_authenticated:
  624. raise BambuCloudAuthError("Not authenticated")
  625. try:
  626. response = await self._client.delete(
  627. f"{self.base_url}/v1/iot-service/api/slicer/setting/{setting_id}",
  628. headers=self._get_headers(),
  629. params={"version": _SLICER_API_VERSION},
  630. )
  631. await self._note_response(response)
  632. if response.status_code in (200, 204):
  633. return {"success": True, "message": "Setting deleted"}
  634. data = response.json() if response.content else {}
  635. error_msg = data.get("message") or data.get("error") or f"HTTP {response.status_code}"
  636. raise BambuCloudError(f"Failed to delete setting: {error_msg}")
  637. except httpx.RequestError as e:
  638. raise BambuCloudError(f"Request failed: {e}")
  639. async def get_devices(self) -> dict:
  640. """Get list of bound devices."""
  641. if not self.is_authenticated:
  642. raise BambuCloudAuthError("Not authenticated")
  643. try:
  644. response = await self._client.get(
  645. f"{self.base_url}/v1/iot-service/api/user/bind", headers=self._get_headers()
  646. )
  647. await self._note_response(response)
  648. if response.status_code == 200:
  649. return response.json()
  650. raise BambuCloudError(f"Failed to get devices: {response.status_code}")
  651. except httpx.RequestError as e:
  652. raise BambuCloudError(f"Request failed: {e}")
  653. async def get_firmware_version(self, device_id: str) -> dict:
  654. """
  655. Get firmware version info for a device.
  656. Returns dict with:
  657. - current_version: Installed firmware version
  658. - latest_version: Latest available firmware version
  659. - update_available: Boolean indicating if update is available
  660. - release_notes: Release notes for latest version
  661. """
  662. if not self.is_authenticated:
  663. raise BambuCloudAuthError("Not authenticated")
  664. try:
  665. response = await self._client.get(
  666. f"{self.base_url}/v1/iot-service/api/user/device/version",
  667. headers=self._get_headers(),
  668. params={"device_id": device_id},
  669. )
  670. await self._note_response(response)
  671. if response.status_code == 200:
  672. data = response.json()
  673. # API wraps response in 'data' field
  674. return data.get("data", data)
  675. raise BambuCloudError(f"Failed to get firmware version: {response.status_code}")
  676. except httpx.RequestError as e:
  677. raise BambuCloudError(f"Request failed: {e}")
  678. async def close(self):
  679. """Close the HTTP client we own. No-op when sharing an app-scoped client."""
  680. if self._owns_client:
  681. await self._client.aclose()
  682. # Previously this module exposed a process-wide ``_cloud_service`` singleton
  683. # via ``get_cloud_service()`` / ``reset_cloud_service()``. That pattern leaked
  684. # region and token state across users (a China-region login would pin the
  685. # singleton to api.bambulab.cn until the next explicit reset), so the singleton
  686. # has been removed. Callers should construct a per-request
  687. # ``BambuCloudService(region=...)`` from the stored region and ``await
  688. # cloud.close()`` it when done. See ``routes.cloud.build_authenticated_cloud``
  689. # for the standard pattern.