cloud.py 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425
  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. reason=result.get("reason"),
  444. )
  445. except BambuCloudAuthError as e:
  446. raise HTTPException(status_code=401, detail=str(e))
  447. except BambuCloudError as e:
  448. raise HTTPException(status_code=500, detail=str(e))
  449. finally:
  450. await cloud.close()
  451. @router.post("/verify", response_model=CloudLoginResponse)
  452. async def verify_code(
  453. request: CloudVerifyRequest,
  454. db: AsyncSession = Depends(get_db),
  455. current_user: User | None = cloud_caller(Permission.CLOUD_AUTH),
  456. ):
  457. """
  458. Complete login with verification code (email or TOTP).
  459. For email verification:
  460. - After calling /cloud/login, the user receives an email with a 6-digit code
  461. - Submit the code with email address
  462. For TOTP verification:
  463. - The user enters the 6-digit code from their authenticator app
  464. - Include the tfa_key from the /cloud/login response
  465. ``request.region`` must match the region used in /cloud/login so that the
  466. TOTP call hits the correct TFA endpoint (bambulab.com vs bambulab.cn).
  467. """
  468. cloud = BambuCloudService(region=request.region)
  469. try:
  470. # Use TOTP verification if tfa_key is provided
  471. if request.tfa_key:
  472. result = await cloud.verify_totp(request.tfa_key, request.code)
  473. else:
  474. result = await cloud.verify_code(request.email, request.code)
  475. if result.get("success") and cloud.access_token:
  476. await store_token(db, cloud.access_token, request.email, request.region, current_user)
  477. return CloudLoginResponse(
  478. success=result.get("success", False),
  479. needs_verification=False,
  480. message=result.get("message", "Unknown error"),
  481. reason=result.get("reason"),
  482. )
  483. except BambuCloudAuthError as e:
  484. raise HTTPException(status_code=401, detail=str(e))
  485. except BambuCloudError as e:
  486. raise HTTPException(status_code=500, detail=str(e))
  487. finally:
  488. await cloud.close()
  489. @router.post("/token", response_model=CloudAuthStatus)
  490. async def set_token(
  491. request: CloudTokenRequest,
  492. db: AsyncSession = Depends(get_db),
  493. current_user: User | None = cloud_caller(Permission.CLOUD_AUTH),
  494. ):
  495. """
  496. Set access token directly.
  497. For users who already have a token (e.g., from Bambu Studio). The
  498. selected ``region`` is persisted alongside the token so every subsequent
  499. request hits the right Bambu API endpoint, including after a restart.
  500. """
  501. cloud = BambuCloudService(region=request.region)
  502. cloud.set_token(request.access_token)
  503. try:
  504. # Verify token works by trying to get profile
  505. await cloud.get_user_profile()
  506. await store_token(db, request.access_token, "token-auth", request.region, current_user)
  507. return CloudAuthStatus(is_authenticated=True, email="token-auth")
  508. except BambuCloudError:
  509. raise HTTPException(status_code=401, detail="Invalid token")
  510. finally:
  511. await cloud.close()
  512. @router.post("/logout")
  513. async def logout(
  514. db: AsyncSession = Depends(get_db),
  515. current_user: User | None = cloud_caller(Permission.CLOUD_AUTH),
  516. ):
  517. """Log out of Bambu Cloud."""
  518. await clear_token(db, current_user)
  519. return {"success": True}
  520. @router.get("/settings", response_model=SlicerSettingsResponse)
  521. async def get_slicer_settings(
  522. version: str = _SLICER_API_VERSION,
  523. db: AsyncSession = Depends(get_db),
  524. current_user: User | None = cloud_caller(Permission.CLOUD_AUTH),
  525. ):
  526. """
  527. Get all slicer settings (filament, printer, process presets).
  528. Requires authentication.
  529. """
  530. cloud = await build_authenticated_cloud(db, current_user)
  531. if cloud is None or not cloud.is_authenticated:
  532. raise HTTPException(status_code=401, detail="Not authenticated")
  533. try:
  534. data = await cloud.get_slicer_settings(version)
  535. result = SlicerSettingsResponse()
  536. # Map API keys to our types (API uses 'print' for process presets)
  537. type_mapping = {
  538. "filament": "filament",
  539. "printer": "printer",
  540. "print": "process", # API calls it 'print', we call it 'process'
  541. }
  542. for api_key, our_type in type_mapping.items():
  543. type_data = data.get(api_key, {})
  544. private_settings = type_data.get("private", [])
  545. public_settings = type_data.get("public", [])
  546. parsed = []
  547. # Private (custom) presets first
  548. for s in private_settings:
  549. parsed.append(
  550. SlicerSetting(
  551. setting_id=s.get("setting_id", s.get("id", "")),
  552. name=s.get("name", "Unknown"),
  553. type=our_type,
  554. version=s.get("version"),
  555. user_id=s.get("user_id"),
  556. updated_time=s.get("updated_time"),
  557. is_custom=True,
  558. )
  559. )
  560. # Public (default) presets
  561. for s in public_settings:
  562. parsed.append(
  563. SlicerSetting(
  564. setting_id=s.get("setting_id", s.get("id", "")),
  565. name=s.get("name", "Unknown"),
  566. type=our_type,
  567. version=s.get("version"),
  568. user_id=s.get("user_id"),
  569. updated_time=s.get("updated_time"),
  570. is_custom=False,
  571. )
  572. )
  573. setattr(result, our_type, parsed)
  574. return result
  575. except BambuCloudAuthError:
  576. await clear_token(db, current_user)
  577. raise HTTPException(status_code=401, detail="Authentication expired")
  578. except BambuCloudError as e:
  579. raise HTTPException(status_code=500, detail=str(e))
  580. finally:
  581. await cloud.close()
  582. @router.get("/settings/{setting_id}")
  583. async def get_setting_detail(
  584. setting_id: str,
  585. db: AsyncSession = Depends(get_db),
  586. current_user: User | None = cloud_caller(Permission.CLOUD_AUTH),
  587. ):
  588. """
  589. Get detailed information for a specific setting/preset.
  590. Returns the full preset configuration.
  591. """
  592. cloud = await build_authenticated_cloud(db, current_user)
  593. if cloud is None or not cloud.is_authenticated:
  594. raise HTTPException(status_code=401, detail="Not authenticated")
  595. try:
  596. data = await cloud.get_setting_detail(setting_id)
  597. return data
  598. except BambuCloudAuthError:
  599. await clear_token(db, current_user)
  600. raise HTTPException(status_code=401, detail="Authentication expired")
  601. except BambuCloudError as e:
  602. raise HTTPException(status_code=500, detail=str(e))
  603. finally:
  604. await cloud.close()
  605. @router.get("/filaments", response_model=list[SlicerSetting])
  606. async def get_filament_presets(
  607. version: str = _SLICER_API_VERSION,
  608. db: AsyncSession = Depends(get_db),
  609. current_user: User | None = cloud_caller(Permission.FILAMENTS_READ),
  610. ):
  611. """
  612. Get just filament presets (convenience endpoint).
  613. Returns all filament presets with custom presets first.
  614. Uses the same cache as get_slicer_settings.
  615. """
  616. settings = await get_slicer_settings(version=version, db=db, current_user=current_user)
  617. return settings.filament
  618. # Cache for filament preset info (setting_id -> {name, k})
  619. _filament_cache: dict[str, dict] = {}
  620. _filament_cache_time: float = 0
  621. FILAMENT_CACHE_TTL = 300 # 5 minutes
  622. # In-flight cloud lookups, keyed by setting_id (#2572). The printer overview
  623. # mounts one filament-info request per printer card, so at farm scale several
  624. # browsers ask for the same uncached preset within the same instant. Without
  625. # coalescing each request issues its own Bambu Cloud round-trip for the same id
  626. # (a thundering herd against a rate-limited API). The first caller to miss a
  627. # given id becomes the leader and resolves it; concurrent callers await its
  628. # future and reuse the result instead of duplicating the call.
  629. _filament_inflight: dict[str, asyncio.Future] = {}
  630. async def _fetch_one_cloud_filament(setting_id: str, cloud: BambuCloudService) -> dict | None:
  631. """Fetch a single filament preset from Bambu Cloud.
  632. Returns ``{"name", "k"}`` on success (name may be empty when the preset
  633. resolves but carries no display name), or ``None`` when the lookup fails.
  634. Never raises — a 400 is the expected answer for many bare preset IDs and is
  635. logged at DEBUG; anything else is a real fault logged at WARNING.
  636. """
  637. try:
  638. api_setting_id = _filament_id_to_setting_id(setting_id)
  639. data = await cloud.get_setting_detail(api_setting_id)
  640. setting = data.get("setting", {})
  641. name = data.get("name", "")
  642. k_value = setting.get("pressure_advance")
  643. if k_value is not None:
  644. try:
  645. k_value = float(k_value)
  646. except (ValueError, TypeError):
  647. k_value = None
  648. return {"name": name, "k": k_value}
  649. except Exception as e:
  650. # A 400 here is the *expected* answer, not a fault, and the local-preset
  651. # fallback (Phase 3) exists to handle it (#2530). Two routine causes:
  652. # * Many official presets are only addressable with a printer variant
  653. # suffix — "GFSA00" resolves, "GFSL05" does not, only "GFSL05_07"
  654. # (@BBL A1) does. The bare ID is all the AMS reports, so the lookup
  655. # legitimately misses.
  656. # * Personal presets ("P…") belong to the Bambu account that sliced the
  657. # file; another account will never resolve them.
  658. # Logging those at WARNING on every AMS tooltip refresh trains users to
  659. # ignore the log. Anything else — expired token, 5xx, a connection
  660. # failure — stays at WARNING because it is a fault.
  661. expected_miss = isinstance(e, BambuCloudError) and e.status_code == 400
  662. logger.log(
  663. logging.DEBUG if expected_miss else logging.WARNING,
  664. "Failed to get cloud preset %s (API ID: %s): %s",
  665. setting_id,
  666. _filament_id_to_setting_id(setting_id),
  667. e,
  668. )
  669. return None
  670. async def _resolve_cloud_filament(setting_id: str, cloud: BambuCloudService) -> dict | None:
  671. """Resolve one preset via Bambu Cloud, single-flighting concurrent misses (#2572).
  672. Concurrent callers for the same ``setting_id`` share one cloud round-trip:
  673. the first caller resolves it while the rest await the shared future. Returns
  674. the info dict (also populating ``_filament_cache``) or ``None`` on failure.
  675. """
  676. if setting_id in _filament_cache:
  677. return _filament_cache[setting_id]
  678. existing = _filament_inflight.get(setting_id)
  679. if existing is not None:
  680. # Another request is already fetching this id — reuse its result.
  681. # shield() so our own cancellation can't cancel the shared leader.
  682. try:
  683. return await asyncio.shield(existing)
  684. except Exception:
  685. return None
  686. fut: asyncio.Future = asyncio.get_event_loop().create_future()
  687. _filament_inflight[setting_id] = fut
  688. info: dict | None = None
  689. try:
  690. info = await _fetch_one_cloud_filament(setting_id, cloud)
  691. return info
  692. finally:
  693. if info is not None:
  694. _filament_cache[setting_id] = info
  695. if not fut.done():
  696. fut.set_result(info)
  697. _filament_inflight.pop(setting_id, None)
  698. # Built-in filament ID → name mapping (fallback when cloud API and local profiles
  699. # don't have the entry). Based on Bambu Lab's known filament catalogue.
  700. _BUILTIN_FILAMENT_NAMES: dict[str, str] = {
  701. "GFA00": "Bambu PLA Basic",
  702. "GFA01": "Bambu PLA Matte",
  703. "GFA02": "Bambu PLA Metal",
  704. "GFA05": "Bambu PLA Silk",
  705. "GFA06": "Bambu PLA Silk+",
  706. "GFA07": "Bambu PLA Marble",
  707. "GFA08": "Bambu PLA Sparkle",
  708. "GFA09": "Bambu PLA Tough",
  709. "GFA11": "Bambu PLA Aero",
  710. "GFA12": "Bambu PLA Glow",
  711. "GFA13": "Bambu PLA Dynamic",
  712. "GFA15": "Bambu PLA Galaxy",
  713. "GFA16": "Bambu PLA Wood",
  714. "GFA50": "Bambu PLA-CF",
  715. "GFB00": "Bambu ABS",
  716. "GFB01": "Bambu ASA",
  717. "GFB02": "Bambu ASA-Aero",
  718. "GFB50": "Bambu ABS-GF",
  719. "GFB51": "Bambu ASA-CF",
  720. "GFB60": "PolyLite ABS",
  721. "GFB61": "PolyLite ASA",
  722. "GFB98": "Generic ASA",
  723. "GFB99": "Generic ABS",
  724. "GFC00": "Bambu PC",
  725. "GFC01": "Bambu PC FR",
  726. "GFC99": "Generic PC",
  727. "GFG00": "Bambu PETG Basic",
  728. "GFG01": "Bambu PETG Translucent",
  729. "GFG02": "Bambu PETG HF",
  730. "GFG50": "Bambu PETG-CF",
  731. "GFG60": "PolyLite PETG",
  732. "GFG96": "Generic PETG HF",
  733. "GFG97": "Generic PCTG",
  734. "GFG98": "Generic PETG-CF",
  735. "GFG99": "Generic PETG",
  736. "GFL00": "PolyLite PLA",
  737. "GFL01": "PolyTerra PLA",
  738. "GFL03": "eSUN PLA+",
  739. "GFL04": "Overture PLA",
  740. "GFL05": "Overture Matte PLA",
  741. "GFL06": "Fiberon PETG-ESD",
  742. "GFL50": "Fiberon PA6-CF",
  743. "GFL51": "Fiberon PA6-GF",
  744. "GFL52": "Fiberon PA12-CF",
  745. "GFL53": "Fiberon PA612-CF",
  746. "GFL54": "Fiberon PET-CF",
  747. "GFL55": "Fiberon PETG-rCF",
  748. "GFL95": "Generic PLA High Speed",
  749. "GFL96": "Generic PLA Silk",
  750. "GFL98": "Generic PLA-CF",
  751. "GFL99": "Generic PLA",
  752. "GFN03": "Bambu PA-CF",
  753. "GFN04": "Bambu PAHT-CF",
  754. "GFN05": "Bambu PA6-CF",
  755. "GFN06": "Bambu PPA-CF",
  756. "GFN08": "Bambu PA6-GF",
  757. "GFN96": "Generic PPA-GF",
  758. "GFN97": "Generic PPA-CF",
  759. "GFN98": "Generic PA-CF",
  760. "GFN99": "Generic PA",
  761. "GFP95": "Generic PP-GF",
  762. "GFP96": "Generic PP-CF",
  763. "GFP97": "Generic PP",
  764. "GFP98": "Generic PE-CF",
  765. "GFP99": "Generic PE",
  766. "GFR98": "Generic PHA",
  767. "GFR99": "Generic EVA",
  768. "GFS00": "Bambu Support W",
  769. "GFS01": "Bambu Support G",
  770. "GFS02": "Bambu Support For PLA",
  771. "GFS03": "Bambu Support For PA/PET",
  772. "GFS04": "Bambu PVA",
  773. "GFS05": "Bambu Support For PLA/PETG",
  774. "GFS06": "Bambu Support for ABS",
  775. "GFS97": "Generic BVOH",
  776. "GFS98": "Generic HIPS",
  777. "GFS99": "Generic PVA",
  778. "GFT01": "Bambu PET-CF",
  779. "GFT02": "Bambu PPS-CF",
  780. "GFT97": "Generic PPS",
  781. "GFT98": "Generic PPS-CF",
  782. "GFU00": "Bambu TPU 95A HF",
  783. "GFU01": "Bambu TPU 95A",
  784. "GFU02": "Bambu TPU for AMS",
  785. "GFU98": "Generic TPU for AMS",
  786. "GFU99": "Generic TPU",
  787. }
  788. async def _enrich_from_local_presets(
  789. unresolved_ids: list[str],
  790. result: dict,
  791. db: AsyncSession,
  792. ) -> dict:
  793. """Fall back to local profiles for filament IDs not resolved by cloud.
  794. Matches by checking the setting_id field inside the local preset's
  795. resolved JSON blob (stored in the 'setting' column).
  796. """
  797. from sqlalchemy import text
  798. from backend.app.models.local_preset import LocalPreset
  799. # Build lookup: converted setting_id -> original filament_id
  800. id_map: dict[str, str] = {}
  801. for fid in unresolved_ids:
  802. converted = _filament_id_to_setting_id(fid)
  803. id_map[converted] = fid
  804. # Also map the original in case the JSON uses that form
  805. id_map[fid] = fid
  806. try:
  807. # Query filament presets that have a setting_id matching any of our IDs
  808. from backend.app.core.db_dialect import is_sqlite
  809. if is_sqlite():
  810. json_filter = text("json_extract(setting, '$.setting_id') IS NOT NULL")
  811. else:
  812. json_filter = text("(setting::jsonb->>'setting_id') IS NOT NULL")
  813. candidates = await db.execute(
  814. select(LocalPreset).where(
  815. LocalPreset.preset_type == "filament",
  816. json_filter,
  817. )
  818. )
  819. for preset in candidates.scalars().all():
  820. try:
  821. setting_data = json.loads(preset.setting) if isinstance(preset.setting, str) else preset.setting
  822. preset_setting_id = setting_data.get("setting_id", "")
  823. if preset_setting_id in id_map:
  824. original_id = id_map[preset_setting_id]
  825. info = {"name": preset.name, "k": None}
  826. # Try to extract K value from the local preset
  827. pa = setting_data.get("pressure_advance")
  828. if pa is not None:
  829. try:
  830. k_val = float(pa[0]) if isinstance(pa, list) else float(pa)
  831. info["k"] = k_val
  832. except (ValueError, TypeError, IndexError):
  833. pass
  834. _filament_cache[original_id] = info
  835. result[original_id] = info
  836. except Exception:
  837. continue
  838. except Exception as e:
  839. logger.warning("Failed to search local presets for filament info: %s", e)
  840. # Phase 4: Fall back to built-in filament name table for any still without a name
  841. for fid in unresolved_ids:
  842. if fid not in result or not result[fid].get("name"):
  843. name = _BUILTIN_FILAMENT_NAMES.get(fid, "")
  844. if name:
  845. # Preserve K value from earlier phases if available
  846. existing_k = result.get(fid, {}).get("k")
  847. info = {"name": name, "k": existing_k}
  848. _filament_cache[fid] = info
  849. result[fid] = info
  850. # Fill remaining unresolved with empty entries
  851. for fid in unresolved_ids:
  852. if fid not in result:
  853. _filament_cache[fid] = {"name": "", "k": None}
  854. result[fid] = {"name": "", "k": None}
  855. return result
  856. # _filament_id_to_setting_id is now imported from backend.app.utils.filament_ids
  857. _filament_id_to_setting_id = filament_id_to_setting_id
  858. @router.post("/filament-info")
  859. async def get_filament_info(
  860. setting_ids: list[str] = Body(...),
  861. db: AsyncSession = Depends(get_db),
  862. current_user: User | None = cloud_caller(Permission.FILAMENTS_READ),
  863. ):
  864. """
  865. Get filament preset info (name and K value) for multiple setting IDs.
  866. Used to enrich AMS tray and nozzle rack tooltips with preset data.
  867. Lookup order: cache → cloud → local profiles → built-in table → empty fallback.
  868. """
  869. import time
  870. logger.info("get_filament_info called with %s IDs: %s", len(setting_ids), setting_ids)
  871. global _filament_cache, _filament_cache_time
  872. # Clear stale cache
  873. if time.time() - _filament_cache_time > FILAMENT_CACHE_TTL:
  874. _filament_cache = {}
  875. _filament_cache_time = time.time()
  876. result = {}
  877. unresolved_ids: list[str] = []
  878. # Phase 1: Check cache
  879. for setting_id in setting_ids:
  880. if not setting_id:
  881. continue
  882. if setting_id in _filament_cache:
  883. result[setting_id] = _filament_cache[setting_id]
  884. else:
  885. unresolved_ids.append(setting_id)
  886. # Phase 2: Try cloud for uncached IDs
  887. if unresolved_ids:
  888. cloud = await build_authenticated_cloud(db, current_user)
  889. # Release the request's DB transaction before the sequential Bambu Cloud
  890. # round-trips below (#2572). build_authenticated_cloud has read the
  891. # stored token — the only DB access this phase needs — and nothing until
  892. # Phase 3 touches the DB again. Without this the session sat "idle in
  893. # transaction" for the full duration of N external HTTP calls, pinning a
  894. # pooled connection per in-flight request. Phase 3's read transparently
  895. # opens a fresh transaction on the same still-open session.
  896. await db.rollback()
  897. if cloud is not None and cloud.is_authenticated:
  898. try:
  899. still_unresolved: list[str] = []
  900. for setting_id in unresolved_ids:
  901. info = await _resolve_cloud_filament(setting_id, cloud)
  902. if info is not None:
  903. result[setting_id] = info
  904. if info is None or not info.get("name"):
  905. still_unresolved.append(setting_id)
  906. unresolved_ids = still_unresolved
  907. finally:
  908. await cloud.close()
  909. elif cloud is not None:
  910. await cloud.close()
  911. # Phase 3: Try local profiles for any IDs still without a name
  912. if unresolved_ids:
  913. result = await _enrich_from_local_presets(unresolved_ids, result, db)
  914. return result
  915. @router.get("/devices", response_model=list[CloudDevice])
  916. async def get_devices(
  917. db: AsyncSession = Depends(get_db),
  918. current_user: User | None = cloud_caller(Permission.PRINTERS_READ),
  919. ):
  920. """
  921. Get list of bound printer devices.
  922. Returns printers registered to the user's Bambu account.
  923. """
  924. cloud = await build_authenticated_cloud(db, current_user)
  925. if cloud is None or not cloud.is_authenticated:
  926. raise HTTPException(status_code=401, detail="Not authenticated")
  927. try:
  928. data = await cloud.get_devices()
  929. devices = data.get("devices", [])
  930. return [
  931. CloudDevice(
  932. dev_id=d.get("dev_id", ""),
  933. name=d.get("name", "Unknown"),
  934. dev_model_name=d.get("dev_model_name"),
  935. dev_product_name=d.get("dev_product_name"),
  936. online=d.get("online", False),
  937. )
  938. for d in devices
  939. ]
  940. except BambuCloudAuthError:
  941. await clear_token(db, current_user)
  942. raise HTTPException(status_code=401, detail="Authentication expired")
  943. except BambuCloudError as e:
  944. raise HTTPException(status_code=500, detail=str(e))
  945. finally:
  946. await cloud.close()
  947. @router.get("/firmware-updates", response_model=FirmwareUpdatesResponse)
  948. async def get_firmware_updates(
  949. db: AsyncSession = Depends(get_db),
  950. current_user: User | None = cloud_caller(Permission.FIRMWARE_READ),
  951. ):
  952. """
  953. Check for firmware updates for all bound devices.
  954. Returns firmware version info for each device including:
  955. - Current installed version
  956. - Latest available version
  957. - Whether an update is available
  958. - Release notes for the latest version
  959. Requires cloud authentication.
  960. """
  961. cloud = await build_authenticated_cloud(db, current_user)
  962. if cloud is None or not cloud.is_authenticated:
  963. raise HTTPException(status_code=401, detail="Not authenticated")
  964. try:
  965. # First get list of bound devices
  966. devices_data = await cloud.get_devices()
  967. devices = devices_data.get("devices", [])
  968. updates = []
  969. updates_available = 0
  970. # Check firmware for each device
  971. for device in devices:
  972. device_id = device.get("dev_id", "")
  973. device_name = device.get("name", "Unknown")
  974. try:
  975. firmware_info = await cloud.get_firmware_version(device_id)
  976. update_available = firmware_info.get("update_available", False)
  977. if update_available:
  978. updates_available += 1
  979. updates.append(
  980. FirmwareUpdateInfo(
  981. device_id=device_id,
  982. device_name=device_name,
  983. current_version=firmware_info.get("current_version"),
  984. latest_version=firmware_info.get("latest_version"),
  985. update_available=update_available,
  986. release_notes=firmware_info.get("release_notes"),
  987. )
  988. )
  989. except BambuCloudError as e:
  990. logger.warning("Failed to get firmware info for %s: %s", device_name, e)
  991. # Still include device but with unknown firmware status
  992. updates.append(
  993. FirmwareUpdateInfo(
  994. device_id=device_id,
  995. device_name=device_name,
  996. current_version=None,
  997. latest_version=None,
  998. update_available=False,
  999. release_notes=None,
  1000. )
  1001. )
  1002. return FirmwareUpdatesResponse(updates=updates, updates_available=updates_available)
  1003. except BambuCloudAuthError:
  1004. await clear_token(db, current_user)
  1005. raise HTTPException(status_code=401, detail="Authentication expired")
  1006. except BambuCloudError as e:
  1007. raise HTTPException(status_code=500, detail=str(e))
  1008. finally:
  1009. await cloud.close()
  1010. @router.post("/settings")
  1011. async def create_setting(
  1012. request: SlicerSettingCreate,
  1013. db: AsyncSession = Depends(get_db),
  1014. current_user: User | None = cloud_caller(Permission.CLOUD_AUTH),
  1015. ):
  1016. """
  1017. Create a new slicer preset/setting.
  1018. Creates a new preset on Bambu Cloud. The preset inherits from a base preset
  1019. and only stores the delta (modified values).
  1020. Type should be: 'filament', 'print', or 'printer'
  1021. """
  1022. cloud = await build_authenticated_cloud(db, current_user)
  1023. if cloud is None or not cloud.is_authenticated:
  1024. raise HTTPException(status_code=401, detail="Not authenticated")
  1025. try:
  1026. data = await cloud.create_setting(
  1027. preset_type=request.type,
  1028. name=request.name,
  1029. base_id=request.base_id,
  1030. setting=request.setting,
  1031. version=request.version,
  1032. )
  1033. return data
  1034. except BambuCloudAuthError:
  1035. await clear_token(db, current_user)
  1036. raise HTTPException(status_code=401, detail="Authentication expired")
  1037. except BambuCloudError as e:
  1038. raise HTTPException(status_code=500, detail=str(e))
  1039. finally:
  1040. await cloud.close()
  1041. @router.put("/settings/{setting_id}")
  1042. async def update_setting(
  1043. setting_id: str,
  1044. request: SlicerSettingUpdate,
  1045. db: AsyncSession = Depends(get_db),
  1046. current_user: User | None = cloud_caller(Permission.CLOUD_AUTH),
  1047. ):
  1048. """
  1049. Update an existing slicer preset/setting.
  1050. Updates the preset's name and/or settings on Bambu Cloud.
  1051. """
  1052. cloud = await build_authenticated_cloud(db, current_user)
  1053. if cloud is None or not cloud.is_authenticated:
  1054. raise HTTPException(status_code=401, detail="Not authenticated")
  1055. try:
  1056. data = await cloud.update_setting(
  1057. setting_id=setting_id,
  1058. name=request.name,
  1059. setting=request.setting,
  1060. )
  1061. return data
  1062. except BambuCloudAuthError:
  1063. await clear_token(db, current_user)
  1064. raise HTTPException(status_code=401, detail="Authentication expired")
  1065. except BambuCloudError as e:
  1066. raise HTTPException(status_code=500, detail=str(e))
  1067. finally:
  1068. await cloud.close()
  1069. @router.delete("/settings/{setting_id}", response_model=SlicerSettingDeleteResponse)
  1070. async def delete_setting(
  1071. setting_id: str,
  1072. db: AsyncSession = Depends(get_db),
  1073. current_user: User | None = cloud_caller(Permission.CLOUD_AUTH),
  1074. ):
  1075. """
  1076. Delete a slicer preset/setting.
  1077. Removes the preset from Bambu Cloud. This cannot be undone.
  1078. """
  1079. cloud = await build_authenticated_cloud(db, current_user)
  1080. if cloud is None or not cloud.is_authenticated:
  1081. raise HTTPException(status_code=401, detail="Not authenticated")
  1082. try:
  1083. result = await cloud.delete_setting(setting_id)
  1084. return SlicerSettingDeleteResponse(
  1085. success=result.get("success", True),
  1086. message=result.get("message", "Setting deleted"),
  1087. )
  1088. except BambuCloudAuthError:
  1089. await clear_token(db, current_user)
  1090. raise HTTPException(status_code=401, detail="Authentication expired")
  1091. except BambuCloudError as e:
  1092. raise HTTPException(status_code=500, detail=str(e))
  1093. finally:
  1094. await cloud.close()
  1095. # Path to field definition files
  1096. FIELDS_DATA_DIR = Path(__file__).parent.parent.parent / "data"
  1097. # Cache for field definitions (loaded once)
  1098. _fields_cache: dict[str, dict] = {}
  1099. def _load_fields(preset_type: str) -> dict:
  1100. """Load field definitions from JSON file."""
  1101. if preset_type in _fields_cache:
  1102. return _fields_cache[preset_type]
  1103. # Map API type names to file names
  1104. file_map = {
  1105. "filament": "filament_fields.json",
  1106. "print": "process_fields.json",
  1107. "process": "process_fields.json",
  1108. "printer": "printer_fields.json",
  1109. }
  1110. filename = file_map.get(preset_type)
  1111. if not filename:
  1112. raise HTTPException(status_code=400, detail=f"Unknown preset type: {preset_type}")
  1113. file_path = FIELDS_DATA_DIR / filename
  1114. if not file_path.exists():
  1115. raise HTTPException(status_code=404, detail=f"Field definitions not found for: {preset_type}")
  1116. with open(file_path) as f:
  1117. data = json.load(f)
  1118. _fields_cache[preset_type] = data
  1119. return data
  1120. @router.get("/builtin-filaments")
  1121. async def get_builtin_filaments(
  1122. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_READ),
  1123. ):
  1124. """
  1125. Get built-in filament names as a fallback source.
  1126. Returns the static _BUILTIN_FILAMENT_NAMES table as a list of
  1127. {filament_id, name} objects. Used by the frontend when cloud
  1128. and local profiles are unavailable.
  1129. """
  1130. return [{"filament_id": fid, "name": name} for fid, name in _BUILTIN_FILAMENT_NAMES.items()]
  1131. # Cache for filament_id → name mapping (resolved from cloud preset details)
  1132. _filament_id_name_cache: dict[str, str] = {}
  1133. _filament_id_name_cache_time: float = 0
  1134. @router.get("/filament-id-map")
  1135. async def get_filament_id_map(
  1136. db: AsyncSession = Depends(get_db),
  1137. current_user: User | None = cloud_caller(Permission.FILAMENTS_READ),
  1138. ):
  1139. """
  1140. Get filament_id → name mapping for user cloud presets.
  1141. K-profiles store a filament_id (e.g., "P4d64437") which is different from
  1142. the cloud preset setting_id (e.g., "PFUS9ac902733670a9"). This endpoint
  1143. fetches details for all custom presets and returns the mapping.
  1144. Cached for 5 minutes.
  1145. """
  1146. import time
  1147. global _filament_id_name_cache, _filament_id_name_cache_time
  1148. if _filament_id_name_cache and time.time() - _filament_id_name_cache_time < FILAMENT_CACHE_TTL:
  1149. return _filament_id_name_cache
  1150. cloud = await build_authenticated_cloud(db, current_user)
  1151. if cloud is None or not cloud.is_authenticated:
  1152. if cloud is not None:
  1153. await cloud.close()
  1154. return _filament_id_name_cache or {}
  1155. try:
  1156. data = await cloud.get_slicer_settings()
  1157. custom_presets = data.get("filament", {}).get("private", [])
  1158. result: dict[str, str] = {}
  1159. for preset in custom_presets:
  1160. setting_id = preset.get("setting_id", "")
  1161. if not setting_id:
  1162. continue
  1163. try:
  1164. detail = await cloud.get_setting_detail(setting_id)
  1165. fid = detail.get("filament_id", "")
  1166. name = detail.get("name", "")
  1167. if fid and name:
  1168. # Strip printer/nozzle suffix: "Devil Design PLA Basic @Bambu Lab H2D 0.4 nozzle" → "Devil Design PLA Basic"
  1169. clean_name = name.split(" @")[0].strip() if " @" in name else name
  1170. result[fid] = clean_name
  1171. except Exception:
  1172. pass
  1173. _filament_id_name_cache = result
  1174. _filament_id_name_cache_time = time.time()
  1175. return result
  1176. except Exception:
  1177. return _filament_id_name_cache or {}
  1178. finally:
  1179. await cloud.close()
  1180. @router.get("/fields/{preset_type}")
  1181. async def get_preset_fields(
  1182. preset_type: Literal["filament", "print", "process", "printer"],
  1183. _: User | None = RequirePermissionIfAuthEnabled(Permission.CLOUD_AUTH),
  1184. ):
  1185. """
  1186. Get field definitions for a preset type.
  1187. Returns a list of field definitions including:
  1188. - key: The setting key name
  1189. - label: Human-readable label
  1190. - type: Field type (text, number, boolean, select)
  1191. - category: Grouping category
  1192. - description: Field description
  1193. - options: For select fields, available options
  1194. - unit: Unit of measurement (if applicable)
  1195. - min/max/step: For number fields, validation constraints
  1196. """
  1197. data = _load_fields(preset_type)
  1198. return data
  1199. @router.get("/fields")
  1200. async def get_all_preset_fields(
  1201. _: User | None = RequirePermissionIfAuthEnabled(Permission.CLOUD_AUTH),
  1202. ):
  1203. """
  1204. Get all field definitions for all preset types.
  1205. Returns field definitions organized by type.
  1206. """
  1207. return {
  1208. "filament": _load_fields("filament"),
  1209. "process": _load_fields("process"),
  1210. "printer": _load_fields("printer"),
  1211. }