cloud.py 49 KB

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