bambu_cloud.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  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 _fetch_csrf_token(self, web_origin: str) -> str | None:
  352. """Seed the ``bbl_csrf_token`` cookie and return its value (#2696).
  353. Bambu added double-submit CSRF protection to the ``bambulab.com`` web
  354. origin. A POST without the cookie is rejected ``403 {"error": "CSRF
  355. error: missing_cookie"}`` before the request body is looked at; with the
  356. cookie but no matching header it becomes ``missing_header``. Only
  357. ``GET /api/csrf`` mints one — the sign-in *page* sets nothing but
  358. Cloudflare's ``__cf_bm``, so landing there first does not help.
  359. The token is re-fetched per verification rather than cached: the client
  360. is process-wide and long-lived, so a stale cookie could otherwise
  361. disagree with the header we send.
  362. """
  363. try:
  364. response = await self._client.get(
  365. f"{web_origin}/api/csrf",
  366. headers={"User-Agent": _USER_AGENT, "Accept": "application/json"},
  367. )
  368. except Exception as e:
  369. logger.warning("Failed to fetch Bambu Cloud CSRF token: %s", e)
  370. return None
  371. # httpx stores the Set-Cookie on the shared jar, which is also what makes
  372. # the cookie ride along on the POST below — we only need the value here
  373. # to echo it back in the header.
  374. try:
  375. token = self._client.cookies.get("bbl_csrf_token")
  376. except Exception: # multiple cookies of the same name across domains
  377. token = None
  378. if not token:
  379. logger.warning(
  380. "Bambu Cloud CSRF endpoint returned no bbl_csrf_token (status %s)",
  381. response.status_code,
  382. )
  383. return token
  384. async def verify_totp(self, tfa_key: str, code: str) -> dict:
  385. """
  386. Complete login with TOTP code from authenticator app.
  387. Args:
  388. tfa_key: The tfaKey returned from initial login request
  389. code: 6-digit TOTP code from authenticator app
  390. """
  391. try:
  392. # TFA endpoint is on bambulab.com, NOT api.bambulab.com.
  393. # We previously sent a Chrome User-Agent plus Origin/Referer headers
  394. # under the assumption Cloudflare would block bot-identified
  395. # requests. Verified 2026-05-12 via curl that the endpoint accepts
  396. # honest "Bambuddy/X.Y.Z" identification cleanly (HTTP 400 with the
  397. # expected application-level "Login failed" JSON, no Cloudflare
  398. # interstitial). Browser-impersonation removed to stay clearly on
  399. # the right side of Bambu Lab's "no falsified client identity" line.
  400. web_origin = "https://bambulab.cn" if "bambulab.cn" in self.base_url else "https://bambulab.com"
  401. tfa_url = f"{web_origin}/api/sign-in/tfa"
  402. # #2696: the web origin is CSRF-protected (double submit). Without
  403. # both halves the endpoint 403s before it ever evaluates the code,
  404. # which surfaced to users as a permanent, misleading "Invalid code".
  405. # api.bambulab.com — where every other call in this service goes,
  406. # including the email-code 2FA path — is not gated, which is why
  407. # only TOTP sign-ins broke.
  408. csrf_token = await self._fetch_csrf_token(web_origin)
  409. if not csrf_token:
  410. return {
  411. "success": False,
  412. "message": (
  413. "Could not obtain a security token from Bambu Cloud. "
  414. "Check the server's internet access and try again."
  415. ),
  416. }
  417. response = await self._client.post(
  418. tfa_url,
  419. headers={
  420. "Content-Type": "application/json",
  421. "User-Agent": _USER_AGENT,
  422. "Accept": "application/json",
  423. # Echo of the bbl_csrf_token cookie httpx just stored. Both
  424. # halves are required; the cookie alone yields
  425. # "missing_header".
  426. "x-bbl-csrf-token": csrf_token,
  427. },
  428. json={
  429. "tfaKey": tfa_key,
  430. "tfaCode": code,
  431. },
  432. )
  433. logger.debug(
  434. f"TOTP verify response: status={response.status_code}, body={response.text[:200] if response.text else '(empty)'}"
  435. )
  436. # Handle empty response
  437. if not response.text or not response.text.strip():
  438. logger.warning("TOTP verification returned empty response (status %s)", response.status_code)
  439. return {"success": False, "message": "Bambu Cloud returned empty response. Please try again."}
  440. try:
  441. data = response.json()
  442. except Exception as json_err:
  443. logger.error("Failed to parse TOTP response: %s, body: %s", json_err, response.text[:500])
  444. cf_message = _detect_cloudflare_challenge(response)
  445. return {"success": False, "message": cf_message or "Invalid response from Bambu Cloud"}
  446. # Token might be in accessToken, token field, or cookies
  447. access_token = data.get("accessToken") or data.get("token")
  448. # Also check cookies for token
  449. if not access_token:
  450. for cookie in response.cookies:
  451. if "token" in cookie.lower():
  452. access_token = response.cookies.get(cookie)
  453. break
  454. if response.status_code == 200 and access_token:
  455. self.access_token = access_token
  456. self.refresh_token = data.get("refreshToken")
  457. # Expiry left unset: Bambu does not tell us when the token dies
  458. # and the token is opaque, so any value here would be invented.
  459. self.token_expiry = None
  460. invalidate_validation_cache(access_token)
  461. return {"success": True, "message": "Login successful"}
  462. # Provide helpful error message
  463. error_msg = data.get("message", "")
  464. # A CSRF rejection means the code was never evaluated (#2696). It
  465. # used to fall through to the generic path below and read as
  466. # "Invalid code", which sent the reporter chasing clock drift and
  467. # leading-zero parsing for a request Bambu had already refused.
  468. csrf_error = data.get("error", "") if isinstance(data.get("error"), str) else ""
  469. if "csrf" in csrf_error.lower() or data.get("reason") in ("missing_cookie", "missing_header"):
  470. logger.error("Bambu Cloud rejected the TOTP request on CSRF grounds: %s", response.text[:200])
  471. return {
  472. "success": False,
  473. "message": (
  474. "Bambu Cloud rejected the sign-in request before checking your code "
  475. "(security-token error). Your code is fine — please try again."
  476. ),
  477. }
  478. if "expired" in error_msg.lower():
  479. return {"success": False, "message": "TOTP session expired. Please try logging in again."}
  480. if not error_msg:
  481. error_msg = data.get("error") or f"TOTP verification failed (status {response.status_code})"
  482. return {"success": False, "message": error_msg}
  483. except Exception as e:
  484. logger.error("TOTP verification failed: %s", e)
  485. # Return error instead of raising - don't trigger 401/500
  486. return {"success": False, "message": f"TOTP verification error: {e}"}
  487. def _set_tokens(self, data: dict):
  488. """Set tokens from a login response.
  489. No expiry is recorded. Bambu's login response carries no expiry, and
  490. the access token is opaque, so the old ``now + 30 days`` was a guess
  491. that outlived its own accuracy — see :attr:`is_authenticated`.
  492. """
  493. self.access_token = data.get("accessToken")
  494. self.refresh_token = data.get("refreshToken")
  495. self.token_expiry = None
  496. if self.access_token:
  497. invalidate_validation_cache(self.access_token)
  498. def set_token(self, access_token: str):
  499. """Load a stored access token.
  500. This used to stamp ``token_expiry = now + 30 days`` — re-derived from
  501. *now* on every request, for a token of entirely unknown age. That made
  502. ``is_authenticated`` a permanent True and is why Bambuddy went on
  503. reporting "connected" long after Bambu had stopped accepting the token.
  504. A stored token's remaining life is unknowable from the token alone, so
  505. we record no expiry and let Bambu be the authority.
  506. """
  507. self.access_token = access_token
  508. self.token_expiry = None
  509. def logout(self):
  510. """Clear authentication state."""
  511. self.access_token = None
  512. self.refresh_token = None
  513. self.token_expiry = None
  514. async def get_user_profile(self) -> dict:
  515. """Get user profile information."""
  516. if not self.is_authenticated:
  517. raise BambuCloudAuthError("Not authenticated")
  518. try:
  519. response = await self._client.get(
  520. f"{self.base_url}/v1/design-user-service/my/preference", headers=self._get_headers()
  521. )
  522. if response.status_code == 200:
  523. return response.json()
  524. raise BambuCloudError(f"Failed to get profile: {response.status_code}")
  525. except httpx.RequestError as e:
  526. raise BambuCloudError(f"Request failed: {e}")
  527. async def get_slicer_settings(self, version: str = _SLICER_API_VERSION) -> dict:
  528. """
  529. Get all slicer settings (filament, printer, process presets).
  530. Args:
  531. version: Slicer version string. Bambu's API requires the XX.YY.ZZ.WW
  532. format but does not validate against a release manifest — we
  533. default to the neutral _SLICER_API_VERSION placeholder so we
  534. never claim to be a specific Bambu Studio build. Callers should
  535. normally use the default.
  536. """
  537. if not self.is_authenticated:
  538. raise BambuCloudAuthError("Not authenticated")
  539. try:
  540. response = await self._client.get(
  541. f"{self.base_url}/v1/iot-service/api/slicer/setting",
  542. headers=self._get_headers(),
  543. params={"version": version},
  544. )
  545. data = response.json()
  546. await self._note_response(response)
  547. if response.status_code == 200:
  548. return data
  549. raise BambuCloudError(f"Failed to get settings: {response.status_code}")
  550. except httpx.RequestError as e:
  551. raise BambuCloudError(f"Request failed: {e}")
  552. async def get_setting_detail(self, setting_id: str) -> dict:
  553. """Get detailed information for a specific setting/preset."""
  554. if not self.is_authenticated:
  555. raise BambuCloudAuthError("Not authenticated")
  556. try:
  557. response = await self._client.get(
  558. f"{self.base_url}/v1/iot-service/api/slicer/setting/{setting_id}",
  559. headers=self._get_headers(),
  560. params={"version": _SLICER_API_VERSION},
  561. )
  562. await self._note_response(response)
  563. if response.status_code == 200:
  564. return response.json()
  565. # Include body so a future contract change is self-diagnostic from logs.
  566. body = (response.text or "")[:200]
  567. raise BambuCloudError(
  568. f"Failed to get setting detail: {response.status_code} {body}",
  569. status_code=response.status_code,
  570. )
  571. except httpx.RequestError as e:
  572. raise BambuCloudError(f"Request failed: {e}")
  573. async def create_setting(
  574. self, preset_type: str, name: str, base_id: str, setting: dict, version: str = "2.0.0.0"
  575. ) -> dict:
  576. """
  577. Create a new slicer preset/setting.
  578. Args:
  579. preset_type: Type of preset - "filament", "print", or "printer"
  580. name: Display name for the preset
  581. base_id: Base preset ID to inherit from (e.g., "GFSA00")
  582. setting: Dict of setting key-value pairs (only modified values from base)
  583. version: Version string for the preset (default: "2.0.0.0")
  584. Returns:
  585. Created preset data including the new setting_id
  586. """
  587. if not self.is_authenticated:
  588. raise BambuCloudAuthError("Not authenticated")
  589. try:
  590. # Add timestamp if not present
  591. import time
  592. if "updated_time" not in setting:
  593. setting["updated_time"] = str(int(time.time()))
  594. payload = {
  595. "type": preset_type,
  596. "name": name,
  597. "version": version,
  598. "base_id": base_id,
  599. "setting": setting,
  600. }
  601. response = await self._client.post(
  602. f"{self.base_url}/v1/iot-service/api/slicer/setting", headers=self._get_headers(), json=payload
  603. )
  604. data = response.json()
  605. await self._note_response(response)
  606. if response.status_code in (200, 201):
  607. return data
  608. error_msg = data.get("message") or data.get("error") or f"HTTP {response.status_code}"
  609. raise BambuCloudError(f"Failed to create setting: {error_msg}")
  610. except httpx.RequestError as e:
  611. raise BambuCloudError(f"Request failed: {e}")
  612. async def update_setting(self, setting_id: str, name: str | None = None, setting: dict | None = None) -> dict:
  613. """
  614. Update an existing slicer preset/setting.
  615. Note: Bambu Cloud API doesn't support true updates. Instead, we:
  616. 1. Fetch the current setting metadata (type, base_id, version)
  617. 2. Use the provided settings as the new complete settings (NOT merged)
  618. 3. Delete the old setting first (to avoid name conflicts)
  619. 4. Create a new setting via POST
  620. Args:
  621. setting_id: ID of the preset to update
  622. name: New display name (optional)
  623. setting: Dict of setting key-value pairs - this REPLACES the old settings entirely
  624. Returns:
  625. Updated preset data with new setting_id
  626. """
  627. if not self.is_authenticated:
  628. raise BambuCloudAuthError("Not authenticated")
  629. try:
  630. # Fetch current setting to get metadata (type, base_id, version)
  631. current = await self.get_setting_detail(setting_id)
  632. preset_type = current.get("type", "filament")
  633. # Use provided settings directly (complete replacement, not merge)
  634. # This allows the frontend to edit the full settings JSON
  635. if setting is not None:
  636. updated_setting = setting.copy()
  637. else:
  638. updated_setting = current.get("setting", {}).copy()
  639. # Extract name from settings_id field in the JSON, or use provided name, or fall back to current
  640. # The settings_id field contains the name in quotes, e.g., '"My Preset Name"'
  641. settings_id_key = {
  642. "filament": "filament_settings_id",
  643. "print": "print_settings_id",
  644. "printer": "printer_settings_id",
  645. }.get(preset_type, "filament_settings_id")
  646. settings_id_value = updated_setting.get(settings_id_key, "")
  647. if settings_id_value:
  648. # Remove surrounding quotes if present (e.g., '"foo"' -> 'foo')
  649. updated_name = settings_id_value.strip('"')
  650. elif name is not None:
  651. updated_name = name
  652. else:
  653. updated_name = current.get("name", "Untitled")
  654. # Update the timestamp
  655. import time
  656. updated_setting["updated_time"] = str(int(time.time()))
  657. # Ensure settings_id field matches the name
  658. updated_setting[settings_id_key] = f'"{updated_name}"'
  659. # Delete the old setting FIRST to avoid name conflicts
  660. await self.delete_setting(setting_id)
  661. # Create new setting via POST
  662. payload = {
  663. "type": preset_type,
  664. "name": updated_name,
  665. "version": current.get("version", "2.0.0.0"),
  666. "base_id": current.get("base_id", ""),
  667. "setting": updated_setting,
  668. }
  669. response = await self._client.post(
  670. f"{self.base_url}/v1/iot-service/api/slicer/setting", headers=self._get_headers(), json=payload
  671. )
  672. data = response.json()
  673. await self._note_response(response)
  674. if response.status_code == 200:
  675. return data
  676. error_msg = data.get("message") or data.get("error") or f"HTTP {response.status_code}"
  677. raise BambuCloudError(f"Failed to update setting: {error_msg}")
  678. except httpx.RequestError as e:
  679. raise BambuCloudError(f"Request failed: {e}")
  680. async def delete_setting(self, setting_id: str) -> dict:
  681. """
  682. Delete a slicer preset/setting.
  683. Args:
  684. setting_id: ID of the preset to delete
  685. Returns:
  686. Deletion confirmation
  687. """
  688. if not self.is_authenticated:
  689. raise BambuCloudAuthError("Not authenticated")
  690. try:
  691. response = await self._client.delete(
  692. f"{self.base_url}/v1/iot-service/api/slicer/setting/{setting_id}",
  693. headers=self._get_headers(),
  694. params={"version": _SLICER_API_VERSION},
  695. )
  696. await self._note_response(response)
  697. if response.status_code in (200, 204):
  698. return {"success": True, "message": "Setting deleted"}
  699. data = response.json() if response.content else {}
  700. error_msg = data.get("message") or data.get("error") or f"HTTP {response.status_code}"
  701. raise BambuCloudError(f"Failed to delete setting: {error_msg}")
  702. except httpx.RequestError as e:
  703. raise BambuCloudError(f"Request failed: {e}")
  704. async def get_devices(self) -> dict:
  705. """Get list of bound devices."""
  706. if not self.is_authenticated:
  707. raise BambuCloudAuthError("Not authenticated")
  708. try:
  709. response = await self._client.get(
  710. f"{self.base_url}/v1/iot-service/api/user/bind", headers=self._get_headers()
  711. )
  712. await self._note_response(response)
  713. if response.status_code == 200:
  714. return response.json()
  715. raise BambuCloudError(f"Failed to get devices: {response.status_code}")
  716. except httpx.RequestError as e:
  717. raise BambuCloudError(f"Request failed: {e}")
  718. async def get_firmware_version(self, device_id: str) -> dict:
  719. """
  720. Get firmware version info for a device.
  721. Returns dict with:
  722. - current_version: Installed firmware version
  723. - latest_version: Latest available firmware version
  724. - update_available: Boolean indicating if update is available
  725. - release_notes: Release notes for latest version
  726. """
  727. if not self.is_authenticated:
  728. raise BambuCloudAuthError("Not authenticated")
  729. try:
  730. response = await self._client.get(
  731. f"{self.base_url}/v1/iot-service/api/user/device/version",
  732. headers=self._get_headers(),
  733. params={"device_id": device_id},
  734. )
  735. await self._note_response(response)
  736. if response.status_code == 200:
  737. data = response.json()
  738. # API wraps response in 'data' field
  739. return data.get("data", data)
  740. raise BambuCloudError(f"Failed to get firmware version: {response.status_code}")
  741. except httpx.RequestError as e:
  742. raise BambuCloudError(f"Request failed: {e}")
  743. async def close(self):
  744. """Close the HTTP client we own. No-op when sharing an app-scoped client."""
  745. if self._owns_client:
  746. await self._client.aclose()
  747. # Previously this module exposed a process-wide ``_cloud_service`` singleton
  748. # via ``get_cloud_service()`` / ``reset_cloud_service()``. That pattern leaked
  749. # region and token state across users (a China-region login would pin the
  750. # singleton to api.bambulab.cn until the next explicit reset), so the singleton
  751. # has been removed. Callers should construct a per-request
  752. # ``BambuCloudService(region=...)`` from the stored region and ``await
  753. # cloud.close()`` it when done. See ``routes.cloud.build_authenticated_cloud``
  754. # for the standard pattern.