cloud.py 53 KB

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