cloud.py 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  1. """
  2. Bambu Lab Cloud API Routes
  3. Handles authentication and profile management with Bambu Cloud.
  4. """
  5. import json
  6. import logging
  7. from pathlib import Path
  8. from typing import Literal
  9. from fastapi import APIRouter, Body, Depends, HTTPException
  10. from sqlalchemy import select
  11. from sqlalchemy.ext.asyncio import AsyncSession
  12. from backend.app.core.auth import RequirePermissionIfAuthEnabled
  13. from backend.app.core.database import get_db
  14. from backend.app.core.permissions import Permission
  15. from backend.app.models.settings import Settings
  16. from backend.app.models.user import User
  17. from backend.app.schemas.cloud import (
  18. CloudAuthStatus,
  19. CloudDevice,
  20. CloudLoginRequest,
  21. CloudLoginResponse,
  22. CloudTokenRequest,
  23. CloudVerifyRequest,
  24. FirmwareUpdateInfo,
  25. FirmwareUpdatesResponse,
  26. SlicerSetting,
  27. SlicerSettingCreate,
  28. SlicerSettingDeleteResponse,
  29. SlicerSettingsResponse,
  30. SlicerSettingUpdate,
  31. )
  32. from backend.app.services.bambu_cloud import (
  33. BambuCloudAuthError,
  34. BambuCloudError,
  35. BambuCloudService,
  36. )
  37. from backend.app.utils.filament_ids import filament_id_to_setting_id
  38. logger = logging.getLogger(__name__)
  39. router = APIRouter(prefix="/cloud", tags=["cloud"])
  40. # Keys for storing cloud credentials in settings
  41. CLOUD_TOKEN_KEY = "bambu_cloud_token"
  42. CLOUD_EMAIL_KEY = "bambu_cloud_email"
  43. CLOUD_REGION_KEY = "bambu_cloud_region"
  44. def _normalise_region(region: str | None) -> str:
  45. """Treat NULL/empty as 'global' for legacy rows that predate the region column."""
  46. return region if region in ("global", "china") else "global"
  47. async def get_stored_token(db: AsyncSession, user: User | None = None) -> tuple[str | None, str | None, str]:
  48. """Get stored cloud token, email, and region.
  49. When a user is provided (auth enabled), returns that user's per-user credentials.
  50. When user is None (auth disabled), falls back to global Settings table.
  51. Region defaults to ``"global"`` when unset (including for rows that predate
  52. the ``cloud_region`` column).
  53. """
  54. if user is not None:
  55. return user.cloud_token, user.cloud_email, _normalise_region(user.cloud_region)
  56. # Fallback: global storage (auth disabled)
  57. result = await db.execute(
  58. select(Settings).where(Settings.key.in_([CLOUD_TOKEN_KEY, CLOUD_EMAIL_KEY, CLOUD_REGION_KEY]))
  59. )
  60. settings = {s.key: s.value for s in result.scalars().all()}
  61. return (
  62. settings.get(CLOUD_TOKEN_KEY),
  63. settings.get(CLOUD_EMAIL_KEY),
  64. _normalise_region(settings.get(CLOUD_REGION_KEY)),
  65. )
  66. async def store_token(db: AsyncSession, token: str, email: str, region: str, user: User | None = None) -> None:
  67. """Store cloud token, email, and region.
  68. When a user is provided (auth enabled), stores on the user record.
  69. When user is None (auth disabled), stores in global Settings table.
  70. """
  71. region = _normalise_region(region)
  72. if user is not None:
  73. # User object is from the auth dependency's session (detached),
  74. # so use a direct UPDATE via the route's db session.
  75. from sqlalchemy import update
  76. await db.execute(
  77. update(User).where(User.id == user.id).values(cloud_token=token, cloud_email=email, cloud_region=region)
  78. )
  79. await db.commit()
  80. return
  81. # Fallback: global storage (auth disabled)
  82. for key, value in [(CLOUD_TOKEN_KEY, token), (CLOUD_EMAIL_KEY, email), (CLOUD_REGION_KEY, region)]:
  83. result = await db.execute(select(Settings).where(Settings.key == key))
  84. setting = result.scalar_one_or_none()
  85. if setting:
  86. setting.value = value
  87. else:
  88. db.add(Settings(key=key, value=value))
  89. await db.commit()
  90. async def clear_token(db: AsyncSession, user: User | None = None) -> None:
  91. """Clear stored cloud token, email, and region.
  92. When a user is provided (auth enabled), clears that user's credentials.
  93. When user is None (auth disabled), clears from global Settings table.
  94. """
  95. if user is not None:
  96. from sqlalchemy import update
  97. await db.execute(
  98. update(User).where(User.id == user.id).values(cloud_token=None, cloud_email=None, cloud_region=None)
  99. )
  100. await db.commit()
  101. return
  102. # Fallback: global storage (auth disabled)
  103. result = await db.execute(
  104. select(Settings).where(Settings.key.in_([CLOUD_TOKEN_KEY, CLOUD_EMAIL_KEY, CLOUD_REGION_KEY]))
  105. )
  106. for setting in result.scalars().all():
  107. await db.delete(setting)
  108. await db.commit()
  109. async def build_authenticated_cloud(db: AsyncSession, user: User | None) -> BambuCloudService | None:
  110. """Build a per-request cloud service seeded with the caller's stored token + region.
  111. Returns ``None`` when no token is stored, so callers can 401 without constructing
  112. (and then closing) a useless client. Caller is responsible for ``await cloud.close()``.
  113. """
  114. token, _email, region = await get_stored_token(db, user)
  115. if not token:
  116. return None
  117. cloud = BambuCloudService(region=region)
  118. cloud.set_token(token)
  119. return cloud
  120. @router.get("/status", response_model=CloudAuthStatus)
  121. async def get_auth_status(
  122. db: AsyncSession = Depends(get_db),
  123. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.CLOUD_AUTH),
  124. ):
  125. """Get current cloud authentication status.
  126. Reads the stored credentials in one DB round-trip (we used to call
  127. ``get_stored_token`` twice — once here and once inside
  128. ``build_authenticated_cloud``). ``region`` is exposed so the frontend can
  129. show "Connected (China)" after a reload without relying on local state.
  130. """
  131. token, email, region = await get_stored_token(db, current_user)
  132. if not token:
  133. return CloudAuthStatus(is_authenticated=False, email=None, region=None)
  134. cloud = BambuCloudService(region=region)
  135. cloud.set_token(token)
  136. try:
  137. authenticated = cloud.is_authenticated
  138. return CloudAuthStatus(
  139. is_authenticated=authenticated,
  140. email=email if authenticated else None,
  141. region=region if authenticated else None,
  142. )
  143. finally:
  144. await cloud.close()
  145. @router.post("/login", response_model=CloudLoginResponse)
  146. async def login(
  147. request: CloudLoginRequest,
  148. db: AsyncSession = Depends(get_db),
  149. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.CLOUD_AUTH),
  150. ):
  151. """
  152. Initiate login to Bambu Cloud.
  153. This will trigger either:
  154. - Email verification: A code is sent to the user's email
  155. - TOTP verification: User enters code from their authenticator app
  156. After receiving/generating the code, call /cloud/verify to complete the login.
  157. For TOTP, include the tfa_key from this response in the verify request.
  158. """
  159. cloud = BambuCloudService(region=request.region)
  160. try:
  161. result = await cloud.login_request(request.email, request.password)
  162. if result.get("success") and cloud.access_token:
  163. # Direct login succeeded (rare)
  164. await store_token(db, cloud.access_token, request.email, request.region, current_user)
  165. return CloudLoginResponse(
  166. success=result.get("success", False),
  167. needs_verification=result.get("needs_verification", False),
  168. message=result.get("message", "Unknown error"),
  169. verification_type=result.get("verification_type"),
  170. tfa_key=result.get("tfa_key"),
  171. )
  172. except BambuCloudAuthError as e:
  173. raise HTTPException(status_code=401, detail=str(e))
  174. except BambuCloudError as e:
  175. raise HTTPException(status_code=500, detail=str(e))
  176. finally:
  177. await cloud.close()
  178. @router.post("/verify", response_model=CloudLoginResponse)
  179. async def verify_code(
  180. request: CloudVerifyRequest,
  181. db: AsyncSession = Depends(get_db),
  182. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.CLOUD_AUTH),
  183. ):
  184. """
  185. Complete login with verification code (email or TOTP).
  186. For email verification:
  187. - After calling /cloud/login, the user receives an email with a 6-digit code
  188. - Submit the code with email address
  189. For TOTP verification:
  190. - The user enters the 6-digit code from their authenticator app
  191. - Include the tfa_key from the /cloud/login response
  192. ``request.region`` must match the region used in /cloud/login so that the
  193. TOTP call hits the correct TFA endpoint (bambulab.com vs bambulab.cn).
  194. """
  195. cloud = BambuCloudService(region=request.region)
  196. try:
  197. # Use TOTP verification if tfa_key is provided
  198. if request.tfa_key:
  199. result = await cloud.verify_totp(request.tfa_key, request.code)
  200. else:
  201. result = await cloud.verify_code(request.email, request.code)
  202. if result.get("success") and cloud.access_token:
  203. await store_token(db, cloud.access_token, request.email, request.region, current_user)
  204. return CloudLoginResponse(
  205. success=result.get("success", False),
  206. needs_verification=False,
  207. message=result.get("message", "Unknown error"),
  208. )
  209. except BambuCloudAuthError as e:
  210. raise HTTPException(status_code=401, detail=str(e))
  211. except BambuCloudError as e:
  212. raise HTTPException(status_code=500, detail=str(e))
  213. finally:
  214. await cloud.close()
  215. @router.post("/token", response_model=CloudAuthStatus)
  216. async def set_token(
  217. request: CloudTokenRequest,
  218. db: AsyncSession = Depends(get_db),
  219. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.CLOUD_AUTH),
  220. ):
  221. """
  222. Set access token directly.
  223. For users who already have a token (e.g., from Bambu Studio). The
  224. selected ``region`` is persisted alongside the token so every subsequent
  225. request hits the right Bambu API endpoint, including after a restart.
  226. """
  227. cloud = BambuCloudService(region=request.region)
  228. cloud.set_token(request.access_token)
  229. try:
  230. # Verify token works by trying to get profile
  231. await cloud.get_user_profile()
  232. await store_token(db, request.access_token, "token-auth", request.region, current_user)
  233. return CloudAuthStatus(is_authenticated=True, email="token-auth")
  234. except BambuCloudError:
  235. raise HTTPException(status_code=401, detail="Invalid token")
  236. finally:
  237. await cloud.close()
  238. @router.post("/logout")
  239. async def logout(
  240. db: AsyncSession = Depends(get_db),
  241. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.CLOUD_AUTH),
  242. ):
  243. """Log out of Bambu Cloud."""
  244. await clear_token(db, current_user)
  245. return {"success": True}
  246. @router.get("/settings", response_model=SlicerSettingsResponse)
  247. async def get_slicer_settings(
  248. version: str = "02.04.00.70",
  249. db: AsyncSession = Depends(get_db),
  250. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.CLOUD_AUTH),
  251. ):
  252. """
  253. Get all slicer settings (filament, printer, process presets).
  254. Requires authentication.
  255. """
  256. cloud = await build_authenticated_cloud(db, current_user)
  257. if cloud is None or not cloud.is_authenticated:
  258. raise HTTPException(status_code=401, detail="Not authenticated")
  259. try:
  260. data = await cloud.get_slicer_settings(version)
  261. result = SlicerSettingsResponse()
  262. # Map API keys to our types (API uses 'print' for process presets)
  263. type_mapping = {
  264. "filament": "filament",
  265. "printer": "printer",
  266. "print": "process", # API calls it 'print', we call it 'process'
  267. }
  268. for api_key, our_type in type_mapping.items():
  269. type_data = data.get(api_key, {})
  270. private_settings = type_data.get("private", [])
  271. public_settings = type_data.get("public", [])
  272. parsed = []
  273. # Private (custom) presets first
  274. for s in private_settings:
  275. parsed.append(
  276. SlicerSetting(
  277. setting_id=s.get("setting_id", s.get("id", "")),
  278. name=s.get("name", "Unknown"),
  279. type=our_type,
  280. version=s.get("version"),
  281. user_id=s.get("user_id"),
  282. updated_time=s.get("updated_time"),
  283. is_custom=True,
  284. )
  285. )
  286. # Public (default) presets
  287. for s in public_settings:
  288. parsed.append(
  289. SlicerSetting(
  290. setting_id=s.get("setting_id", s.get("id", "")),
  291. name=s.get("name", "Unknown"),
  292. type=our_type,
  293. version=s.get("version"),
  294. user_id=s.get("user_id"),
  295. updated_time=s.get("updated_time"),
  296. is_custom=False,
  297. )
  298. )
  299. setattr(result, our_type, parsed)
  300. return result
  301. except BambuCloudAuthError:
  302. await clear_token(db, current_user)
  303. raise HTTPException(status_code=401, detail="Authentication expired")
  304. except BambuCloudError as e:
  305. raise HTTPException(status_code=500, detail=str(e))
  306. finally:
  307. await cloud.close()
  308. @router.get("/settings/{setting_id}")
  309. async def get_setting_detail(
  310. setting_id: str,
  311. db: AsyncSession = Depends(get_db),
  312. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.CLOUD_AUTH),
  313. ):
  314. """
  315. Get detailed information for a specific setting/preset.
  316. Returns the full preset configuration.
  317. """
  318. cloud = await build_authenticated_cloud(db, current_user)
  319. if cloud is None or not cloud.is_authenticated:
  320. raise HTTPException(status_code=401, detail="Not authenticated")
  321. try:
  322. data = await cloud.get_setting_detail(setting_id)
  323. return data
  324. except BambuCloudAuthError:
  325. await clear_token(db, current_user)
  326. raise HTTPException(status_code=401, detail="Authentication expired")
  327. except BambuCloudError as e:
  328. raise HTTPException(status_code=500, detail=str(e))
  329. finally:
  330. await cloud.close()
  331. @router.get("/filaments", response_model=list[SlicerSetting])
  332. async def get_filament_presets(
  333. version: str = "02.04.00.70",
  334. db: AsyncSession = Depends(get_db),
  335. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_READ),
  336. ):
  337. """
  338. Get just filament presets (convenience endpoint).
  339. Returns all filament presets with custom presets first.
  340. Uses the same cache as get_slicer_settings.
  341. """
  342. settings = await get_slicer_settings(version=version, db=db, current_user=current_user)
  343. return settings.filament
  344. # Cache for filament preset info (setting_id -> {name, k})
  345. _filament_cache: dict[str, dict] = {}
  346. _filament_cache_time: float = 0
  347. FILAMENT_CACHE_TTL = 300 # 5 minutes
  348. # Built-in filament ID → name mapping (fallback when cloud API and local profiles
  349. # don't have the entry). Based on Bambu Lab's known filament catalogue.
  350. _BUILTIN_FILAMENT_NAMES: dict[str, str] = {
  351. "GFA00": "Bambu PLA Basic",
  352. "GFA01": "Bambu PLA Matte",
  353. "GFA02": "Bambu PLA Metal",
  354. "GFA05": "Bambu PLA Silk",
  355. "GFA06": "Bambu PLA Silk+",
  356. "GFA07": "Bambu PLA Marble",
  357. "GFA08": "Bambu PLA Sparkle",
  358. "GFA09": "Bambu PLA Tough",
  359. "GFA11": "Bambu PLA Aero",
  360. "GFA12": "Bambu PLA Glow",
  361. "GFA13": "Bambu PLA Dynamic",
  362. "GFA15": "Bambu PLA Galaxy",
  363. "GFA16": "Bambu PLA Wood",
  364. "GFA50": "Bambu PLA-CF",
  365. "GFB00": "Bambu ABS",
  366. "GFB01": "Bambu ASA",
  367. "GFB02": "Bambu ASA-Aero",
  368. "GFB50": "Bambu ABS-GF",
  369. "GFB51": "Bambu ASA-CF",
  370. "GFB60": "PolyLite ABS",
  371. "GFB61": "PolyLite ASA",
  372. "GFB98": "Generic ASA",
  373. "GFB99": "Generic ABS",
  374. "GFC00": "Bambu PC",
  375. "GFC01": "Bambu PC FR",
  376. "GFC99": "Generic PC",
  377. "GFG00": "Bambu PETG Basic",
  378. "GFG01": "Bambu PETG Translucent",
  379. "GFG02": "Bambu PETG HF",
  380. "GFG50": "Bambu PETG-CF",
  381. "GFG60": "PolyLite PETG",
  382. "GFG96": "Generic PETG HF",
  383. "GFG97": "Generic PCTG",
  384. "GFG98": "Generic PETG-CF",
  385. "GFG99": "Generic PETG",
  386. "GFL00": "PolyLite PLA",
  387. "GFL01": "PolyTerra PLA",
  388. "GFL03": "eSUN PLA+",
  389. "GFL04": "Overture PLA",
  390. "GFL05": "Overture Matte PLA",
  391. "GFL06": "Fiberon PETG-ESD",
  392. "GFL50": "Fiberon PA6-CF",
  393. "GFL51": "Fiberon PA6-GF",
  394. "GFL52": "Fiberon PA12-CF",
  395. "GFL53": "Fiberon PA612-CF",
  396. "GFL54": "Fiberon PET-CF",
  397. "GFL55": "Fiberon PETG-rCF",
  398. "GFL95": "Generic PLA High Speed",
  399. "GFL96": "Generic PLA Silk",
  400. "GFL98": "Generic PLA-CF",
  401. "GFL99": "Generic PLA",
  402. "GFN03": "Bambu PA-CF",
  403. "GFN04": "Bambu PAHT-CF",
  404. "GFN05": "Bambu PA6-CF",
  405. "GFN06": "Bambu PPA-CF",
  406. "GFN08": "Bambu PA6-GF",
  407. "GFN96": "Generic PPA-GF",
  408. "GFN97": "Generic PPA-CF",
  409. "GFN98": "Generic PA-CF",
  410. "GFN99": "Generic PA",
  411. "GFP95": "Generic PP-GF",
  412. "GFP96": "Generic PP-CF",
  413. "GFP97": "Generic PP",
  414. "GFP98": "Generic PE-CF",
  415. "GFP99": "Generic PE",
  416. "GFR98": "Generic PHA",
  417. "GFR99": "Generic EVA",
  418. "GFS00": "Bambu Support W",
  419. "GFS01": "Bambu Support G",
  420. "GFS02": "Bambu Support For PLA",
  421. "GFS03": "Bambu Support For PA/PET",
  422. "GFS04": "Bambu PVA",
  423. "GFS05": "Bambu Support For PLA/PETG",
  424. "GFS06": "Bambu Support for ABS",
  425. "GFS97": "Generic BVOH",
  426. "GFS98": "Generic HIPS",
  427. "GFS99": "Generic PVA",
  428. "GFT01": "Bambu PET-CF",
  429. "GFT02": "Bambu PPS-CF",
  430. "GFT97": "Generic PPS",
  431. "GFT98": "Generic PPS-CF",
  432. "GFU00": "Bambu TPU 95A HF",
  433. "GFU01": "Bambu TPU 95A",
  434. "GFU02": "Bambu TPU for AMS",
  435. "GFU98": "Generic TPU for AMS",
  436. "GFU99": "Generic TPU",
  437. }
  438. async def _enrich_from_local_presets(
  439. unresolved_ids: list[str],
  440. result: dict,
  441. db: AsyncSession,
  442. ) -> dict:
  443. """Fall back to local profiles for filament IDs not resolved by cloud.
  444. Matches by checking the setting_id field inside the local preset's
  445. resolved JSON blob (stored in the 'setting' column).
  446. """
  447. from sqlalchemy import text
  448. from backend.app.models.local_preset import LocalPreset
  449. # Build lookup: converted setting_id -> original filament_id
  450. id_map: dict[str, str] = {}
  451. for fid in unresolved_ids:
  452. converted = _filament_id_to_setting_id(fid)
  453. id_map[converted] = fid
  454. # Also map the original in case the JSON uses that form
  455. id_map[fid] = fid
  456. try:
  457. # Query filament presets that have a setting_id matching any of our IDs
  458. from backend.app.core.db_dialect import is_sqlite
  459. if is_sqlite():
  460. json_filter = text("json_extract(setting, '$.setting_id') IS NOT NULL")
  461. else:
  462. json_filter = text("(setting::jsonb->>'setting_id') IS NOT NULL")
  463. candidates = await db.execute(
  464. select(LocalPreset).where(
  465. LocalPreset.preset_type == "filament",
  466. json_filter,
  467. )
  468. )
  469. for preset in candidates.scalars().all():
  470. try:
  471. setting_data = json.loads(preset.setting) if isinstance(preset.setting, str) else preset.setting
  472. preset_setting_id = setting_data.get("setting_id", "")
  473. if preset_setting_id in id_map:
  474. original_id = id_map[preset_setting_id]
  475. info = {"name": preset.name, "k": None}
  476. # Try to extract K value from the local preset
  477. pa = setting_data.get("pressure_advance")
  478. if pa is not None:
  479. try:
  480. k_val = float(pa[0]) if isinstance(pa, list) else float(pa)
  481. info["k"] = k_val
  482. except (ValueError, TypeError, IndexError):
  483. pass
  484. _filament_cache[original_id] = info
  485. result[original_id] = info
  486. except Exception:
  487. continue
  488. except Exception as e:
  489. logger.warning("Failed to search local presets for filament info: %s", e)
  490. # Phase 4: Fall back to built-in filament name table for any still without a name
  491. for fid in unresolved_ids:
  492. if fid not in result or not result[fid].get("name"):
  493. name = _BUILTIN_FILAMENT_NAMES.get(fid, "")
  494. if name:
  495. # Preserve K value from earlier phases if available
  496. existing_k = result.get(fid, {}).get("k")
  497. info = {"name": name, "k": existing_k}
  498. _filament_cache[fid] = info
  499. result[fid] = info
  500. # Fill remaining unresolved with empty entries
  501. for fid in unresolved_ids:
  502. if fid not in result:
  503. _filament_cache[fid] = {"name": "", "k": None}
  504. result[fid] = {"name": "", "k": None}
  505. return result
  506. # _filament_id_to_setting_id is now imported from backend.app.utils.filament_ids
  507. _filament_id_to_setting_id = filament_id_to_setting_id
  508. @router.post("/filament-info")
  509. async def get_filament_info(
  510. setting_ids: list[str] = Body(...),
  511. db: AsyncSession = Depends(get_db),
  512. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_READ),
  513. ):
  514. """
  515. Get filament preset info (name and K value) for multiple setting IDs.
  516. Used to enrich AMS tray and nozzle rack tooltips with preset data.
  517. Lookup order: cache → cloud → local profiles → built-in table → empty fallback.
  518. """
  519. import time
  520. logger.info("get_filament_info called with %s IDs: %s", len(setting_ids), setting_ids)
  521. global _filament_cache, _filament_cache_time
  522. # Clear stale cache
  523. if time.time() - _filament_cache_time > FILAMENT_CACHE_TTL:
  524. _filament_cache = {}
  525. _filament_cache_time = time.time()
  526. result = {}
  527. unresolved_ids: list[str] = []
  528. # Phase 1: Check cache
  529. for setting_id in setting_ids:
  530. if not setting_id:
  531. continue
  532. if setting_id in _filament_cache:
  533. result[setting_id] = _filament_cache[setting_id]
  534. else:
  535. unresolved_ids.append(setting_id)
  536. # Phase 2: Try cloud for uncached IDs
  537. if unresolved_ids:
  538. cloud = await build_authenticated_cloud(db, current_user)
  539. if cloud is not None and cloud.is_authenticated:
  540. try:
  541. still_unresolved: list[str] = []
  542. for setting_id in unresolved_ids:
  543. try:
  544. api_setting_id = _filament_id_to_setting_id(setting_id)
  545. data = await cloud.get_setting_detail(api_setting_id)
  546. setting = data.get("setting", {})
  547. name = data.get("name", "")
  548. k_value = setting.get("pressure_advance")
  549. if k_value is not None:
  550. try:
  551. k_value = float(k_value)
  552. except (ValueError, TypeError):
  553. k_value = None
  554. info = {"name": name, "k": k_value}
  555. _filament_cache[setting_id] = info
  556. result[setting_id] = info
  557. if not name:
  558. still_unresolved.append(setting_id)
  559. except Exception as e:
  560. logger.warning(
  561. f"Failed to get cloud preset {setting_id} "
  562. f"(API ID: {_filament_id_to_setting_id(setting_id)}): {e}"
  563. )
  564. still_unresolved.append(setting_id)
  565. unresolved_ids = still_unresolved
  566. finally:
  567. await cloud.close()
  568. elif cloud is not None:
  569. await cloud.close()
  570. # Phase 3: Try local profiles for any IDs still without a name
  571. if unresolved_ids:
  572. result = await _enrich_from_local_presets(unresolved_ids, result, db)
  573. return result
  574. @router.get("/devices", response_model=list[CloudDevice])
  575. async def get_devices(
  576. db: AsyncSession = Depends(get_db),
  577. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  578. ):
  579. """
  580. Get list of bound printer devices.
  581. Returns printers registered to the user's Bambu account.
  582. """
  583. cloud = await build_authenticated_cloud(db, current_user)
  584. if cloud is None or not cloud.is_authenticated:
  585. raise HTTPException(status_code=401, detail="Not authenticated")
  586. try:
  587. data = await cloud.get_devices()
  588. devices = data.get("devices", [])
  589. return [
  590. CloudDevice(
  591. dev_id=d.get("dev_id", ""),
  592. name=d.get("name", "Unknown"),
  593. dev_model_name=d.get("dev_model_name"),
  594. dev_product_name=d.get("dev_product_name"),
  595. online=d.get("online", False),
  596. )
  597. for d in devices
  598. ]
  599. except BambuCloudAuthError:
  600. await clear_token(db, current_user)
  601. raise HTTPException(status_code=401, detail="Authentication expired")
  602. except BambuCloudError as e:
  603. raise HTTPException(status_code=500, detail=str(e))
  604. finally:
  605. await cloud.close()
  606. @router.get("/firmware-updates", response_model=FirmwareUpdatesResponse)
  607. async def get_firmware_updates(
  608. db: AsyncSession = Depends(get_db),
  609. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.FIRMWARE_READ),
  610. ):
  611. """
  612. Check for firmware updates for all bound devices.
  613. Returns firmware version info for each device including:
  614. - Current installed version
  615. - Latest available version
  616. - Whether an update is available
  617. - Release notes for the latest version
  618. Requires cloud authentication.
  619. """
  620. cloud = await build_authenticated_cloud(db, current_user)
  621. if cloud is None or not cloud.is_authenticated:
  622. raise HTTPException(status_code=401, detail="Not authenticated")
  623. try:
  624. # First get list of bound devices
  625. devices_data = await cloud.get_devices()
  626. devices = devices_data.get("devices", [])
  627. updates = []
  628. updates_available = 0
  629. # Check firmware for each device
  630. for device in devices:
  631. device_id = device.get("dev_id", "")
  632. device_name = device.get("name", "Unknown")
  633. try:
  634. firmware_info = await cloud.get_firmware_version(device_id)
  635. update_available = firmware_info.get("update_available", False)
  636. if update_available:
  637. updates_available += 1
  638. updates.append(
  639. FirmwareUpdateInfo(
  640. device_id=device_id,
  641. device_name=device_name,
  642. current_version=firmware_info.get("current_version"),
  643. latest_version=firmware_info.get("latest_version"),
  644. update_available=update_available,
  645. release_notes=firmware_info.get("release_notes"),
  646. )
  647. )
  648. except BambuCloudError as e:
  649. logger.warning("Failed to get firmware info for %s: %s", device_name, e)
  650. # Still include device but with unknown firmware status
  651. updates.append(
  652. FirmwareUpdateInfo(
  653. device_id=device_id,
  654. device_name=device_name,
  655. current_version=None,
  656. latest_version=None,
  657. update_available=False,
  658. release_notes=None,
  659. )
  660. )
  661. return FirmwareUpdatesResponse(updates=updates, updates_available=updates_available)
  662. except BambuCloudAuthError:
  663. await clear_token(db, current_user)
  664. raise HTTPException(status_code=401, detail="Authentication expired")
  665. except BambuCloudError as e:
  666. raise HTTPException(status_code=500, detail=str(e))
  667. finally:
  668. await cloud.close()
  669. @router.post("/settings")
  670. async def create_setting(
  671. request: SlicerSettingCreate,
  672. db: AsyncSession = Depends(get_db),
  673. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.CLOUD_AUTH),
  674. ):
  675. """
  676. Create a new slicer preset/setting.
  677. Creates a new preset on Bambu Cloud. The preset inherits from a base preset
  678. and only stores the delta (modified values).
  679. Type should be: 'filament', 'print', or 'printer'
  680. """
  681. cloud = await build_authenticated_cloud(db, current_user)
  682. if cloud is None or not cloud.is_authenticated:
  683. raise HTTPException(status_code=401, detail="Not authenticated")
  684. try:
  685. data = await cloud.create_setting(
  686. preset_type=request.type,
  687. name=request.name,
  688. base_id=request.base_id,
  689. setting=request.setting,
  690. version=request.version,
  691. )
  692. return data
  693. except BambuCloudAuthError:
  694. await clear_token(db, current_user)
  695. raise HTTPException(status_code=401, detail="Authentication expired")
  696. except BambuCloudError as e:
  697. raise HTTPException(status_code=500, detail=str(e))
  698. finally:
  699. await cloud.close()
  700. @router.put("/settings/{setting_id}")
  701. async def update_setting(
  702. setting_id: str,
  703. request: SlicerSettingUpdate,
  704. db: AsyncSession = Depends(get_db),
  705. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.CLOUD_AUTH),
  706. ):
  707. """
  708. Update an existing slicer preset/setting.
  709. Updates the preset's name and/or settings on Bambu Cloud.
  710. """
  711. cloud = await build_authenticated_cloud(db, current_user)
  712. if cloud is None or not cloud.is_authenticated:
  713. raise HTTPException(status_code=401, detail="Not authenticated")
  714. try:
  715. data = await cloud.update_setting(
  716. setting_id=setting_id,
  717. name=request.name,
  718. setting=request.setting,
  719. )
  720. return data
  721. except BambuCloudAuthError:
  722. await clear_token(db, current_user)
  723. raise HTTPException(status_code=401, detail="Authentication expired")
  724. except BambuCloudError as e:
  725. raise HTTPException(status_code=500, detail=str(e))
  726. finally:
  727. await cloud.close()
  728. @router.delete("/settings/{setting_id}", response_model=SlicerSettingDeleteResponse)
  729. async def delete_setting(
  730. setting_id: str,
  731. db: AsyncSession = Depends(get_db),
  732. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.CLOUD_AUTH),
  733. ):
  734. """
  735. Delete a slicer preset/setting.
  736. Removes the preset from Bambu Cloud. This cannot be undone.
  737. """
  738. cloud = await build_authenticated_cloud(db, current_user)
  739. if cloud is None or not cloud.is_authenticated:
  740. raise HTTPException(status_code=401, detail="Not authenticated")
  741. try:
  742. result = await cloud.delete_setting(setting_id)
  743. return SlicerSettingDeleteResponse(
  744. success=result.get("success", True),
  745. message=result.get("message", "Setting deleted"),
  746. )
  747. except BambuCloudAuthError:
  748. await clear_token(db, current_user)
  749. raise HTTPException(status_code=401, detail="Authentication expired")
  750. except BambuCloudError as e:
  751. raise HTTPException(status_code=500, detail=str(e))
  752. finally:
  753. await cloud.close()
  754. # Path to field definition files
  755. FIELDS_DATA_DIR = Path(__file__).parent.parent.parent / "data"
  756. # Cache for field definitions (loaded once)
  757. _fields_cache: dict[str, dict] = {}
  758. def _load_fields(preset_type: str) -> dict:
  759. """Load field definitions from JSON file."""
  760. if preset_type in _fields_cache:
  761. return _fields_cache[preset_type]
  762. # Map API type names to file names
  763. file_map = {
  764. "filament": "filament_fields.json",
  765. "print": "process_fields.json",
  766. "process": "process_fields.json",
  767. "printer": "printer_fields.json",
  768. }
  769. filename = file_map.get(preset_type)
  770. if not filename:
  771. raise HTTPException(status_code=400, detail=f"Unknown preset type: {preset_type}")
  772. file_path = FIELDS_DATA_DIR / filename
  773. if not file_path.exists():
  774. raise HTTPException(status_code=404, detail=f"Field definitions not found for: {preset_type}")
  775. with open(file_path) as f:
  776. data = json.load(f)
  777. _fields_cache[preset_type] = data
  778. return data
  779. @router.get("/builtin-filaments")
  780. async def get_builtin_filaments(
  781. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_READ),
  782. ):
  783. """
  784. Get built-in filament names as a fallback source.
  785. Returns the static _BUILTIN_FILAMENT_NAMES table as a list of
  786. {filament_id, name} objects. Used by the frontend when cloud
  787. and local profiles are unavailable.
  788. """
  789. return [{"filament_id": fid, "name": name} for fid, name in _BUILTIN_FILAMENT_NAMES.items()]
  790. # Cache for filament_id → name mapping (resolved from cloud preset details)
  791. _filament_id_name_cache: dict[str, str] = {}
  792. _filament_id_name_cache_time: float = 0
  793. @router.get("/filament-id-map")
  794. async def get_filament_id_map(
  795. db: AsyncSession = Depends(get_db),
  796. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_READ),
  797. ):
  798. """
  799. Get filament_id → name mapping for user cloud presets.
  800. K-profiles store a filament_id (e.g., "P4d64437") which is different from
  801. the cloud preset setting_id (e.g., "PFUS9ac902733670a9"). This endpoint
  802. fetches details for all custom presets and returns the mapping.
  803. Cached for 5 minutes.
  804. """
  805. import time
  806. global _filament_id_name_cache, _filament_id_name_cache_time
  807. if _filament_id_name_cache and time.time() - _filament_id_name_cache_time < FILAMENT_CACHE_TTL:
  808. return _filament_id_name_cache
  809. cloud = await build_authenticated_cloud(db, current_user)
  810. if cloud is None or not cloud.is_authenticated:
  811. if cloud is not None:
  812. await cloud.close()
  813. return _filament_id_name_cache or {}
  814. try:
  815. data = await cloud.get_slicer_settings()
  816. custom_presets = data.get("filament", {}).get("private", [])
  817. result: dict[str, str] = {}
  818. for preset in custom_presets:
  819. setting_id = preset.get("setting_id", "")
  820. if not setting_id:
  821. continue
  822. try:
  823. detail = await cloud.get_setting_detail(setting_id)
  824. fid = detail.get("filament_id", "")
  825. name = detail.get("name", "")
  826. if fid and name:
  827. # Strip printer/nozzle suffix: "Devil Design PLA Basic @Bambu Lab H2D 0.4 nozzle" → "Devil Design PLA Basic"
  828. clean_name = name.split(" @")[0].strip() if " @" in name else name
  829. result[fid] = clean_name
  830. except Exception:
  831. pass
  832. _filament_id_name_cache = result
  833. _filament_id_name_cache_time = time.time()
  834. return result
  835. except Exception:
  836. return _filament_id_name_cache or {}
  837. finally:
  838. await cloud.close()
  839. @router.get("/fields/{preset_type}")
  840. async def get_preset_fields(
  841. preset_type: Literal["filament", "print", "process", "printer"],
  842. _: User | None = RequirePermissionIfAuthEnabled(Permission.CLOUD_AUTH),
  843. ):
  844. """
  845. Get field definitions for a preset type.
  846. Returns a list of field definitions including:
  847. - key: The setting key name
  848. - label: Human-readable label
  849. - type: Field type (text, number, boolean, select)
  850. - category: Grouping category
  851. - description: Field description
  852. - options: For select fields, available options
  853. - unit: Unit of measurement (if applicable)
  854. - min/max/step: For number fields, validation constraints
  855. """
  856. data = _load_fields(preset_type)
  857. return data
  858. @router.get("/fields")
  859. async def get_all_preset_fields(
  860. _: User | None = RequirePermissionIfAuthEnabled(Permission.CLOUD_AUTH),
  861. ):
  862. """
  863. Get all field definitions for all preset types.
  864. Returns field definitions organized by type.
  865. """
  866. return {
  867. "filament": _load_fields("filament"),
  868. "process": _load_fields("process"),
  869. "printer": _load_fields("printer"),
  870. }