cloud.py 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423
  1. """
  2. Bambu Lab Cloud API Routes
  3. Handles authentication and profile management with Bambu Cloud.
  4. """
  5. import asyncio
  6. import json
  7. import logging
  8. from datetime import datetime, timezone
  9. from pathlib import Path
  10. from typing import Literal
  11. from fastapi import APIRouter, Body, Depends, Header, HTTPException, Request
  12. from fastapi.security import HTTPAuthorizationCredentials
  13. from sqlalchemy import select, update
  14. from sqlalchemy.ext.asyncio import AsyncSession
  15. from backend.app.core.auth import (
  16. RequirePermissionIfAuthEnabled,
  17. _user_from_api_key,
  18. _validate_api_key,
  19. require_permission_if_auth_enabled,
  20. security,
  21. )
  22. from backend.app.core.database import async_session, get_db
  23. from backend.app.core.permissions import Permission
  24. from backend.app.models.api_key import APIKey
  25. from backend.app.models.settings import Settings
  26. from backend.app.models.user import User
  27. from backend.app.schemas.cloud import (
  28. CloudAuthStatus,
  29. CloudDevice,
  30. CloudLoginRequest,
  31. CloudLoginResponse,
  32. CloudTokenRequest,
  33. CloudVerifyRequest,
  34. FirmwareUpdateInfo,
  35. FirmwareUpdatesResponse,
  36. SlicerSetting,
  37. SlicerSettingCreate,
  38. SlicerSettingDeleteResponse,
  39. SlicerSettingsResponse,
  40. SlicerSettingUpdate,
  41. )
  42. from backend.app.services.bambu_cloud import (
  43. _SLICER_API_VERSION,
  44. BambuCloudAuthError,
  45. BambuCloudError,
  46. BambuCloudService,
  47. invalidate_validation_cache,
  48. )
  49. from backend.app.utils.filament_ids import filament_id_to_setting_id
  50. logger = logging.getLogger(__name__)
  51. async def _cloud_api_key_gate(
  52. request: Request,
  53. credentials: HTTPAuthorizationCredentials | None = Depends(security),
  54. x_api_key: str | None = Header(default=None, alias="X-API-Key"),
  55. db: AsyncSession = Depends(get_db),
  56. ) -> None:
  57. """Router-level dependency: enforce API-key cloud-access fences (#1182).
  58. Runs before every /cloud/* handler. JWT-authed and anonymous callers are
  59. no-ops — their access is gated by the per-route ``Permission.CLOUD_AUTH``
  60. / ``Permission.FILAMENTS_READ`` / etc. dependency. API-keyed callers
  61. must have an owner and ``can_access_cloud=True``; legacy ownerless keys
  62. and keys without the cloud scope are rejected here.
  63. On a successful API-keyed request the owner User is stashed on
  64. ``request.state.api_key_owner`` so route handlers can resolve it via
  65. ``cloud_caller`` (the auth gate returns None for API keys to avoid a
  66. wider behaviour change in non-cloud routes — see auth.py).
  67. The dep duplicates the API-key validation done by the regular auth gate
  68. (which runs as a route-level dep, *after* router-level deps). The cost
  69. is one extra ``SELECT FROM api_keys`` per /cloud/* request — bounded and
  70. cheap (key_prefix is indexed).
  71. """
  72. api_key_value: str | None = None
  73. if x_api_key:
  74. api_key_value = x_api_key
  75. elif credentials and credentials.credentials.startswith("bb_"):
  76. api_key_value = credentials.credentials
  77. if api_key_value is None:
  78. return # JWT or anonymous — no-op
  79. api_key = await _validate_api_key(db, api_key_value)
  80. if api_key is None:
  81. # Invalid key — let the route-level auth gate produce the 401 so the
  82. # error matches what every other route returns for a bad key.
  83. return
  84. _assert_api_key_can_access_cloud(api_key)
  85. # All fences passed. Stash the owner so cloud routes can resolve their
  86. # caller User without going through the auth gate (which intentionally
  87. # returns None for API keys to keep #1182 surface-bounded to /cloud/*).
  88. request.state.api_key_owner = await _user_from_api_key(db, api_key)
  89. def cloud_caller(*permissions: Permission):
  90. """Route-level dep factory for /cloud/* handlers.
  91. Returns a Depends that resolves to:
  92. - the JWT-authenticated User (when a JWT is present and the route's
  93. permission set is satisfied), OR
  94. - the API-key owner User stashed by the router-level gate
  95. (``request.state.api_key_owner``), OR
  96. - None when auth is disabled.
  97. Replaces the direct ``RequirePermissionIfAuthEnabled(...)`` dep on cloud
  98. routes so API-keyed callers get the *owner* in ``current_user`` rather
  99. than None — without that the route falls back to the global Settings
  100. cloud_token, which is empty in auth-enabled deployments.
  101. """
  102. base_dep = require_permission_if_auth_enabled(*permissions)
  103. async def resolved(
  104. request: Request,
  105. base_user: User | None = Depends(base_dep),
  106. ) -> User | None:
  107. if base_user is not None:
  108. return base_user
  109. return getattr(request.state, "api_key_owner", None)
  110. return Depends(resolved)
  111. async def resolve_api_key_cloud_owner(
  112. credentials: HTTPAuthorizationCredentials | None = Depends(security),
  113. x_api_key: str | None = Header(default=None, alias="X-API-Key"),
  114. db: AsyncSession = Depends(get_db),
  115. ) -> User | None:
  116. """Route-level dep for non-/cloud/* endpoints that need to read the
  117. caller's stored Bambu Cloud token (e.g. the slice path resolving cloud
  118. presets — #1182 follow-up).
  119. Returns the API key's owner User when the caller is an API-keyed
  120. request *and* the key has ``can_access_cloud=True``; returns None for
  121. JWT, anonymous, or API keys without the cloud scope. The caller is
  122. expected to fall back to the JWT-authed ``current_user`` first and use
  123. this dep's result only when ``current_user`` is None.
  124. Unlike ``_cloud_api_key_gate`` (which 403s legacy/non-cloud keys at the
  125. router level), this dep is permissive: it returns None instead of
  126. raising, so a slice request via an API key without cloud scope still
  127. runs against local presets. The downstream cloud-token check in
  128. ``preset_resolver._resolve_cloud`` produces the right 400 if the
  129. request actually selects a cloud preset.
  130. """
  131. api_key_value: str | None = None
  132. if x_api_key:
  133. api_key_value = x_api_key
  134. elif credentials and credentials.credentials.startswith("bb_"):
  135. api_key_value = credentials.credentials
  136. if api_key_value is None:
  137. return None
  138. api_key = await _validate_api_key(db, api_key_value)
  139. if api_key is None or api_key.user_id is None or not api_key.can_access_cloud:
  140. return None
  141. return await _user_from_api_key(db, api_key)
  142. router = APIRouter(prefix="/cloud", tags=["cloud"], dependencies=[Depends(_cloud_api_key_gate)])
  143. # Keys for storing cloud credentials in settings
  144. CLOUD_TOKEN_KEY = "bambu_cloud_token"
  145. CLOUD_EMAIL_KEY = "bambu_cloud_email"
  146. CLOUD_REGION_KEY = "bambu_cloud_region"
  147. # Global (auth-disabled) counterpart of ``User.cloud_token_invalid_at``. Stores
  148. # an ISO timestamp; absent/empty means "not known to be dead".
  149. CLOUD_TOKEN_INVALID_KEY = "bambu_cloud_token_invalid_at"
  150. def _normalise_region(region: str | None) -> str:
  151. """Treat NULL/empty as 'global' for legacy rows that predate the region column."""
  152. return region if region in ("global", "china") else "global"
  153. async def is_cloud_token_invalid(db: AsyncSession, user: User | None = None) -> bool:
  154. """Whether the stored Bambu token is known to have been rejected.
  155. Set by :func:`mark_cloud_token_invalid` the first time Bambu answers 401,
  156. cleared on a fresh login/logout. This is the only durable record we have:
  157. Bambu's access token is opaque (no readable expiry) and Bambuddy does not
  158. persist the refresh token, so without this flag a dead credential looks
  159. exactly like a live one.
  160. """
  161. if user is not None:
  162. return user.cloud_token_invalid_at is not None
  163. result = await db.execute(select(Settings).where(Settings.key == CLOUD_TOKEN_INVALID_KEY))
  164. row = result.scalar_one_or_none()
  165. return bool(row and row.value)
  166. async def mark_cloud_token_invalid(user_id: int | None) -> None:
  167. """Record that Bambu rejected the stored token.
  168. Opens its own session on purpose. This runs from
  169. ``BambuCloudService._on_auth_failure``, i.e. in the middle of a route that
  170. is about to fail — writing through that route's session would tie the flag
  171. to a transaction the route may still roll back, and the fact that the
  172. credential is dead is true regardless of how the request ends.
  173. Best-effort: a bookkeeping failure must never replace the 401 the caller
  174. actually needs to see.
  175. """
  176. now = datetime.now(timezone.utc)
  177. try:
  178. async with async_session() as db:
  179. if user_id is not None:
  180. await db.execute(update(User).where(User.id == user_id).values(cloud_token_invalid_at=now))
  181. else:
  182. result = await db.execute(select(Settings).where(Settings.key == CLOUD_TOKEN_INVALID_KEY))
  183. row = result.scalar_one_or_none()
  184. if row:
  185. row.value = now.isoformat()
  186. else:
  187. db.add(Settings(key=CLOUD_TOKEN_INVALID_KEY, value=now.isoformat()))
  188. await db.commit()
  189. logger.warning("Bambu Cloud rejected the stored token (user_id=%s) — marking the sign-in as expired", user_id)
  190. except Exception:
  191. logger.exception("Could not record the Bambu Cloud token as invalid")
  192. async def _clear_cloud_token_invalid(db: AsyncSession, user: User | None) -> None:
  193. """Clear the rejected-token flag — called on every fresh login and logout."""
  194. if user is not None:
  195. await db.execute(update(User).where(User.id == user.id).values(cloud_token_invalid_at=None))
  196. return
  197. result = await db.execute(select(Settings).where(Settings.key == CLOUD_TOKEN_INVALID_KEY))
  198. row = result.scalar_one_or_none()
  199. if row:
  200. await db.delete(row)
  201. async def get_stored_token(db: AsyncSession, user: User | None = None) -> tuple[str | None, str | None, str]:
  202. """Get stored cloud token, email, and region.
  203. When a user is provided (auth enabled), returns that user's per-user credentials.
  204. When user is None (auth disabled), falls back to global Settings table.
  205. Region defaults to ``"global"`` when unset (including for rows that predate
  206. the ``cloud_region`` column).
  207. """
  208. if user is not None:
  209. return user.cloud_token, user.cloud_email, _normalise_region(user.cloud_region)
  210. # Fallback: global storage (auth disabled)
  211. result = await db.execute(
  212. select(Settings).where(Settings.key.in_([CLOUD_TOKEN_KEY, CLOUD_EMAIL_KEY, CLOUD_REGION_KEY]))
  213. )
  214. settings = {s.key: s.value for s in result.scalars().all()}
  215. return (
  216. settings.get(CLOUD_TOKEN_KEY),
  217. settings.get(CLOUD_EMAIL_KEY),
  218. _normalise_region(settings.get(CLOUD_REGION_KEY)),
  219. )
  220. async def store_token(db: AsyncSession, token: str, email: str, region: str, user: User | None = None) -> None:
  221. """Store cloud token, email, and region.
  222. When a user is provided (auth enabled), stores on the user record.
  223. When user is None (auth disabled), stores in global Settings table.
  224. Always clears the rejected-token flag: this is a *fresh* credential, and
  225. leaving the flag set would report the new sign-in as expired.
  226. """
  227. region = _normalise_region(region)
  228. invalidate_validation_cache(token)
  229. if user is not None:
  230. # User object is from the auth dependency's session (detached),
  231. # so use a direct UPDATE via the route's db session.
  232. await db.execute(
  233. update(User)
  234. .where(User.id == user.id)
  235. .values(cloud_token=token, cloud_email=email, cloud_region=region, cloud_token_invalid_at=None)
  236. )
  237. await db.commit()
  238. return
  239. # Fallback: global storage (auth disabled)
  240. for key, value in [(CLOUD_TOKEN_KEY, token), (CLOUD_EMAIL_KEY, email), (CLOUD_REGION_KEY, region)]:
  241. result = await db.execute(select(Settings).where(Settings.key == key))
  242. setting = result.scalar_one_or_none()
  243. if setting:
  244. setting.value = value
  245. else:
  246. db.add(Settings(key=key, value=value))
  247. await _clear_cloud_token_invalid(db, None)
  248. await db.commit()
  249. async def clear_token(db: AsyncSession, user: User | None = None) -> None:
  250. """Clear stored cloud token, email, and region.
  251. When a user is provided (auth enabled), clears that user's credentials.
  252. When user is None (auth disabled), clears from global Settings table.
  253. The rejected-token flag goes with the token: once there is no credential,
  254. "the credential is dead" is not a state worth remembering, and leaving it
  255. behind would make the next login look expired the moment it is stored.
  256. """
  257. token, _email, _region = await get_stored_token(db, user)
  258. if token:
  259. invalidate_validation_cache(token)
  260. if user is not None:
  261. await db.execute(
  262. update(User)
  263. .where(User.id == user.id)
  264. .values(cloud_token=None, cloud_email=None, cloud_region=None, cloud_token_invalid_at=None)
  265. )
  266. await db.commit()
  267. return
  268. # Fallback: global storage (auth disabled)
  269. result = await db.execute(
  270. select(Settings).where(
  271. Settings.key.in_([CLOUD_TOKEN_KEY, CLOUD_EMAIL_KEY, CLOUD_REGION_KEY, CLOUD_TOKEN_INVALID_KEY])
  272. )
  273. )
  274. for setting in result.scalars().all():
  275. await db.delete(setting)
  276. await db.commit()
  277. async def migrate_global_cloud_token_to_user(db: AsyncSession, user: User) -> bool:
  278. """Move a globally-stored cloud token onto ``user`` (auth being enabled).
  279. ``get_stored_token`` reads the global ``Settings`` rows when auth is off and
  280. ``User.cloud_token`` when it's on. Enabling auth therefore switches which
  281. column the cloud routes consult — without this migration the token linked
  282. before setup is stranded in ``Settings``, ``build_authenticated_cloud``
  283. returns ``None``, and every ``/cloud/*`` route silently degrades (#2530).
  284. The global rows are deleted after the copy so the credential isn't left at
  285. rest in a table nothing reads any more. Does **not** commit — the caller
  286. owns the transaction. Returns True when a token was actually migrated.
  287. """
  288. token, email, region = await get_stored_token(db, None)
  289. if not token:
  290. return False
  291. user.cloud_token = token
  292. user.cloud_email = email
  293. user.cloud_region = _normalise_region(region)
  294. result = await db.execute(
  295. select(Settings).where(Settings.key.in_([CLOUD_TOKEN_KEY, CLOUD_EMAIL_KEY, CLOUD_REGION_KEY]))
  296. )
  297. for setting in result.scalars().all():
  298. await db.delete(setting)
  299. return True
  300. async def migrate_user_cloud_token_to_global(db: AsyncSession, user: User) -> bool:
  301. """Move ``user``'s cloud token into global storage (auth being disabled).
  302. The mirror of :func:`migrate_global_cloud_token_to_user`: once auth is off,
  303. ``get_stored_token`` stops consulting ``User.cloud_token`` entirely, so the
  304. admin who turns auth off would otherwise lose their own cloud link.
  305. Refuses to overwrite an existing global token — a stale row from a previous
  306. no-auth stint is still someone's credential, and clobbering it silently is
  307. worse than leaving this admin to re-link. Does **not** commit. Returns True
  308. when a token was actually migrated.
  309. """
  310. if not user.cloud_token:
  311. return False
  312. existing, _, _ = await get_stored_token(db, None)
  313. if existing:
  314. return False
  315. for key, value in [
  316. (CLOUD_TOKEN_KEY, user.cloud_token),
  317. (CLOUD_EMAIL_KEY, user.cloud_email),
  318. (CLOUD_REGION_KEY, _normalise_region(user.cloud_region)),
  319. ]:
  320. if value is None:
  321. continue
  322. db.add(Settings(key=key, value=value))
  323. user.cloud_token = None
  324. user.cloud_email = None
  325. user.cloud_region = None
  326. return True
  327. def _assert_api_key_can_access_cloud(api_key: APIKey) -> None:
  328. """Reject API keys that aren't authorised to read cloud data.
  329. Three independent fences for API keys (#1182):
  330. 1. user_id IS NOT NULL — legacy keys created before per-user ownership
  331. have no owner whose cloud_token we could read; force recreate.
  332. 2. can_access_cloud=True — opt-in scope so existing automation doesn't
  333. start reading cloud data without the operator explicitly enabling it.
  334. 3. owner has stored cloud_token — enforced separately at the route
  335. level via ``build_authenticated_cloud`` returning None.
  336. """
  337. if api_key.user_id is None:
  338. raise HTTPException(
  339. status_code=401,
  340. detail=(
  341. "This API key was created before per-user cloud access was supported. "
  342. "Recreate it from Settings → API Keys to use /cloud/* endpoints."
  343. ),
  344. )
  345. if not api_key.can_access_cloud:
  346. raise HTTPException(
  347. status_code=403,
  348. detail=(
  349. "This API key is not authorised to access Bambu Cloud data. "
  350. "Enable 'Allow cloud access' on the key in Settings → API Keys."
  351. ),
  352. )
  353. async def build_authenticated_cloud(db: AsyncSession, user: User | None) -> BambuCloudService | None:
  354. """Build a per-request cloud service seeded with the caller's stored token + region.
  355. Returns ``None`` when no token is stored, so callers can 401 without constructing
  356. (and then closing) a useless client. Caller is responsible for ``await cloud.close()``.
  357. The service is wired to persist a rejected-token flag the moment Bambu
  358. answers 401, so every route that builds a client this way makes the whole
  359. app agree the sign-in is dead — rather than each feature discovering it
  360. separately and reporting Bambu's own opaque "Please login." at the user.
  361. """
  362. token, _email, region = await get_stored_token(db, user)
  363. if not token:
  364. return None
  365. user_id = user.id if user is not None else None
  366. cloud = BambuCloudService(region=region, on_auth_failure=lambda: mark_cloud_token_invalid(user_id))
  367. cloud.set_token(token)
  368. return cloud
  369. @router.get("/status", response_model=CloudAuthStatus)
  370. async def get_auth_status(
  371. db: AsyncSession = Depends(get_db),
  372. current_user: User | None = cloud_caller(Permission.CLOUD_AUTH),
  373. ):
  374. """Get current cloud authentication status.
  375. "We hold a token" is not the same claim as "Bambu accepts it", and this
  376. endpoint used to make the former while reporting the latter: it asked
  377. ``cloud.is_authenticated``, which was a string-presence check behind a
  378. self-renewing expiry, so it answered ``true`` for as long as any token
  379. existed — including tokens Bambu had been rejecting for months (#2562
  380. follow-up). It now asks Bambu.
  381. The verdict is cached for five minutes inside the service, so the several
  382. components polling this endpoint don't each pay a round-trip. When Bambu
  383. can't be reached the answer is ``None`` and we report the last known state
  384. rather than signing the user out over a transient outage.
  385. ``region`` is exposed so the frontend can show "Connected (China)" after a
  386. reload without relying on local state.
  387. """
  388. token, email, region = await get_stored_token(db, current_user)
  389. if not token:
  390. return CloudAuthStatus(is_authenticated=False, email=None, region=None, sign_in_expired=False)
  391. known_invalid = await is_cloud_token_invalid(db, current_user)
  392. user_id = current_user.id if current_user is not None else None
  393. cloud = BambuCloudService(region=region, on_auth_failure=lambda: mark_cloud_token_invalid(user_id))
  394. cloud.set_token(token)
  395. try:
  396. if known_invalid:
  397. # Already recorded as dead. Don't re-ask Bambu on every poll — only a
  398. # new login can change this, and that clears the flag.
  399. accepted: bool | None = False
  400. else:
  401. accepted = await cloud.validate_token()
  402. finally:
  403. await cloud.close()
  404. if accepted is None:
  405. # Bambu unreachable / 5xx / Cloudflare challenge. Report what we last
  406. # knew — a cloud outage must not present as "your sign-in expired".
  407. accepted = not known_invalid
  408. return CloudAuthStatus(
  409. is_authenticated=bool(accepted),
  410. email=email if accepted else None,
  411. region=region if accepted else None,
  412. # Distinguishes "you were signed in and the token died" from "you never
  413. # signed in" — the UI shows the same login form either way, but only the
  414. # former deserves an explanation for why it reappeared.
  415. sign_in_expired=not accepted,
  416. )
  417. @router.post("/login", response_model=CloudLoginResponse)
  418. async def login(
  419. request: CloudLoginRequest,
  420. db: AsyncSession = Depends(get_db),
  421. current_user: User | None = cloud_caller(Permission.CLOUD_AUTH),
  422. ):
  423. """
  424. Initiate login to Bambu Cloud.
  425. This will trigger either:
  426. - Email verification: A code is sent to the user's email
  427. - TOTP verification: User enters code from their authenticator app
  428. After receiving/generating the code, call /cloud/verify to complete the login.
  429. For TOTP, include the tfa_key from this response in the verify request.
  430. """
  431. cloud = BambuCloudService(region=request.region)
  432. try:
  433. result = await cloud.login_request(request.email, request.password)
  434. if result.get("success") and cloud.access_token:
  435. # Direct login succeeded (rare)
  436. await store_token(db, cloud.access_token, request.email, request.region, current_user)
  437. return CloudLoginResponse(
  438. success=result.get("success", False),
  439. needs_verification=result.get("needs_verification", False),
  440. message=result.get("message", "Unknown error"),
  441. verification_type=result.get("verification_type"),
  442. tfa_key=result.get("tfa_key"),
  443. )
  444. except BambuCloudAuthError as e:
  445. raise HTTPException(status_code=401, detail=str(e))
  446. except BambuCloudError as e:
  447. raise HTTPException(status_code=500, detail=str(e))
  448. finally:
  449. await cloud.close()
  450. @router.post("/verify", response_model=CloudLoginResponse)
  451. async def verify_code(
  452. request: CloudVerifyRequest,
  453. db: AsyncSession = Depends(get_db),
  454. current_user: User | None = cloud_caller(Permission.CLOUD_AUTH),
  455. ):
  456. """
  457. Complete login with verification code (email or TOTP).
  458. For email verification:
  459. - After calling /cloud/login, the user receives an email with a 6-digit code
  460. - Submit the code with email address
  461. For TOTP verification:
  462. - The user enters the 6-digit code from their authenticator app
  463. - Include the tfa_key from the /cloud/login response
  464. ``request.region`` must match the region used in /cloud/login so that the
  465. TOTP call hits the correct TFA endpoint (bambulab.com vs bambulab.cn).
  466. """
  467. cloud = BambuCloudService(region=request.region)
  468. try:
  469. # Use TOTP verification if tfa_key is provided
  470. if request.tfa_key:
  471. result = await cloud.verify_totp(request.tfa_key, request.code)
  472. else:
  473. result = await cloud.verify_code(request.email, request.code)
  474. if result.get("success") and cloud.access_token:
  475. await store_token(db, cloud.access_token, request.email, request.region, current_user)
  476. return CloudLoginResponse(
  477. success=result.get("success", False),
  478. needs_verification=False,
  479. message=result.get("message", "Unknown error"),
  480. )
  481. except BambuCloudAuthError as e:
  482. raise HTTPException(status_code=401, detail=str(e))
  483. except BambuCloudError as e:
  484. raise HTTPException(status_code=500, detail=str(e))
  485. finally:
  486. await cloud.close()
  487. @router.post("/token", response_model=CloudAuthStatus)
  488. async def set_token(
  489. request: CloudTokenRequest,
  490. db: AsyncSession = Depends(get_db),
  491. current_user: User | None = cloud_caller(Permission.CLOUD_AUTH),
  492. ):
  493. """
  494. Set access token directly.
  495. For users who already have a token (e.g., from Bambu Studio). The
  496. selected ``region`` is persisted alongside the token so every subsequent
  497. request hits the right Bambu API endpoint, including after a restart.
  498. """
  499. cloud = BambuCloudService(region=request.region)
  500. cloud.set_token(request.access_token)
  501. try:
  502. # Verify token works by trying to get profile
  503. await cloud.get_user_profile()
  504. await store_token(db, request.access_token, "token-auth", request.region, current_user)
  505. return CloudAuthStatus(is_authenticated=True, email="token-auth")
  506. except BambuCloudError:
  507. raise HTTPException(status_code=401, detail="Invalid token")
  508. finally:
  509. await cloud.close()
  510. @router.post("/logout")
  511. async def logout(
  512. db: AsyncSession = Depends(get_db),
  513. current_user: User | None = cloud_caller(Permission.CLOUD_AUTH),
  514. ):
  515. """Log out of Bambu Cloud."""
  516. await clear_token(db, current_user)
  517. return {"success": True}
  518. @router.get("/settings", response_model=SlicerSettingsResponse)
  519. async def get_slicer_settings(
  520. version: str = _SLICER_API_VERSION,
  521. db: AsyncSession = Depends(get_db),
  522. current_user: User | None = cloud_caller(Permission.CLOUD_AUTH),
  523. ):
  524. """
  525. Get all slicer settings (filament, printer, process presets).
  526. Requires authentication.
  527. """
  528. cloud = await build_authenticated_cloud(db, current_user)
  529. if cloud is None or not cloud.is_authenticated:
  530. raise HTTPException(status_code=401, detail="Not authenticated")
  531. try:
  532. data = await cloud.get_slicer_settings(version)
  533. result = SlicerSettingsResponse()
  534. # Map API keys to our types (API uses 'print' for process presets)
  535. type_mapping = {
  536. "filament": "filament",
  537. "printer": "printer",
  538. "print": "process", # API calls it 'print', we call it 'process'
  539. }
  540. for api_key, our_type in type_mapping.items():
  541. type_data = data.get(api_key, {})
  542. private_settings = type_data.get("private", [])
  543. public_settings = type_data.get("public", [])
  544. parsed = []
  545. # Private (custom) presets first
  546. for s in private_settings:
  547. parsed.append(
  548. SlicerSetting(
  549. setting_id=s.get("setting_id", s.get("id", "")),
  550. name=s.get("name", "Unknown"),
  551. type=our_type,
  552. version=s.get("version"),
  553. user_id=s.get("user_id"),
  554. updated_time=s.get("updated_time"),
  555. is_custom=True,
  556. )
  557. )
  558. # Public (default) presets
  559. for s in public_settings:
  560. parsed.append(
  561. SlicerSetting(
  562. setting_id=s.get("setting_id", s.get("id", "")),
  563. name=s.get("name", "Unknown"),
  564. type=our_type,
  565. version=s.get("version"),
  566. user_id=s.get("user_id"),
  567. updated_time=s.get("updated_time"),
  568. is_custom=False,
  569. )
  570. )
  571. setattr(result, our_type, parsed)
  572. return result
  573. except BambuCloudAuthError:
  574. await clear_token(db, current_user)
  575. raise HTTPException(status_code=401, detail="Authentication expired")
  576. except BambuCloudError as e:
  577. raise HTTPException(status_code=500, detail=str(e))
  578. finally:
  579. await cloud.close()
  580. @router.get("/settings/{setting_id}")
  581. async def get_setting_detail(
  582. setting_id: str,
  583. db: AsyncSession = Depends(get_db),
  584. current_user: User | None = cloud_caller(Permission.CLOUD_AUTH),
  585. ):
  586. """
  587. Get detailed information for a specific setting/preset.
  588. Returns the full preset configuration.
  589. """
  590. cloud = await build_authenticated_cloud(db, current_user)
  591. if cloud is None or not cloud.is_authenticated:
  592. raise HTTPException(status_code=401, detail="Not authenticated")
  593. try:
  594. data = await cloud.get_setting_detail(setting_id)
  595. return data
  596. except BambuCloudAuthError:
  597. await clear_token(db, current_user)
  598. raise HTTPException(status_code=401, detail="Authentication expired")
  599. except BambuCloudError as e:
  600. raise HTTPException(status_code=500, detail=str(e))
  601. finally:
  602. await cloud.close()
  603. @router.get("/filaments", response_model=list[SlicerSetting])
  604. async def get_filament_presets(
  605. version: str = _SLICER_API_VERSION,
  606. db: AsyncSession = Depends(get_db),
  607. current_user: User | None = cloud_caller(Permission.FILAMENTS_READ),
  608. ):
  609. """
  610. Get just filament presets (convenience endpoint).
  611. Returns all filament presets with custom presets first.
  612. Uses the same cache as get_slicer_settings.
  613. """
  614. settings = await get_slicer_settings(version=version, db=db, current_user=current_user)
  615. return settings.filament
  616. # Cache for filament preset info (setting_id -> {name, k})
  617. _filament_cache: dict[str, dict] = {}
  618. _filament_cache_time: float = 0
  619. FILAMENT_CACHE_TTL = 300 # 5 minutes
  620. # In-flight cloud lookups, keyed by setting_id (#2572). The printer overview
  621. # mounts one filament-info request per printer card, so at farm scale several
  622. # browsers ask for the same uncached preset within the same instant. Without
  623. # coalescing each request issues its own Bambu Cloud round-trip for the same id
  624. # (a thundering herd against a rate-limited API). The first caller to miss a
  625. # given id becomes the leader and resolves it; concurrent callers await its
  626. # future and reuse the result instead of duplicating the call.
  627. _filament_inflight: dict[str, asyncio.Future] = {}
  628. async def _fetch_one_cloud_filament(setting_id: str, cloud: BambuCloudService) -> dict | None:
  629. """Fetch a single filament preset from Bambu Cloud.
  630. Returns ``{"name", "k"}`` on success (name may be empty when the preset
  631. resolves but carries no display name), or ``None`` when the lookup fails.
  632. Never raises — a 400 is the expected answer for many bare preset IDs and is
  633. logged at DEBUG; anything else is a real fault logged at WARNING.
  634. """
  635. try:
  636. api_setting_id = _filament_id_to_setting_id(setting_id)
  637. data = await cloud.get_setting_detail(api_setting_id)
  638. setting = data.get("setting", {})
  639. name = data.get("name", "")
  640. k_value = setting.get("pressure_advance")
  641. if k_value is not None:
  642. try:
  643. k_value = float(k_value)
  644. except (ValueError, TypeError):
  645. k_value = None
  646. return {"name": name, "k": k_value}
  647. except Exception as e:
  648. # A 400 here is the *expected* answer, not a fault, and the local-preset
  649. # fallback (Phase 3) exists to handle it (#2530). Two routine causes:
  650. # * Many official presets are only addressable with a printer variant
  651. # suffix — "GFSA00" resolves, "GFSL05" does not, only "GFSL05_07"
  652. # (@BBL A1) does. The bare ID is all the AMS reports, so the lookup
  653. # legitimately misses.
  654. # * Personal presets ("P…") belong to the Bambu account that sliced the
  655. # file; another account will never resolve them.
  656. # Logging those at WARNING on every AMS tooltip refresh trains users to
  657. # ignore the log. Anything else — expired token, 5xx, a connection
  658. # failure — stays at WARNING because it is a fault.
  659. expected_miss = isinstance(e, BambuCloudError) and e.status_code == 400
  660. logger.log(
  661. logging.DEBUG if expected_miss else logging.WARNING,
  662. "Failed to get cloud preset %s (API ID: %s): %s",
  663. setting_id,
  664. _filament_id_to_setting_id(setting_id),
  665. e,
  666. )
  667. return None
  668. async def _resolve_cloud_filament(setting_id: str, cloud: BambuCloudService) -> dict | None:
  669. """Resolve one preset via Bambu Cloud, single-flighting concurrent misses (#2572).
  670. Concurrent callers for the same ``setting_id`` share one cloud round-trip:
  671. the first caller resolves it while the rest await the shared future. Returns
  672. the info dict (also populating ``_filament_cache``) or ``None`` on failure.
  673. """
  674. if setting_id in _filament_cache:
  675. return _filament_cache[setting_id]
  676. existing = _filament_inflight.get(setting_id)
  677. if existing is not None:
  678. # Another request is already fetching this id — reuse its result.
  679. # shield() so our own cancellation can't cancel the shared leader.
  680. try:
  681. return await asyncio.shield(existing)
  682. except Exception:
  683. return None
  684. fut: asyncio.Future = asyncio.get_event_loop().create_future()
  685. _filament_inflight[setting_id] = fut
  686. info: dict | None = None
  687. try:
  688. info = await _fetch_one_cloud_filament(setting_id, cloud)
  689. return info
  690. finally:
  691. if info is not None:
  692. _filament_cache[setting_id] = info
  693. if not fut.done():
  694. fut.set_result(info)
  695. _filament_inflight.pop(setting_id, None)
  696. # Built-in filament ID → name mapping (fallback when cloud API and local profiles
  697. # don't have the entry). Based on Bambu Lab's known filament catalogue.
  698. _BUILTIN_FILAMENT_NAMES: dict[str, str] = {
  699. "GFA00": "Bambu PLA Basic",
  700. "GFA01": "Bambu PLA Matte",
  701. "GFA02": "Bambu PLA Metal",
  702. "GFA05": "Bambu PLA Silk",
  703. "GFA06": "Bambu PLA Silk+",
  704. "GFA07": "Bambu PLA Marble",
  705. "GFA08": "Bambu PLA Sparkle",
  706. "GFA09": "Bambu PLA Tough",
  707. "GFA11": "Bambu PLA Aero",
  708. "GFA12": "Bambu PLA Glow",
  709. "GFA13": "Bambu PLA Dynamic",
  710. "GFA15": "Bambu PLA Galaxy",
  711. "GFA16": "Bambu PLA Wood",
  712. "GFA50": "Bambu PLA-CF",
  713. "GFB00": "Bambu ABS",
  714. "GFB01": "Bambu ASA",
  715. "GFB02": "Bambu ASA-Aero",
  716. "GFB50": "Bambu ABS-GF",
  717. "GFB51": "Bambu ASA-CF",
  718. "GFB60": "PolyLite ABS",
  719. "GFB61": "PolyLite ASA",
  720. "GFB98": "Generic ASA",
  721. "GFB99": "Generic ABS",
  722. "GFC00": "Bambu PC",
  723. "GFC01": "Bambu PC FR",
  724. "GFC99": "Generic PC",
  725. "GFG00": "Bambu PETG Basic",
  726. "GFG01": "Bambu PETG Translucent",
  727. "GFG02": "Bambu PETG HF",
  728. "GFG50": "Bambu PETG-CF",
  729. "GFG60": "PolyLite PETG",
  730. "GFG96": "Generic PETG HF",
  731. "GFG97": "Generic PCTG",
  732. "GFG98": "Generic PETG-CF",
  733. "GFG99": "Generic PETG",
  734. "GFL00": "PolyLite PLA",
  735. "GFL01": "PolyTerra PLA",
  736. "GFL03": "eSUN PLA+",
  737. "GFL04": "Overture PLA",
  738. "GFL05": "Overture Matte PLA",
  739. "GFL06": "Fiberon PETG-ESD",
  740. "GFL50": "Fiberon PA6-CF",
  741. "GFL51": "Fiberon PA6-GF",
  742. "GFL52": "Fiberon PA12-CF",
  743. "GFL53": "Fiberon PA612-CF",
  744. "GFL54": "Fiberon PET-CF",
  745. "GFL55": "Fiberon PETG-rCF",
  746. "GFL95": "Generic PLA High Speed",
  747. "GFL96": "Generic PLA Silk",
  748. "GFL98": "Generic PLA-CF",
  749. "GFL99": "Generic PLA",
  750. "GFN03": "Bambu PA-CF",
  751. "GFN04": "Bambu PAHT-CF",
  752. "GFN05": "Bambu PA6-CF",
  753. "GFN06": "Bambu PPA-CF",
  754. "GFN08": "Bambu PA6-GF",
  755. "GFN96": "Generic PPA-GF",
  756. "GFN97": "Generic PPA-CF",
  757. "GFN98": "Generic PA-CF",
  758. "GFN99": "Generic PA",
  759. "GFP95": "Generic PP-GF",
  760. "GFP96": "Generic PP-CF",
  761. "GFP97": "Generic PP",
  762. "GFP98": "Generic PE-CF",
  763. "GFP99": "Generic PE",
  764. "GFR98": "Generic PHA",
  765. "GFR99": "Generic EVA",
  766. "GFS00": "Bambu Support W",
  767. "GFS01": "Bambu Support G",
  768. "GFS02": "Bambu Support For PLA",
  769. "GFS03": "Bambu Support For PA/PET",
  770. "GFS04": "Bambu PVA",
  771. "GFS05": "Bambu Support For PLA/PETG",
  772. "GFS06": "Bambu Support for ABS",
  773. "GFS97": "Generic BVOH",
  774. "GFS98": "Generic HIPS",
  775. "GFS99": "Generic PVA",
  776. "GFT01": "Bambu PET-CF",
  777. "GFT02": "Bambu PPS-CF",
  778. "GFT97": "Generic PPS",
  779. "GFT98": "Generic PPS-CF",
  780. "GFU00": "Bambu TPU 95A HF",
  781. "GFU01": "Bambu TPU 95A",
  782. "GFU02": "Bambu TPU for AMS",
  783. "GFU98": "Generic TPU for AMS",
  784. "GFU99": "Generic TPU",
  785. }
  786. async def _enrich_from_local_presets(
  787. unresolved_ids: list[str],
  788. result: dict,
  789. db: AsyncSession,
  790. ) -> dict:
  791. """Fall back to local profiles for filament IDs not resolved by cloud.
  792. Matches by checking the setting_id field inside the local preset's
  793. resolved JSON blob (stored in the 'setting' column).
  794. """
  795. from sqlalchemy import text
  796. from backend.app.models.local_preset import LocalPreset
  797. # Build lookup: converted setting_id -> original filament_id
  798. id_map: dict[str, str] = {}
  799. for fid in unresolved_ids:
  800. converted = _filament_id_to_setting_id(fid)
  801. id_map[converted] = fid
  802. # Also map the original in case the JSON uses that form
  803. id_map[fid] = fid
  804. try:
  805. # Query filament presets that have a setting_id matching any of our IDs
  806. from backend.app.core.db_dialect import is_sqlite
  807. if is_sqlite():
  808. json_filter = text("json_extract(setting, '$.setting_id') IS NOT NULL")
  809. else:
  810. json_filter = text("(setting::jsonb->>'setting_id') IS NOT NULL")
  811. candidates = await db.execute(
  812. select(LocalPreset).where(
  813. LocalPreset.preset_type == "filament",
  814. json_filter,
  815. )
  816. )
  817. for preset in candidates.scalars().all():
  818. try:
  819. setting_data = json.loads(preset.setting) if isinstance(preset.setting, str) else preset.setting
  820. preset_setting_id = setting_data.get("setting_id", "")
  821. if preset_setting_id in id_map:
  822. original_id = id_map[preset_setting_id]
  823. info = {"name": preset.name, "k": None}
  824. # Try to extract K value from the local preset
  825. pa = setting_data.get("pressure_advance")
  826. if pa is not None:
  827. try:
  828. k_val = float(pa[0]) if isinstance(pa, list) else float(pa)
  829. info["k"] = k_val
  830. except (ValueError, TypeError, IndexError):
  831. pass
  832. _filament_cache[original_id] = info
  833. result[original_id] = info
  834. except Exception:
  835. continue
  836. except Exception as e:
  837. logger.warning("Failed to search local presets for filament info: %s", e)
  838. # Phase 4: Fall back to built-in filament name table for any still without a name
  839. for fid in unresolved_ids:
  840. if fid not in result or not result[fid].get("name"):
  841. name = _BUILTIN_FILAMENT_NAMES.get(fid, "")
  842. if name:
  843. # Preserve K value from earlier phases if available
  844. existing_k = result.get(fid, {}).get("k")
  845. info = {"name": name, "k": existing_k}
  846. _filament_cache[fid] = info
  847. result[fid] = info
  848. # Fill remaining unresolved with empty entries
  849. for fid in unresolved_ids:
  850. if fid not in result:
  851. _filament_cache[fid] = {"name": "", "k": None}
  852. result[fid] = {"name": "", "k": None}
  853. return result
  854. # _filament_id_to_setting_id is now imported from backend.app.utils.filament_ids
  855. _filament_id_to_setting_id = filament_id_to_setting_id
  856. @router.post("/filament-info")
  857. async def get_filament_info(
  858. setting_ids: list[str] = Body(...),
  859. db: AsyncSession = Depends(get_db),
  860. current_user: User | None = cloud_caller(Permission.FILAMENTS_READ),
  861. ):
  862. """
  863. Get filament preset info (name and K value) for multiple setting IDs.
  864. Used to enrich AMS tray and nozzle rack tooltips with preset data.
  865. Lookup order: cache → cloud → local profiles → built-in table → empty fallback.
  866. """
  867. import time
  868. logger.info("get_filament_info called with %s IDs: %s", len(setting_ids), setting_ids)
  869. global _filament_cache, _filament_cache_time
  870. # Clear stale cache
  871. if time.time() - _filament_cache_time > FILAMENT_CACHE_TTL:
  872. _filament_cache = {}
  873. _filament_cache_time = time.time()
  874. result = {}
  875. unresolved_ids: list[str] = []
  876. # Phase 1: Check cache
  877. for setting_id in setting_ids:
  878. if not setting_id:
  879. continue
  880. if setting_id in _filament_cache:
  881. result[setting_id] = _filament_cache[setting_id]
  882. else:
  883. unresolved_ids.append(setting_id)
  884. # Phase 2: Try cloud for uncached IDs
  885. if unresolved_ids:
  886. cloud = await build_authenticated_cloud(db, current_user)
  887. # Release the request's DB transaction before the sequential Bambu Cloud
  888. # round-trips below (#2572). build_authenticated_cloud has read the
  889. # stored token — the only DB access this phase needs — and nothing until
  890. # Phase 3 touches the DB again. Without this the session sat "idle in
  891. # transaction" for the full duration of N external HTTP calls, pinning a
  892. # pooled connection per in-flight request. Phase 3's read transparently
  893. # opens a fresh transaction on the same still-open session.
  894. await db.rollback()
  895. if cloud is not None and cloud.is_authenticated:
  896. try:
  897. still_unresolved: list[str] = []
  898. for setting_id in unresolved_ids:
  899. info = await _resolve_cloud_filament(setting_id, cloud)
  900. if info is not None:
  901. result[setting_id] = info
  902. if info is None or not info.get("name"):
  903. still_unresolved.append(setting_id)
  904. unresolved_ids = still_unresolved
  905. finally:
  906. await cloud.close()
  907. elif cloud is not None:
  908. await cloud.close()
  909. # Phase 3: Try local profiles for any IDs still without a name
  910. if unresolved_ids:
  911. result = await _enrich_from_local_presets(unresolved_ids, result, db)
  912. return result
  913. @router.get("/devices", response_model=list[CloudDevice])
  914. async def get_devices(
  915. db: AsyncSession = Depends(get_db),
  916. current_user: User | None = cloud_caller(Permission.PRINTERS_READ),
  917. ):
  918. """
  919. Get list of bound printer devices.
  920. Returns printers registered to the user's Bambu account.
  921. """
  922. cloud = await build_authenticated_cloud(db, current_user)
  923. if cloud is None or not cloud.is_authenticated:
  924. raise HTTPException(status_code=401, detail="Not authenticated")
  925. try:
  926. data = await cloud.get_devices()
  927. devices = data.get("devices", [])
  928. return [
  929. CloudDevice(
  930. dev_id=d.get("dev_id", ""),
  931. name=d.get("name", "Unknown"),
  932. dev_model_name=d.get("dev_model_name"),
  933. dev_product_name=d.get("dev_product_name"),
  934. online=d.get("online", False),
  935. )
  936. for d in devices
  937. ]
  938. except BambuCloudAuthError:
  939. await clear_token(db, current_user)
  940. raise HTTPException(status_code=401, detail="Authentication expired")
  941. except BambuCloudError as e:
  942. raise HTTPException(status_code=500, detail=str(e))
  943. finally:
  944. await cloud.close()
  945. @router.get("/firmware-updates", response_model=FirmwareUpdatesResponse)
  946. async def get_firmware_updates(
  947. db: AsyncSession = Depends(get_db),
  948. current_user: User | None = cloud_caller(Permission.FIRMWARE_READ),
  949. ):
  950. """
  951. Check for firmware updates for all bound devices.
  952. Returns firmware version info for each device including:
  953. - Current installed version
  954. - Latest available version
  955. - Whether an update is available
  956. - Release notes for the latest version
  957. Requires cloud authentication.
  958. """
  959. cloud = await build_authenticated_cloud(db, current_user)
  960. if cloud is None or not cloud.is_authenticated:
  961. raise HTTPException(status_code=401, detail="Not authenticated")
  962. try:
  963. # First get list of bound devices
  964. devices_data = await cloud.get_devices()
  965. devices = devices_data.get("devices", [])
  966. updates = []
  967. updates_available = 0
  968. # Check firmware for each device
  969. for device in devices:
  970. device_id = device.get("dev_id", "")
  971. device_name = device.get("name", "Unknown")
  972. try:
  973. firmware_info = await cloud.get_firmware_version(device_id)
  974. update_available = firmware_info.get("update_available", False)
  975. if update_available:
  976. updates_available += 1
  977. updates.append(
  978. FirmwareUpdateInfo(
  979. device_id=device_id,
  980. device_name=device_name,
  981. current_version=firmware_info.get("current_version"),
  982. latest_version=firmware_info.get("latest_version"),
  983. update_available=update_available,
  984. release_notes=firmware_info.get("release_notes"),
  985. )
  986. )
  987. except BambuCloudError as e:
  988. logger.warning("Failed to get firmware info for %s: %s", device_name, e)
  989. # Still include device but with unknown firmware status
  990. updates.append(
  991. FirmwareUpdateInfo(
  992. device_id=device_id,
  993. device_name=device_name,
  994. current_version=None,
  995. latest_version=None,
  996. update_available=False,
  997. release_notes=None,
  998. )
  999. )
  1000. return FirmwareUpdatesResponse(updates=updates, updates_available=updates_available)
  1001. except BambuCloudAuthError:
  1002. await clear_token(db, current_user)
  1003. raise HTTPException(status_code=401, detail="Authentication expired")
  1004. except BambuCloudError as e:
  1005. raise HTTPException(status_code=500, detail=str(e))
  1006. finally:
  1007. await cloud.close()
  1008. @router.post("/settings")
  1009. async def create_setting(
  1010. request: SlicerSettingCreate,
  1011. db: AsyncSession = Depends(get_db),
  1012. current_user: User | None = cloud_caller(Permission.CLOUD_AUTH),
  1013. ):
  1014. """
  1015. Create a new slicer preset/setting.
  1016. Creates a new preset on Bambu Cloud. The preset inherits from a base preset
  1017. and only stores the delta (modified values).
  1018. Type should be: 'filament', 'print', or 'printer'
  1019. """
  1020. cloud = await build_authenticated_cloud(db, current_user)
  1021. if cloud is None or not cloud.is_authenticated:
  1022. raise HTTPException(status_code=401, detail="Not authenticated")
  1023. try:
  1024. data = await cloud.create_setting(
  1025. preset_type=request.type,
  1026. name=request.name,
  1027. base_id=request.base_id,
  1028. setting=request.setting,
  1029. version=request.version,
  1030. )
  1031. return data
  1032. except BambuCloudAuthError:
  1033. await clear_token(db, current_user)
  1034. raise HTTPException(status_code=401, detail="Authentication expired")
  1035. except BambuCloudError as e:
  1036. raise HTTPException(status_code=500, detail=str(e))
  1037. finally:
  1038. await cloud.close()
  1039. @router.put("/settings/{setting_id}")
  1040. async def update_setting(
  1041. setting_id: str,
  1042. request: SlicerSettingUpdate,
  1043. db: AsyncSession = Depends(get_db),
  1044. current_user: User | None = cloud_caller(Permission.CLOUD_AUTH),
  1045. ):
  1046. """
  1047. Update an existing slicer preset/setting.
  1048. Updates the preset's name and/or settings on Bambu Cloud.
  1049. """
  1050. cloud = await build_authenticated_cloud(db, current_user)
  1051. if cloud is None or not cloud.is_authenticated:
  1052. raise HTTPException(status_code=401, detail="Not authenticated")
  1053. try:
  1054. data = await cloud.update_setting(
  1055. setting_id=setting_id,
  1056. name=request.name,
  1057. setting=request.setting,
  1058. )
  1059. return data
  1060. except BambuCloudAuthError:
  1061. await clear_token(db, current_user)
  1062. raise HTTPException(status_code=401, detail="Authentication expired")
  1063. except BambuCloudError as e:
  1064. raise HTTPException(status_code=500, detail=str(e))
  1065. finally:
  1066. await cloud.close()
  1067. @router.delete("/settings/{setting_id}", response_model=SlicerSettingDeleteResponse)
  1068. async def delete_setting(
  1069. setting_id: str,
  1070. db: AsyncSession = Depends(get_db),
  1071. current_user: User | None = cloud_caller(Permission.CLOUD_AUTH),
  1072. ):
  1073. """
  1074. Delete a slicer preset/setting.
  1075. Removes the preset from Bambu Cloud. This cannot be undone.
  1076. """
  1077. cloud = await build_authenticated_cloud(db, current_user)
  1078. if cloud is None or not cloud.is_authenticated:
  1079. raise HTTPException(status_code=401, detail="Not authenticated")
  1080. try:
  1081. result = await cloud.delete_setting(setting_id)
  1082. return SlicerSettingDeleteResponse(
  1083. success=result.get("success", True),
  1084. message=result.get("message", "Setting deleted"),
  1085. )
  1086. except BambuCloudAuthError:
  1087. await clear_token(db, current_user)
  1088. raise HTTPException(status_code=401, detail="Authentication expired")
  1089. except BambuCloudError as e:
  1090. raise HTTPException(status_code=500, detail=str(e))
  1091. finally:
  1092. await cloud.close()
  1093. # Path to field definition files
  1094. FIELDS_DATA_DIR = Path(__file__).parent.parent.parent / "data"
  1095. # Cache for field definitions (loaded once)
  1096. _fields_cache: dict[str, dict] = {}
  1097. def _load_fields(preset_type: str) -> dict:
  1098. """Load field definitions from JSON file."""
  1099. if preset_type in _fields_cache:
  1100. return _fields_cache[preset_type]
  1101. # Map API type names to file names
  1102. file_map = {
  1103. "filament": "filament_fields.json",
  1104. "print": "process_fields.json",
  1105. "process": "process_fields.json",
  1106. "printer": "printer_fields.json",
  1107. }
  1108. filename = file_map.get(preset_type)
  1109. if not filename:
  1110. raise HTTPException(status_code=400, detail=f"Unknown preset type: {preset_type}")
  1111. file_path = FIELDS_DATA_DIR / filename
  1112. if not file_path.exists():
  1113. raise HTTPException(status_code=404, detail=f"Field definitions not found for: {preset_type}")
  1114. with open(file_path) as f:
  1115. data = json.load(f)
  1116. _fields_cache[preset_type] = data
  1117. return data
  1118. @router.get("/builtin-filaments")
  1119. async def get_builtin_filaments(
  1120. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_READ),
  1121. ):
  1122. """
  1123. Get built-in filament names as a fallback source.
  1124. Returns the static _BUILTIN_FILAMENT_NAMES table as a list of
  1125. {filament_id, name} objects. Used by the frontend when cloud
  1126. and local profiles are unavailable.
  1127. """
  1128. return [{"filament_id": fid, "name": name} for fid, name in _BUILTIN_FILAMENT_NAMES.items()]
  1129. # Cache for filament_id → name mapping (resolved from cloud preset details)
  1130. _filament_id_name_cache: dict[str, str] = {}
  1131. _filament_id_name_cache_time: float = 0
  1132. @router.get("/filament-id-map")
  1133. async def get_filament_id_map(
  1134. db: AsyncSession = Depends(get_db),
  1135. current_user: User | None = cloud_caller(Permission.FILAMENTS_READ),
  1136. ):
  1137. """
  1138. Get filament_id → name mapping for user cloud presets.
  1139. K-profiles store a filament_id (e.g., "P4d64437") which is different from
  1140. the cloud preset setting_id (e.g., "PFUS9ac902733670a9"). This endpoint
  1141. fetches details for all custom presets and returns the mapping.
  1142. Cached for 5 minutes.
  1143. """
  1144. import time
  1145. global _filament_id_name_cache, _filament_id_name_cache_time
  1146. if _filament_id_name_cache and time.time() - _filament_id_name_cache_time < FILAMENT_CACHE_TTL:
  1147. return _filament_id_name_cache
  1148. cloud = await build_authenticated_cloud(db, current_user)
  1149. if cloud is None or not cloud.is_authenticated:
  1150. if cloud is not None:
  1151. await cloud.close()
  1152. return _filament_id_name_cache or {}
  1153. try:
  1154. data = await cloud.get_slicer_settings()
  1155. custom_presets = data.get("filament", {}).get("private", [])
  1156. result: dict[str, str] = {}
  1157. for preset in custom_presets:
  1158. setting_id = preset.get("setting_id", "")
  1159. if not setting_id:
  1160. continue
  1161. try:
  1162. detail = await cloud.get_setting_detail(setting_id)
  1163. fid = detail.get("filament_id", "")
  1164. name = detail.get("name", "")
  1165. if fid and name:
  1166. # Strip printer/nozzle suffix: "Devil Design PLA Basic @Bambu Lab H2D 0.4 nozzle" → "Devil Design PLA Basic"
  1167. clean_name = name.split(" @")[0].strip() if " @" in name else name
  1168. result[fid] = clean_name
  1169. except Exception:
  1170. pass
  1171. _filament_id_name_cache = result
  1172. _filament_id_name_cache_time = time.time()
  1173. return result
  1174. except Exception:
  1175. return _filament_id_name_cache or {}
  1176. finally:
  1177. await cloud.close()
  1178. @router.get("/fields/{preset_type}")
  1179. async def get_preset_fields(
  1180. preset_type: Literal["filament", "print", "process", "printer"],
  1181. _: User | None = RequirePermissionIfAuthEnabled(Permission.CLOUD_AUTH),
  1182. ):
  1183. """
  1184. Get field definitions for a preset type.
  1185. Returns a list of field definitions including:
  1186. - key: The setting key name
  1187. - label: Human-readable label
  1188. - type: Field type (text, number, boolean, select)
  1189. - category: Grouping category
  1190. - description: Field description
  1191. - options: For select fields, available options
  1192. - unit: Unit of measurement (if applicable)
  1193. - min/max/step: For number fields, validation constraints
  1194. """
  1195. data = _load_fields(preset_type)
  1196. return data
  1197. @router.get("/fields")
  1198. async def get_all_preset_fields(
  1199. _: User | None = RequirePermissionIfAuthEnabled(Permission.CLOUD_AUTH),
  1200. ):
  1201. """
  1202. Get all field definitions for all preset types.
  1203. Returns field definitions organized by type.
  1204. """
  1205. return {
  1206. "filament": _load_fields("filament"),
  1207. "process": _load_fields("process"),
  1208. "printer": _load_fields("printer"),
  1209. }