cloud.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  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. get_cloud_service,
  36. )
  37. logger = logging.getLogger(__name__)
  38. router = APIRouter(prefix="/cloud", tags=["cloud"])
  39. # Keys for storing cloud credentials in settings
  40. CLOUD_TOKEN_KEY = "bambu_cloud_token"
  41. CLOUD_EMAIL_KEY = "bambu_cloud_email"
  42. async def get_stored_token(db: AsyncSession) -> tuple[str | None, str | None]:
  43. """Get stored cloud token and email from database."""
  44. result = await db.execute(select(Settings).where(Settings.key.in_([CLOUD_TOKEN_KEY, CLOUD_EMAIL_KEY])))
  45. settings = {s.key: s.value for s in result.scalars().all()}
  46. return settings.get(CLOUD_TOKEN_KEY), settings.get(CLOUD_EMAIL_KEY)
  47. async def store_token(db: AsyncSession, token: str, email: str) -> None:
  48. """Store cloud token and email in database."""
  49. for key, value in [(CLOUD_TOKEN_KEY, token), (CLOUD_EMAIL_KEY, email)]:
  50. result = await db.execute(select(Settings).where(Settings.key == key))
  51. setting = result.scalar_one_or_none()
  52. if setting:
  53. setting.value = value
  54. else:
  55. db.add(Settings(key=key, value=value))
  56. await db.commit()
  57. async def clear_token(db: AsyncSession) -> None:
  58. """Clear stored cloud token and email."""
  59. result = await db.execute(select(Settings).where(Settings.key.in_([CLOUD_TOKEN_KEY, CLOUD_EMAIL_KEY])))
  60. for setting in result.scalars().all():
  61. await db.delete(setting)
  62. await db.commit()
  63. @router.get("/status", response_model=CloudAuthStatus)
  64. async def get_auth_status(
  65. db: AsyncSession = Depends(get_db),
  66. _: User | None = RequirePermissionIfAuthEnabled(Permission.CLOUD_AUTH),
  67. ):
  68. """Get current cloud authentication status."""
  69. token, email = await get_stored_token(db)
  70. cloud = get_cloud_service()
  71. if token:
  72. cloud.set_token(token)
  73. return CloudAuthStatus(
  74. is_authenticated=cloud.is_authenticated,
  75. email=email if cloud.is_authenticated else None,
  76. )
  77. @router.post("/login", response_model=CloudLoginResponse)
  78. async def login(
  79. request: CloudLoginRequest,
  80. db: AsyncSession = Depends(get_db),
  81. _: User | None = RequirePermissionIfAuthEnabled(Permission.CLOUD_AUTH),
  82. ):
  83. """
  84. Initiate login to Bambu Cloud.
  85. This will trigger either:
  86. - Email verification: A code is sent to the user's email
  87. - TOTP verification: User enters code from their authenticator app
  88. After receiving/generating the code, call /cloud/verify to complete the login.
  89. For TOTP, include the tfa_key from this response in the verify request.
  90. """
  91. cloud = get_cloud_service()
  92. # Store email temporarily for verification step
  93. await store_token(db, "", request.email)
  94. try:
  95. result = await cloud.login_request(request.email, request.password)
  96. if result.get("success") and cloud.access_token:
  97. # Direct login succeeded (rare)
  98. await store_token(db, cloud.access_token, request.email)
  99. return CloudLoginResponse(
  100. success=result.get("success", False),
  101. needs_verification=result.get("needs_verification", False),
  102. message=result.get("message", "Unknown error"),
  103. verification_type=result.get("verification_type"),
  104. tfa_key=result.get("tfa_key"),
  105. )
  106. except BambuCloudAuthError as e:
  107. raise HTTPException(status_code=401, detail=str(e))
  108. except BambuCloudError as e:
  109. raise HTTPException(status_code=500, detail=str(e))
  110. @router.post("/verify", response_model=CloudLoginResponse)
  111. async def verify_code(
  112. request: CloudVerifyRequest,
  113. db: AsyncSession = Depends(get_db),
  114. _: User | None = RequirePermissionIfAuthEnabled(Permission.CLOUD_AUTH),
  115. ):
  116. """
  117. Complete login with verification code (email or TOTP).
  118. For email verification:
  119. - After calling /cloud/login, the user receives an email with a 6-digit code
  120. - Submit the code with email address
  121. For TOTP verification:
  122. - The user enters the 6-digit code from their authenticator app
  123. - Include the tfa_key from the /cloud/login response
  124. """
  125. cloud = get_cloud_service()
  126. try:
  127. # Use TOTP verification if tfa_key is provided
  128. if request.tfa_key:
  129. result = await cloud.verify_totp(request.tfa_key, request.code)
  130. else:
  131. result = await cloud.verify_code(request.email, request.code)
  132. if result.get("success") and cloud.access_token:
  133. await store_token(db, cloud.access_token, request.email)
  134. return CloudLoginResponse(
  135. success=result.get("success", False),
  136. needs_verification=False,
  137. message=result.get("message", "Unknown error"),
  138. )
  139. except BambuCloudAuthError as e:
  140. raise HTTPException(status_code=401, detail=str(e))
  141. except BambuCloudError as e:
  142. raise HTTPException(status_code=500, detail=str(e))
  143. @router.post("/token", response_model=CloudAuthStatus)
  144. async def set_token(
  145. request: CloudTokenRequest,
  146. db: AsyncSession = Depends(get_db),
  147. _: User | None = RequirePermissionIfAuthEnabled(Permission.CLOUD_AUTH),
  148. ):
  149. """
  150. Set access token directly.
  151. For users who already have a token (e.g., from Bambu Studio).
  152. """
  153. cloud = get_cloud_service()
  154. cloud.set_token(request.access_token)
  155. # Verify token works by trying to get profile
  156. try:
  157. await cloud.get_user_profile()
  158. await store_token(db, request.access_token, "token-auth")
  159. return CloudAuthStatus(is_authenticated=True, email="token-auth")
  160. except BambuCloudError:
  161. cloud.logout()
  162. raise HTTPException(status_code=401, detail="Invalid token")
  163. @router.post("/logout")
  164. async def logout(
  165. db: AsyncSession = Depends(get_db),
  166. _: User | None = RequirePermissionIfAuthEnabled(Permission.CLOUD_AUTH),
  167. ):
  168. """Log out of Bambu Cloud."""
  169. cloud = get_cloud_service()
  170. cloud.logout()
  171. await clear_token(db)
  172. return {"success": True}
  173. @router.get("/settings", response_model=SlicerSettingsResponse)
  174. async def get_slicer_settings(
  175. version: str = "02.04.00.70",
  176. db: AsyncSession = Depends(get_db),
  177. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  178. ):
  179. """
  180. Get all slicer settings (filament, printer, process presets).
  181. Requires authentication.
  182. """
  183. token, _ = await get_stored_token(db)
  184. if not token:
  185. raise HTTPException(status_code=401, detail="Not authenticated")
  186. cloud = get_cloud_service()
  187. cloud.set_token(token)
  188. if not cloud.is_authenticated:
  189. raise HTTPException(status_code=401, detail="Not authenticated")
  190. try:
  191. data = await cloud.get_slicer_settings(version)
  192. result = SlicerSettingsResponse()
  193. # Map API keys to our types (API uses 'print' for process presets)
  194. type_mapping = {
  195. "filament": "filament",
  196. "printer": "printer",
  197. "print": "process", # API calls it 'print', we call it 'process'
  198. }
  199. for api_key, our_type in type_mapping.items():
  200. type_data = data.get(api_key, {})
  201. # Combine public and private presets, private (user's own) first
  202. all_settings = type_data.get("private", []) + type_data.get("public", [])
  203. parsed = []
  204. for s in all_settings:
  205. parsed.append(
  206. SlicerSetting(
  207. setting_id=s.get("setting_id", s.get("id", "")),
  208. name=s.get("name", "Unknown"),
  209. type=our_type,
  210. version=s.get("version"),
  211. user_id=s.get("user_id"),
  212. updated_time=s.get("updated_time"),
  213. )
  214. )
  215. setattr(result, our_type, parsed)
  216. return result
  217. except BambuCloudAuthError:
  218. await clear_token(db)
  219. raise HTTPException(status_code=401, detail="Authentication expired")
  220. except BambuCloudError as e:
  221. raise HTTPException(status_code=500, detail=str(e))
  222. @router.get("/settings/{setting_id}")
  223. async def get_setting_detail(
  224. setting_id: str,
  225. db: AsyncSession = Depends(get_db),
  226. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  227. ):
  228. """
  229. Get detailed information for a specific setting/preset.
  230. Returns the full preset configuration.
  231. """
  232. token, _ = await get_stored_token(db)
  233. if not token:
  234. raise HTTPException(status_code=401, detail="Not authenticated")
  235. cloud = get_cloud_service()
  236. cloud.set_token(token)
  237. if not cloud.is_authenticated:
  238. raise HTTPException(status_code=401, detail="Not authenticated")
  239. try:
  240. data = await cloud.get_setting_detail(setting_id)
  241. return data
  242. except BambuCloudAuthError:
  243. await clear_token(db)
  244. raise HTTPException(status_code=401, detail="Authentication expired")
  245. except BambuCloudError as e:
  246. raise HTTPException(status_code=500, detail=str(e))
  247. # Cache for filament preset info (setting_id -> {name, k})
  248. _filament_cache: dict[str, dict] = {}
  249. _filament_cache_time: float = 0
  250. FILAMENT_CACHE_TTL = 300 # 5 minutes
  251. # Built-in filament ID → name mapping (fallback when cloud API and local profiles
  252. # don't have the entry). Based on Bambu Lab's known filament catalogue.
  253. _BUILTIN_FILAMENT_NAMES: dict[str, str] = {
  254. "GFA00": "Bambu PLA Basic",
  255. "GFA01": "Bambu PLA Matte",
  256. "GFA02": "Bambu PLA Metal",
  257. "GFA05": "Bambu PLA Silk",
  258. "GFA06": "Bambu PLA Silk+",
  259. "GFA07": "Bambu PLA Marble",
  260. "GFA08": "Bambu PLA Sparkle",
  261. "GFA09": "Bambu PLA Tough",
  262. "GFA11": "Bambu PLA Aero",
  263. "GFA12": "Bambu PLA Glow",
  264. "GFA13": "Bambu PLA Dynamic",
  265. "GFA15": "Bambu PLA Galaxy",
  266. "GFA16": "Bambu PLA Wood",
  267. "GFA50": "Bambu PLA-CF",
  268. "GFB00": "Bambu ABS",
  269. "GFB01": "Bambu ASA",
  270. "GFB02": "Bambu ASA-Aero",
  271. "GFB50": "Bambu ABS-GF",
  272. "GFB51": "Bambu ASA-CF",
  273. "GFB60": "PolyLite ABS",
  274. "GFB61": "PolyLite ASA",
  275. "GFB98": "Generic ASA",
  276. "GFB99": "Generic ABS",
  277. "GFC00": "Bambu PC",
  278. "GFC01": "Bambu PC FR",
  279. "GFC99": "Generic PC",
  280. "GFG00": "Bambu PETG Basic",
  281. "GFG01": "Bambu PETG Translucent",
  282. "GFG02": "Bambu PETG HF",
  283. "GFG50": "Bambu PETG-CF",
  284. "GFG60": "PolyLite PETG",
  285. "GFG96": "Generic PETG HF",
  286. "GFG97": "Generic PCTG",
  287. "GFG98": "Generic PETG-CF",
  288. "GFG99": "Generic PETG",
  289. "GFL00": "PolyLite PLA",
  290. "GFL01": "PolyTerra PLA",
  291. "GFL03": "eSUN PLA+",
  292. "GFL04": "Overture PLA",
  293. "GFL05": "Overture Matte PLA",
  294. "GFL06": "Fiberon PETG-ESD",
  295. "GFL50": "Fiberon PA6-CF",
  296. "GFL51": "Fiberon PA6-GF",
  297. "GFL52": "Fiberon PA12-CF",
  298. "GFL53": "Fiberon PA612-CF",
  299. "GFL54": "Fiberon PET-CF",
  300. "GFL55": "Fiberon PETG-rCF",
  301. "GFL95": "Generic PLA High Speed",
  302. "GFL96": "Generic PLA Silk",
  303. "GFL98": "Generic PLA-CF",
  304. "GFL99": "Generic PLA",
  305. "GFN03": "Bambu PA-CF",
  306. "GFN04": "Bambu PAHT-CF",
  307. "GFN05": "Bambu PA6-CF",
  308. "GFN06": "Bambu PPA-CF",
  309. "GFN08": "Bambu PA6-GF",
  310. "GFN96": "Generic PPA-GF",
  311. "GFN97": "Generic PPA-CF",
  312. "GFN98": "Generic PA-CF",
  313. "GFN99": "Generic PA",
  314. "GFP95": "Generic PP-GF",
  315. "GFP96": "Generic PP-CF",
  316. "GFP97": "Generic PP",
  317. "GFP98": "Generic PE-CF",
  318. "GFP99": "Generic PE",
  319. "GFR98": "Generic PHA",
  320. "GFR99": "Generic EVA",
  321. "GFS00": "Bambu Support W",
  322. "GFS01": "Bambu Support G",
  323. "GFS02": "Bambu Support For PLA",
  324. "GFS03": "Bambu Support For PA/PET",
  325. "GFS04": "Bambu PVA",
  326. "GFS05": "Bambu Support For PLA/PETG",
  327. "GFS06": "Bambu Support for ABS",
  328. "GFS97": "Generic BVOH",
  329. "GFS98": "Generic HIPS",
  330. "GFS99": "Generic PVA",
  331. "GFT01": "Bambu PET-CF",
  332. "GFT02": "Bambu PPS-CF",
  333. "GFT97": "Generic PPS",
  334. "GFT98": "Generic PPS-CF",
  335. "GFU00": "Bambu TPU 95A HF",
  336. "GFU01": "Bambu TPU 95A",
  337. "GFU02": "Bambu TPU for AMS",
  338. "GFU98": "Generic TPU for AMS",
  339. "GFU99": "Generic TPU",
  340. }
  341. async def _enrich_from_local_presets(
  342. unresolved_ids: list[str],
  343. result: dict,
  344. db: AsyncSession,
  345. ) -> dict:
  346. """Fall back to local profiles for filament IDs not resolved by cloud.
  347. Matches by checking the setting_id field inside the local preset's
  348. resolved JSON blob (stored in the 'setting' column).
  349. """
  350. from sqlalchemy import text
  351. from backend.app.models.local_preset import LocalPreset
  352. # Build lookup: converted setting_id -> original filament_id
  353. id_map: dict[str, str] = {}
  354. for fid in unresolved_ids:
  355. converted = _filament_id_to_setting_id(fid)
  356. id_map[converted] = fid
  357. # Also map the original in case the JSON uses that form
  358. id_map[fid] = fid
  359. try:
  360. # Query filament presets that have a setting_id matching any of our IDs
  361. # json_extract is supported in SQLite >= 3.9 and all modern Python builds
  362. candidates = await db.execute(
  363. select(LocalPreset).where(
  364. LocalPreset.preset_type == "filament",
  365. text("json_extract(setting, '$.setting_id') IS NOT NULL"),
  366. )
  367. )
  368. for preset in candidates.scalars().all():
  369. try:
  370. setting_data = json.loads(preset.setting) if isinstance(preset.setting, str) else preset.setting
  371. preset_setting_id = setting_data.get("setting_id", "")
  372. if preset_setting_id in id_map:
  373. original_id = id_map[preset_setting_id]
  374. info = {"name": preset.name, "k": None}
  375. # Try to extract K value from the local preset
  376. pa = setting_data.get("pressure_advance")
  377. if pa is not None:
  378. try:
  379. k_val = float(pa[0]) if isinstance(pa, list) else float(pa)
  380. info["k"] = k_val
  381. except (ValueError, TypeError, IndexError):
  382. pass
  383. _filament_cache[original_id] = info
  384. result[original_id] = info
  385. except Exception:
  386. continue
  387. except Exception as e:
  388. logger.warning("Failed to search local presets for filament info: %s", e)
  389. # Phase 4: Fall back to built-in filament name table for any still without a name
  390. for fid in unresolved_ids:
  391. if fid not in result or not result[fid].get("name"):
  392. name = _BUILTIN_FILAMENT_NAMES.get(fid, "")
  393. if name:
  394. # Preserve K value from earlier phases if available
  395. existing_k = result.get(fid, {}).get("k")
  396. info = {"name": name, "k": existing_k}
  397. _filament_cache[fid] = info
  398. result[fid] = info
  399. # Fill remaining unresolved with empty entries
  400. for fid in unresolved_ids:
  401. if fid not in result:
  402. _filament_cache[fid] = {"name": "", "k": None}
  403. result[fid] = {"name": "", "k": None}
  404. return result
  405. def _filament_id_to_setting_id(filament_id: str) -> str:
  406. """
  407. Convert filament_id to setting_id format for Bambu Cloud API.
  408. Printers report filament_id (e.g., GFA00, GFG02) but the API expects
  409. setting_id format which has an "S" inserted after "GF" (e.g., GFSA00, GFSG02).
  410. User presets (starting with "P") and already-correct IDs are returned unchanged.
  411. """
  412. if not filament_id:
  413. return filament_id
  414. # User presets start with "P" - leave unchanged
  415. if filament_id.startswith("P"):
  416. return filament_id
  417. # Official Bambu presets: GFx## -> GFSx##
  418. # Check if it matches the filament_id pattern (GF followed by letter and digits)
  419. if filament_id.startswith("GF") and len(filament_id) >= 4:
  420. # Check if it's already a setting_id (has S after GF)
  421. if filament_id[2] == "S":
  422. return filament_id
  423. # Insert "S" after "GF": GFA00 -> GFSA00
  424. return f"GFS{filament_id[2:]}"
  425. return filament_id
  426. @router.post("/filament-info")
  427. async def get_filament_info(
  428. setting_ids: list[str] = Body(...),
  429. db: AsyncSession = Depends(get_db),
  430. _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_READ),
  431. ):
  432. """
  433. Get filament preset info (name and K value) for multiple setting IDs.
  434. Used to enrich AMS tray and nozzle rack tooltips with preset data.
  435. Lookup order: cache → cloud → local profiles → built-in table → empty fallback.
  436. """
  437. import time
  438. logger.info("get_filament_info called with %s IDs: %s", len(setting_ids), setting_ids)
  439. global _filament_cache, _filament_cache_time
  440. # Clear stale cache
  441. if time.time() - _filament_cache_time > FILAMENT_CACHE_TTL:
  442. _filament_cache = {}
  443. _filament_cache_time = time.time()
  444. result = {}
  445. unresolved_ids: list[str] = []
  446. # Phase 1: Check cache
  447. for setting_id in setting_ids:
  448. if not setting_id:
  449. continue
  450. if setting_id in _filament_cache:
  451. result[setting_id] = _filament_cache[setting_id]
  452. else:
  453. unresolved_ids.append(setting_id)
  454. # Phase 2: Try cloud for uncached IDs
  455. if unresolved_ids:
  456. token, _ = await get_stored_token(db)
  457. if token:
  458. cloud = get_cloud_service()
  459. cloud.set_token(token)
  460. if cloud.is_authenticated:
  461. still_unresolved: list[str] = []
  462. for setting_id in unresolved_ids:
  463. try:
  464. api_setting_id = _filament_id_to_setting_id(setting_id)
  465. data = await cloud.get_setting_detail(api_setting_id)
  466. setting = data.get("setting", {})
  467. name = data.get("name", "")
  468. k_value = setting.get("pressure_advance")
  469. if k_value is not None:
  470. try:
  471. k_value = float(k_value)
  472. except (ValueError, TypeError):
  473. k_value = None
  474. info = {"name": name, "k": k_value}
  475. _filament_cache[setting_id] = info
  476. result[setting_id] = info
  477. if not name:
  478. still_unresolved.append(setting_id)
  479. except Exception as e:
  480. logger.warning(
  481. f"Failed to get cloud preset {setting_id} "
  482. f"(API ID: {_filament_id_to_setting_id(setting_id)}): {e}"
  483. )
  484. still_unresolved.append(setting_id)
  485. unresolved_ids = still_unresolved
  486. # Phase 3: Try local profiles for any IDs still without a name
  487. if unresolved_ids:
  488. result = await _enrich_from_local_presets(unresolved_ids, result, db)
  489. return result
  490. @router.get("/devices", response_model=list[CloudDevice])
  491. async def get_devices(
  492. db: AsyncSession = Depends(get_db),
  493. _: User | None = RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  494. ):
  495. """
  496. Get list of bound printer devices.
  497. Returns printers registered to the user's Bambu account.
  498. """
  499. token, _ = await get_stored_token(db)
  500. if not token:
  501. raise HTTPException(status_code=401, detail="Not authenticated")
  502. cloud = get_cloud_service()
  503. cloud.set_token(token)
  504. if not cloud.is_authenticated:
  505. raise HTTPException(status_code=401, detail="Not authenticated")
  506. try:
  507. data = await cloud.get_devices()
  508. devices = data.get("devices", [])
  509. return [
  510. CloudDevice(
  511. dev_id=d.get("dev_id", ""),
  512. name=d.get("name", "Unknown"),
  513. dev_model_name=d.get("dev_model_name"),
  514. dev_product_name=d.get("dev_product_name"),
  515. online=d.get("online", False),
  516. )
  517. for d in devices
  518. ]
  519. except BambuCloudAuthError:
  520. await clear_token(db)
  521. raise HTTPException(status_code=401, detail="Authentication expired")
  522. except BambuCloudError as e:
  523. raise HTTPException(status_code=500, detail=str(e))
  524. @router.get("/firmware-updates", response_model=FirmwareUpdatesResponse)
  525. async def get_firmware_updates(
  526. db: AsyncSession = Depends(get_db),
  527. _: User | None = RequirePermissionIfAuthEnabled(Permission.FIRMWARE_READ),
  528. ):
  529. """
  530. Check for firmware updates for all bound devices.
  531. Returns firmware version info for each device including:
  532. - Current installed version
  533. - Latest available version
  534. - Whether an update is available
  535. - Release notes for the latest version
  536. Requires cloud authentication.
  537. """
  538. token, _ = await get_stored_token(db)
  539. if not token:
  540. raise HTTPException(status_code=401, detail="Not authenticated")
  541. cloud = get_cloud_service()
  542. cloud.set_token(token)
  543. if not cloud.is_authenticated:
  544. raise HTTPException(status_code=401, detail="Not authenticated")
  545. try:
  546. # First get list of bound devices
  547. devices_data = await cloud.get_devices()
  548. devices = devices_data.get("devices", [])
  549. updates = []
  550. updates_available = 0
  551. # Check firmware for each device
  552. for device in devices:
  553. device_id = device.get("dev_id", "")
  554. device_name = device.get("name", "Unknown")
  555. try:
  556. firmware_info = await cloud.get_firmware_version(device_id)
  557. update_available = firmware_info.get("update_available", False)
  558. if update_available:
  559. updates_available += 1
  560. updates.append(
  561. FirmwareUpdateInfo(
  562. device_id=device_id,
  563. device_name=device_name,
  564. current_version=firmware_info.get("current_version"),
  565. latest_version=firmware_info.get("latest_version"),
  566. update_available=update_available,
  567. release_notes=firmware_info.get("release_notes"),
  568. )
  569. )
  570. except BambuCloudError as e:
  571. logger.warning("Failed to get firmware info for %s: %s", device_name, e)
  572. # Still include device but with unknown firmware status
  573. updates.append(
  574. FirmwareUpdateInfo(
  575. device_id=device_id,
  576. device_name=device_name,
  577. current_version=None,
  578. latest_version=None,
  579. update_available=False,
  580. release_notes=None,
  581. )
  582. )
  583. return FirmwareUpdatesResponse(updates=updates, updates_available=updates_available)
  584. except BambuCloudAuthError:
  585. await clear_token(db)
  586. raise HTTPException(status_code=401, detail="Authentication expired")
  587. except BambuCloudError as e:
  588. raise HTTPException(status_code=500, detail=str(e))
  589. @router.post("/settings")
  590. async def create_setting(
  591. request: SlicerSettingCreate,
  592. db: AsyncSession = Depends(get_db),
  593. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  594. ):
  595. """
  596. Create a new slicer preset/setting.
  597. Creates a new preset on Bambu Cloud. The preset inherits from a base preset
  598. and only stores the delta (modified values).
  599. Type should be: 'filament', 'print', or 'printer'
  600. """
  601. token, _ = await get_stored_token(db)
  602. if not token:
  603. raise HTTPException(status_code=401, detail="Not authenticated")
  604. cloud = get_cloud_service()
  605. cloud.set_token(token)
  606. if not cloud.is_authenticated:
  607. raise HTTPException(status_code=401, detail="Not authenticated")
  608. try:
  609. data = await cloud.create_setting(
  610. preset_type=request.type,
  611. name=request.name,
  612. base_id=request.base_id,
  613. setting=request.setting,
  614. version=request.version,
  615. )
  616. return data
  617. except BambuCloudAuthError:
  618. await clear_token(db)
  619. raise HTTPException(status_code=401, detail="Authentication expired")
  620. except BambuCloudError as e:
  621. raise HTTPException(status_code=500, detail=str(e))
  622. @router.put("/settings/{setting_id}")
  623. async def update_setting(
  624. setting_id: str,
  625. request: SlicerSettingUpdate,
  626. db: AsyncSession = Depends(get_db),
  627. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  628. ):
  629. """
  630. Update an existing slicer preset/setting.
  631. Updates the preset's name and/or settings on Bambu Cloud.
  632. """
  633. token, _ = await get_stored_token(db)
  634. if not token:
  635. raise HTTPException(status_code=401, detail="Not authenticated")
  636. cloud = get_cloud_service()
  637. cloud.set_token(token)
  638. if not cloud.is_authenticated:
  639. raise HTTPException(status_code=401, detail="Not authenticated")
  640. try:
  641. data = await cloud.update_setting(
  642. setting_id=setting_id,
  643. name=request.name,
  644. setting=request.setting,
  645. )
  646. return data
  647. except BambuCloudAuthError:
  648. await clear_token(db)
  649. raise HTTPException(status_code=401, detail="Authentication expired")
  650. except BambuCloudError as e:
  651. raise HTTPException(status_code=500, detail=str(e))
  652. @router.delete("/settings/{setting_id}", response_model=SlicerSettingDeleteResponse)
  653. async def delete_setting(
  654. setting_id: str,
  655. db: AsyncSession = Depends(get_db),
  656. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  657. ):
  658. """
  659. Delete a slicer preset/setting.
  660. Removes the preset from Bambu Cloud. This cannot be undone.
  661. """
  662. token, _ = await get_stored_token(db)
  663. if not token:
  664. raise HTTPException(status_code=401, detail="Not authenticated")
  665. cloud = get_cloud_service()
  666. cloud.set_token(token)
  667. if not cloud.is_authenticated:
  668. raise HTTPException(status_code=401, detail="Not authenticated")
  669. try:
  670. result = await cloud.delete_setting(setting_id)
  671. return SlicerSettingDeleteResponse(
  672. success=result.get("success", True),
  673. message=result.get("message", "Setting deleted"),
  674. )
  675. except BambuCloudAuthError:
  676. await clear_token(db)
  677. raise HTTPException(status_code=401, detail="Authentication expired")
  678. except BambuCloudError as e:
  679. raise HTTPException(status_code=500, detail=str(e))
  680. # Path to field definition files
  681. FIELDS_DATA_DIR = Path(__file__).parent.parent.parent / "data"
  682. # Cache for field definitions (loaded once)
  683. _fields_cache: dict[str, dict] = {}
  684. def _load_fields(preset_type: str) -> dict:
  685. """Load field definitions from JSON file."""
  686. if preset_type in _fields_cache:
  687. return _fields_cache[preset_type]
  688. # Map API type names to file names
  689. file_map = {
  690. "filament": "filament_fields.json",
  691. "print": "process_fields.json",
  692. "process": "process_fields.json",
  693. "printer": "printer_fields.json",
  694. }
  695. filename = file_map.get(preset_type)
  696. if not filename:
  697. raise HTTPException(status_code=400, detail=f"Unknown preset type: {preset_type}")
  698. file_path = FIELDS_DATA_DIR / filename
  699. if not file_path.exists():
  700. raise HTTPException(status_code=404, detail=f"Field definitions not found for: {preset_type}")
  701. with open(file_path) as f:
  702. data = json.load(f)
  703. _fields_cache[preset_type] = data
  704. return data
  705. @router.get("/fields/{preset_type}")
  706. async def get_preset_fields(
  707. preset_type: Literal["filament", "print", "process", "printer"],
  708. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  709. ):
  710. """
  711. Get field definitions for a preset type.
  712. Returns a list of field definitions including:
  713. - key: The setting key name
  714. - label: Human-readable label
  715. - type: Field type (text, number, boolean, select)
  716. - category: Grouping category
  717. - description: Field description
  718. - options: For select fields, available options
  719. - unit: Unit of measurement (if applicable)
  720. - min/max/step: For number fields, validation constraints
  721. """
  722. data = _load_fields(preset_type)
  723. return data
  724. @router.get("/fields")
  725. async def get_all_preset_fields(
  726. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  727. ):
  728. """
  729. Get all field definitions for all preset types.
  730. Returns field definitions organized by type.
  731. """
  732. return {
  733. "filament": _load_fields("filament"),
  734. "process": _load_fields("process"),
  735. "printer": _load_fields("printer"),
  736. }