cloud.py 34 KB

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