bambu_cloud.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. """
  2. Bambu Lab Cloud API Service
  3. Handles authentication and profile management with Bambu Lab's cloud services.
  4. """
  5. import logging
  6. from datetime import datetime, timedelta, timezone
  7. import httpx
  8. logger = logging.getLogger(__name__)
  9. BAMBU_API_BASE = "https://api.bambulab.com"
  10. BAMBU_API_BASE_CN = "https://api.bambulab.cn"
  11. # Client identity sent to Bambu Lab's cloud services. We identify honestly as
  12. # Bambuddy — the URL in parens makes the source unambiguous so Bambu can
  13. # distinguish our traffic from impersonators. This is the opposite of what the
  14. # OrcaSlicer fork was called out for in the May 2026 Bambu Lab blog post
  15. # ("Setting the record straight on cloud access and community"): we do not
  16. # introduce ourselves as official Bambu Studio.
  17. _USER_AGENT = "Bambuddy/1.0 (+https://github.com/maziggy/bambuddy)"
  18. # Cloudflare protection on Bambu Lab's edge intermittently returns interstitials /
  19. # challenges instead of the JSON the API normally produces (issue #1575). The
  20. # parse error that results is opaque — these helpers detect the CF markers so
  21. # we can surface an actionable message instead of "Invalid response from Bambu Cloud".
  22. _CF_INTERSTITIAL_USER_MESSAGE = (
  23. "Bambu Cloud is temporarily blocking automated requests from your network. "
  24. "This is a Cloudflare protection on Bambu Lab's side, not a Bambuddy issue. "
  25. "Please wait a few minutes and try again. If it persists, signing in to "
  26. "bambulab.com once from a browser on the same network usually clears the "
  27. "challenge."
  28. )
  29. def _detect_cloudflare_challenge(response) -> str | None:
  30. """Return a user-actionable message when the response is a Cloudflare
  31. challenge / mitigation page instead of the JSON the API normally returns.
  32. Triggers on any of:
  33. - body contains "Just a moment..." (CF interactive challenge title)
  34. - body contains "challenges.cloudflare.com" (CF turnstile widget src)
  35. - HTTP 403 with a "cf-mitigated" response header (CF blocked)
  36. - HTTP 503 with a "cf-ray" response header (CF Under Attack mode)
  37. Returns None when the response doesn't look like a CF challenge — callers
  38. fall through to their existing error path.
  39. """
  40. try:
  41. body = response.text or ""
  42. except Exception:
  43. body = ""
  44. if "Just a moment..." in body or "challenges.cloudflare.com" in body:
  45. return _CF_INTERSTITIAL_USER_MESSAGE
  46. try:
  47. status = int(getattr(response, "status_code", 0) or 0)
  48. except (TypeError, ValueError):
  49. status = 0
  50. headers = getattr(response, "headers", {}) or {}
  51. if status == 403 and "cf-mitigated" in headers:
  52. return _CF_INTERSTITIAL_USER_MESSAGE
  53. if status == 503 and "cf-ray" in headers:
  54. return _CF_INTERSTITIAL_USER_MESSAGE
  55. return None
  56. # The `/v1/iot-service/api/slicer/setting` endpoint subtree — the plural GET
  57. # for the list, the singular GET/DELETE for a specific preset by setting_id, and
  58. # the POST for create — requires a `version` query parameter in the XX.YY.ZZ.WW
  59. # format Bambu Studio releases use. Without it the API returns HTTP 400
  60. # "field 'version' is not set"; non-matching formats like "bambuddy-1.0" return
  61. # HTTP 422 "Invalid input parameters". However, Bambu's server accepts ANY value
  62. # within that format — it doesn't validate against a release manifest. We
  63. # therefore use a neutral "1.0.0.0" placeholder that does not impersonate any
  64. # real Bambu Studio release. Our client identity is in the User-Agent header.
  65. _SLICER_API_VERSION = "1.0.0.0"
  66. class BambuCloudError(Exception):
  67. """Base exception for Bambu Cloud errors."""
  68. pass
  69. class BambuCloudAuthError(BambuCloudError):
  70. """Authentication related errors."""
  71. pass
  72. _shared_http_client: httpx.AsyncClient | None = None
  73. def set_shared_http_client(client: httpx.AsyncClient | None) -> None:
  74. """Register an app-scoped ``httpx.AsyncClient`` so per-request
  75. ``BambuCloudService`` instances can reuse its connection pool.
  76. Pass ``None`` during shutdown to unregister. The service only holds a
  77. reference (never closes a client it does not own), so region + token
  78. state still stays per-request — this only shares the transport pool.
  79. """
  80. global _shared_http_client
  81. _shared_http_client = client
  82. class BambuCloudService:
  83. """Service for interacting with Bambu Lab Cloud API."""
  84. def __init__(self, region: str = "global", client: httpx.AsyncClient | None = None):
  85. self.base_url = BAMBU_API_BASE if region == "global" else BAMBU_API_BASE_CN
  86. self.access_token: str | None = None
  87. self.refresh_token: str | None = None
  88. self.token_expiry: datetime | None = None
  89. # Prefer an explicitly-injected client (tests), else fall back to the
  90. # app-scoped shared client (production), and finally create our own so
  91. # scripts / tests that skip the lifespan still get a working service.
  92. if client is not None:
  93. self._client = client
  94. self._owns_client = False
  95. elif _shared_http_client is not None:
  96. self._client = _shared_http_client
  97. self._owns_client = False
  98. else:
  99. self._client = httpx.AsyncClient(timeout=30.0)
  100. self._owns_client = True
  101. @property
  102. def is_authenticated(self) -> bool:
  103. """Check if we have a valid token."""
  104. if not self.access_token:
  105. return False
  106. return not (self.token_expiry and datetime.now(timezone.utc) > self.token_expiry)
  107. def _get_headers(self) -> dict:
  108. """Get headers for authenticated requests."""
  109. headers = {
  110. "Content-Type": "application/json",
  111. "User-Agent": _USER_AGENT,
  112. }
  113. if self.access_token:
  114. headers["Authorization"] = f"Bearer {self.access_token}"
  115. return headers
  116. async def login_request(self, email: str, password: str) -> dict:
  117. """
  118. Initiate login - this will trigger either email verification or TOTP prompt.
  119. Returns dict with login status, verification type, and tfaKey if needed.
  120. """
  121. try:
  122. response = await self._client.post(
  123. f"{self.base_url}/v1/user-service/user/login",
  124. headers={"Content-Type": "application/json"},
  125. json={
  126. "account": email,
  127. "password": password,
  128. },
  129. )
  130. try:
  131. data = response.json()
  132. except Exception as json_err:
  133. logger.error("Failed to parse login response: %s, body: %s", json_err, response.text[:500])
  134. cf_message = _detect_cloudflare_challenge(response)
  135. return {
  136. "success": False,
  137. "needs_verification": False,
  138. "message": cf_message or "Invalid response from Bambu Cloud",
  139. }
  140. logger.debug(
  141. f"Login response: status={response.status_code}, loginType={data.get('loginType')}, hasTfaKey={'tfaKey' in data}"
  142. )
  143. if response.status_code == 200:
  144. login_type = data.get("loginType")
  145. tfa_key = data.get("tfaKey")
  146. # TOTP authentication required
  147. if login_type == "tfa" or (tfa_key and login_type != "verifyCode"):
  148. return {
  149. "success": False,
  150. "needs_verification": True,
  151. "verification_type": "totp",
  152. "tfa_key": tfa_key,
  153. "message": "Enter the code from your authenticator app",
  154. }
  155. # Email verification required
  156. if login_type == "verifyCode":
  157. return {
  158. "success": False,
  159. "needs_verification": True,
  160. "verification_type": "email",
  161. "tfa_key": None,
  162. "message": "Verification code sent to email",
  163. }
  164. # Direct login success (rare, usually needs 2FA)
  165. if "accessToken" in data:
  166. self._set_tokens(data)
  167. return {"success": True, "needs_verification": False, "message": "Login successful"}
  168. # Handle specific error codes
  169. error_msg = data.get("message") or data.get("error") or "Login failed"
  170. return {"success": False, "needs_verification": False, "message": error_msg}
  171. except Exception as e:
  172. logger.error("Login request failed: %s", e)
  173. raise BambuCloudAuthError(f"Login request failed: {e}")
  174. async def verify_code(self, email: str, code: str) -> dict:
  175. """
  176. Complete login with email verification code.
  177. """
  178. try:
  179. response = await self._client.post(
  180. f"{self.base_url}/v1/user-service/user/login",
  181. headers={"Content-Type": "application/json"},
  182. json={
  183. "account": email,
  184. "code": code,
  185. },
  186. )
  187. try:
  188. data = response.json()
  189. except Exception as json_err:
  190. logger.error("Failed to parse email-verify response: %s, body: %s", json_err, response.text[:500])
  191. cf_message = _detect_cloudflare_challenge(response)
  192. return {"success": False, "message": cf_message or "Invalid response from Bambu Cloud"}
  193. logger.debug("Email verify response: status=%s, hasToken=%s", response.status_code, "accessToken" in data)
  194. if response.status_code == 200 and "accessToken" in data:
  195. self._set_tokens(data)
  196. return {"success": True, "message": "Login successful"}
  197. return {"success": False, "message": data.get("message", "Verification failed")}
  198. except Exception as e:
  199. logger.error("Email verification failed: %s", e)
  200. raise BambuCloudAuthError(f"Verification failed: {e}")
  201. async def verify_totp(self, tfa_key: str, code: str) -> dict:
  202. """
  203. Complete login with TOTP code from authenticator app.
  204. Args:
  205. tfa_key: The tfaKey returned from initial login request
  206. code: 6-digit TOTP code from authenticator app
  207. """
  208. try:
  209. # TFA endpoint is on bambulab.com, NOT api.bambulab.com.
  210. # We previously sent a Chrome User-Agent plus Origin/Referer headers
  211. # under the assumption Cloudflare would block bot-identified
  212. # requests. Verified 2026-05-12 via curl that the endpoint accepts
  213. # honest "Bambuddy/X.Y.Z" identification cleanly (HTTP 400 with the
  214. # expected application-level "Login failed" JSON, no Cloudflare
  215. # interstitial). Browser-impersonation removed to stay clearly on
  216. # the right side of Bambu Lab's "no falsified client identity" line.
  217. tfa_url = "https://bambulab.com/api/sign-in/tfa"
  218. if "bambulab.cn" in self.base_url:
  219. tfa_url = "https://bambulab.cn/api/sign-in/tfa"
  220. response = await self._client.post(
  221. tfa_url,
  222. headers={
  223. "Content-Type": "application/json",
  224. "User-Agent": _USER_AGENT,
  225. "Accept": "application/json",
  226. },
  227. json={
  228. "tfaKey": tfa_key,
  229. "tfaCode": code,
  230. },
  231. )
  232. logger.debug(
  233. f"TOTP verify response: status={response.status_code}, body={response.text[:200] if response.text else '(empty)'}"
  234. )
  235. # Handle empty response
  236. if not response.text or not response.text.strip():
  237. logger.warning("TOTP verification returned empty response (status %s)", response.status_code)
  238. return {"success": False, "message": "Bambu Cloud returned empty response. Please try again."}
  239. try:
  240. data = response.json()
  241. except Exception as json_err:
  242. logger.error("Failed to parse TOTP response: %s, body: %s", json_err, response.text[:500])
  243. cf_message = _detect_cloudflare_challenge(response)
  244. return {"success": False, "message": cf_message or "Invalid response from Bambu Cloud"}
  245. # Token might be in accessToken, token field, or cookies
  246. access_token = data.get("accessToken") or data.get("token")
  247. # Also check cookies for token
  248. if not access_token:
  249. for cookie in response.cookies:
  250. if "token" in cookie.lower():
  251. access_token = response.cookies.get(cookie)
  252. break
  253. if response.status_code == 200 and access_token:
  254. self.access_token = access_token
  255. self.refresh_token = data.get("refreshToken")
  256. from datetime import datetime, timedelta, timezone
  257. self.token_expiry = datetime.now(timezone.utc) + timedelta(days=30)
  258. return {"success": True, "message": "Login successful"}
  259. # Provide helpful error message
  260. error_msg = data.get("message", "")
  261. if "expired" in error_msg.lower():
  262. return {"success": False, "message": "TOTP session expired. Please try logging in again."}
  263. if not error_msg:
  264. error_msg = f"TOTP verification failed (status {response.status_code})"
  265. return {"success": False, "message": error_msg}
  266. except Exception as e:
  267. logger.error("TOTP verification failed: %s", e)
  268. # Return error instead of raising - don't trigger 401/500
  269. return {"success": False, "message": f"TOTP verification error: {e}"}
  270. def _set_tokens(self, data: dict):
  271. """Set tokens from login response."""
  272. self.access_token = data.get("accessToken")
  273. self.refresh_token = data.get("refreshToken")
  274. # Token typically valid for ~3 months, but we'll refresh more often
  275. self.token_expiry = datetime.now(timezone.utc) + timedelta(days=30)
  276. def set_token(self, access_token: str):
  277. """Set access token directly (for stored tokens)."""
  278. self.access_token = access_token
  279. self.token_expiry = datetime.now(timezone.utc) + timedelta(days=30)
  280. def logout(self):
  281. """Clear authentication state."""
  282. self.access_token = None
  283. self.refresh_token = None
  284. self.token_expiry = None
  285. async def get_user_profile(self) -> dict:
  286. """Get user profile information."""
  287. if not self.is_authenticated:
  288. raise BambuCloudAuthError("Not authenticated")
  289. try:
  290. response = await self._client.get(
  291. f"{self.base_url}/v1/design-user-service/my/preference", headers=self._get_headers()
  292. )
  293. if response.status_code == 200:
  294. return response.json()
  295. raise BambuCloudError(f"Failed to get profile: {response.status_code}")
  296. except httpx.RequestError as e:
  297. raise BambuCloudError(f"Request failed: {e}")
  298. async def get_slicer_settings(self, version: str = _SLICER_API_VERSION) -> dict:
  299. """
  300. Get all slicer settings (filament, printer, process presets).
  301. Args:
  302. version: Slicer version string. Bambu's API requires the XX.YY.ZZ.WW
  303. format but does not validate against a release manifest — we
  304. default to the neutral _SLICER_API_VERSION placeholder so we
  305. never claim to be a specific Bambu Studio build. Callers should
  306. normally use the default.
  307. """
  308. if not self.is_authenticated:
  309. raise BambuCloudAuthError("Not authenticated")
  310. try:
  311. response = await self._client.get(
  312. f"{self.base_url}/v1/iot-service/api/slicer/setting",
  313. headers=self._get_headers(),
  314. params={"version": version},
  315. )
  316. data = response.json()
  317. if response.status_code == 200:
  318. return data
  319. raise BambuCloudError(f"Failed to get settings: {response.status_code}")
  320. except httpx.RequestError as e:
  321. raise BambuCloudError(f"Request failed: {e}")
  322. async def get_setting_detail(self, setting_id: str) -> dict:
  323. """Get detailed information for a specific setting/preset."""
  324. if not self.is_authenticated:
  325. raise BambuCloudAuthError("Not authenticated")
  326. try:
  327. response = await self._client.get(
  328. f"{self.base_url}/v1/iot-service/api/slicer/setting/{setting_id}",
  329. headers=self._get_headers(),
  330. params={"version": _SLICER_API_VERSION},
  331. )
  332. if response.status_code == 200:
  333. return response.json()
  334. # Include body so a future contract change is self-diagnostic from logs.
  335. body = (response.text or "")[:200]
  336. raise BambuCloudError(f"Failed to get setting detail: {response.status_code} {body}")
  337. except httpx.RequestError as e:
  338. raise BambuCloudError(f"Request failed: {e}")
  339. async def create_setting(
  340. self, preset_type: str, name: str, base_id: str, setting: dict, version: str = "2.0.0.0"
  341. ) -> dict:
  342. """
  343. Create a new slicer preset/setting.
  344. Args:
  345. preset_type: Type of preset - "filament", "print", or "printer"
  346. name: Display name for the preset
  347. base_id: Base preset ID to inherit from (e.g., "GFSA00")
  348. setting: Dict of setting key-value pairs (only modified values from base)
  349. version: Version string for the preset (default: "2.0.0.0")
  350. Returns:
  351. Created preset data including the new setting_id
  352. """
  353. if not self.is_authenticated:
  354. raise BambuCloudAuthError("Not authenticated")
  355. try:
  356. # Add timestamp if not present
  357. import time
  358. if "updated_time" not in setting:
  359. setting["updated_time"] = str(int(time.time()))
  360. payload = {
  361. "type": preset_type,
  362. "name": name,
  363. "version": version,
  364. "base_id": base_id,
  365. "setting": setting,
  366. }
  367. response = await self._client.post(
  368. f"{self.base_url}/v1/iot-service/api/slicer/setting", headers=self._get_headers(), json=payload
  369. )
  370. data = response.json()
  371. if response.status_code in (200, 201):
  372. return data
  373. error_msg = data.get("message") or data.get("error") or f"HTTP {response.status_code}"
  374. raise BambuCloudError(f"Failed to create setting: {error_msg}")
  375. except httpx.RequestError as e:
  376. raise BambuCloudError(f"Request failed: {e}")
  377. async def update_setting(self, setting_id: str, name: str | None = None, setting: dict | None = None) -> dict:
  378. """
  379. Update an existing slicer preset/setting.
  380. Note: Bambu Cloud API doesn't support true updates. Instead, we:
  381. 1. Fetch the current setting metadata (type, base_id, version)
  382. 2. Use the provided settings as the new complete settings (NOT merged)
  383. 3. Delete the old setting first (to avoid name conflicts)
  384. 4. Create a new setting via POST
  385. Args:
  386. setting_id: ID of the preset to update
  387. name: New display name (optional)
  388. setting: Dict of setting key-value pairs - this REPLACES the old settings entirely
  389. Returns:
  390. Updated preset data with new setting_id
  391. """
  392. if not self.is_authenticated:
  393. raise BambuCloudAuthError("Not authenticated")
  394. try:
  395. # Fetch current setting to get metadata (type, base_id, version)
  396. current = await self.get_setting_detail(setting_id)
  397. preset_type = current.get("type", "filament")
  398. # Use provided settings directly (complete replacement, not merge)
  399. # This allows the frontend to edit the full settings JSON
  400. if setting is not None:
  401. updated_setting = setting.copy()
  402. else:
  403. updated_setting = current.get("setting", {}).copy()
  404. # Extract name from settings_id field in the JSON, or use provided name, or fall back to current
  405. # The settings_id field contains the name in quotes, e.g., '"My Preset Name"'
  406. settings_id_key = {
  407. "filament": "filament_settings_id",
  408. "print": "print_settings_id",
  409. "printer": "printer_settings_id",
  410. }.get(preset_type, "filament_settings_id")
  411. settings_id_value = updated_setting.get(settings_id_key, "")
  412. if settings_id_value:
  413. # Remove surrounding quotes if present (e.g., '"foo"' -> 'foo')
  414. updated_name = settings_id_value.strip('"')
  415. elif name is not None:
  416. updated_name = name
  417. else:
  418. updated_name = current.get("name", "Untitled")
  419. # Update the timestamp
  420. import time
  421. updated_setting["updated_time"] = str(int(time.time()))
  422. # Ensure settings_id field matches the name
  423. updated_setting[settings_id_key] = f'"{updated_name}"'
  424. # Delete the old setting FIRST to avoid name conflicts
  425. await self.delete_setting(setting_id)
  426. # Create new setting via POST
  427. payload = {
  428. "type": preset_type,
  429. "name": updated_name,
  430. "version": current.get("version", "2.0.0.0"),
  431. "base_id": current.get("base_id", ""),
  432. "setting": updated_setting,
  433. }
  434. response = await self._client.post(
  435. f"{self.base_url}/v1/iot-service/api/slicer/setting", headers=self._get_headers(), json=payload
  436. )
  437. data = response.json()
  438. if response.status_code == 200:
  439. return data
  440. error_msg = data.get("message") or data.get("error") or f"HTTP {response.status_code}"
  441. raise BambuCloudError(f"Failed to update setting: {error_msg}")
  442. except httpx.RequestError as e:
  443. raise BambuCloudError(f"Request failed: {e}")
  444. async def delete_setting(self, setting_id: str) -> dict:
  445. """
  446. Delete a slicer preset/setting.
  447. Args:
  448. setting_id: ID of the preset to delete
  449. Returns:
  450. Deletion confirmation
  451. """
  452. if not self.is_authenticated:
  453. raise BambuCloudAuthError("Not authenticated")
  454. try:
  455. response = await self._client.delete(
  456. f"{self.base_url}/v1/iot-service/api/slicer/setting/{setting_id}",
  457. headers=self._get_headers(),
  458. params={"version": _SLICER_API_VERSION},
  459. )
  460. if response.status_code in (200, 204):
  461. return {"success": True, "message": "Setting deleted"}
  462. data = response.json() if response.content else {}
  463. error_msg = data.get("message") or data.get("error") or f"HTTP {response.status_code}"
  464. raise BambuCloudError(f"Failed to delete setting: {error_msg}")
  465. except httpx.RequestError as e:
  466. raise BambuCloudError(f"Request failed: {e}")
  467. async def get_devices(self) -> dict:
  468. """Get list of bound devices."""
  469. if not self.is_authenticated:
  470. raise BambuCloudAuthError("Not authenticated")
  471. try:
  472. response = await self._client.get(
  473. f"{self.base_url}/v1/iot-service/api/user/bind", headers=self._get_headers()
  474. )
  475. if response.status_code == 200:
  476. return response.json()
  477. raise BambuCloudError(f"Failed to get devices: {response.status_code}")
  478. except httpx.RequestError as e:
  479. raise BambuCloudError(f"Request failed: {e}")
  480. async def get_firmware_version(self, device_id: str) -> dict:
  481. """
  482. Get firmware version info for a device.
  483. Returns dict with:
  484. - current_version: Installed firmware version
  485. - latest_version: Latest available firmware version
  486. - update_available: Boolean indicating if update is available
  487. - release_notes: Release notes for latest version
  488. """
  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/user/device/version",
  494. headers=self._get_headers(),
  495. params={"device_id": device_id},
  496. )
  497. if response.status_code == 200:
  498. data = response.json()
  499. # API wraps response in 'data' field
  500. return data.get("data", data)
  501. raise BambuCloudError(f"Failed to get firmware version: {response.status_code}")
  502. except httpx.RequestError as e:
  503. raise BambuCloudError(f"Request failed: {e}")
  504. async def close(self):
  505. """Close the HTTP client we own. No-op when sharing an app-scoped client."""
  506. if self._owns_client:
  507. await self._client.aclose()
  508. # Previously this module exposed a process-wide ``_cloud_service`` singleton
  509. # via ``get_cloud_service()`` / ``reset_cloud_service()``. That pattern leaked
  510. # region and token state across users (a China-region login would pin the
  511. # singleton to api.bambulab.cn until the next explicit reset), so the singleton
  512. # has been removed. Callers should construct a per-request
  513. # ``BambuCloudService(region=...)`` from the stored region and ``await
  514. # cloud.close()`` it when done. See ``routes.cloud.build_authenticated_cloud``
  515. # for the standard pattern.