cloud.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. """
  2. Bambu Lab Cloud API Routes
  3. Handles authentication and profile management with Bambu Cloud.
  4. """
  5. import json
  6. from pathlib import Path
  7. from typing import Literal
  8. from fastapi import APIRouter, HTTPException, Depends
  9. from sqlalchemy.ext.asyncio import AsyncSession
  10. from sqlalchemy import select
  11. from backend.app.core.database import get_db
  12. from backend.app.models.settings import Settings
  13. from backend.app.services.bambu_cloud import (
  14. get_cloud_service,
  15. BambuCloudError,
  16. BambuCloudAuthError,
  17. )
  18. from backend.app.schemas.cloud import (
  19. CloudLoginRequest,
  20. CloudVerifyRequest,
  21. CloudLoginResponse,
  22. CloudAuthStatus,
  23. CloudTokenRequest,
  24. SlicerSettingsResponse,
  25. SlicerSetting,
  26. CloudDevice,
  27. SlicerSettingCreate,
  28. SlicerSettingUpdate,
  29. SlicerSettingDeleteResponse,
  30. )
  31. router = APIRouter(prefix="/cloud", tags=["cloud"])
  32. # Keys for storing cloud credentials in settings
  33. CLOUD_TOKEN_KEY = "bambu_cloud_token"
  34. CLOUD_EMAIL_KEY = "bambu_cloud_email"
  35. async def get_stored_token(db: AsyncSession) -> tuple[str | None, str | None]:
  36. """Get stored cloud token and email from database."""
  37. result = await db.execute(
  38. select(Settings).where(Settings.key.in_([CLOUD_TOKEN_KEY, CLOUD_EMAIL_KEY]))
  39. )
  40. settings = {s.key: s.value for s in result.scalars().all()}
  41. return settings.get(CLOUD_TOKEN_KEY), settings.get(CLOUD_EMAIL_KEY)
  42. async def store_token(db: AsyncSession, token: str, email: str) -> None:
  43. """Store cloud token and email in database."""
  44. for key, value in [(CLOUD_TOKEN_KEY, token), (CLOUD_EMAIL_KEY, email)]:
  45. result = await db.execute(select(Settings).where(Settings.key == key))
  46. setting = result.scalar_one_or_none()
  47. if setting:
  48. setting.value = value
  49. else:
  50. db.add(Settings(key=key, value=value))
  51. await db.commit()
  52. async def clear_token(db: AsyncSession) -> None:
  53. """Clear stored cloud token and email."""
  54. result = await db.execute(
  55. select(Settings).where(Settings.key.in_([CLOUD_TOKEN_KEY, CLOUD_EMAIL_KEY]))
  56. )
  57. for setting in result.scalars().all():
  58. await db.delete(setting)
  59. await db.commit()
  60. @router.get("/status", response_model=CloudAuthStatus)
  61. async def get_auth_status(db: AsyncSession = Depends(get_db)):
  62. """Get current cloud authentication status."""
  63. token, email = await get_stored_token(db)
  64. cloud = get_cloud_service()
  65. if token:
  66. cloud.set_token(token)
  67. return CloudAuthStatus(
  68. is_authenticated=cloud.is_authenticated,
  69. email=email if cloud.is_authenticated else None,
  70. )
  71. @router.post("/login", response_model=CloudLoginResponse)
  72. async def login(request: CloudLoginRequest, db: AsyncSession = Depends(get_db)):
  73. """
  74. Initiate login to Bambu Cloud.
  75. This will typically trigger a verification code to be sent to the user's email.
  76. After receiving the code, call /cloud/verify to complete the login.
  77. """
  78. cloud = get_cloud_service()
  79. # Store email temporarily for verification step
  80. await store_token(db, "", request.email)
  81. try:
  82. result = await cloud.login_request(request.email, request.password)
  83. if result.get("success") and cloud.access_token:
  84. # Direct login succeeded (rare)
  85. await store_token(db, cloud.access_token, request.email)
  86. return CloudLoginResponse(
  87. success=result.get("success", False),
  88. needs_verification=result.get("needs_verification", False),
  89. message=result.get("message", "Unknown error"),
  90. )
  91. except BambuCloudAuthError as e:
  92. raise HTTPException(status_code=401, detail=str(e))
  93. except BambuCloudError as e:
  94. raise HTTPException(status_code=500, detail=str(e))
  95. @router.post("/verify", response_model=CloudLoginResponse)
  96. async def verify_code(request: CloudVerifyRequest, db: AsyncSession = Depends(get_db)):
  97. """
  98. Complete login with verification code.
  99. After calling /cloud/login, the user will receive an email with a 6-digit code.
  100. Submit that code here to complete authentication.
  101. """
  102. cloud = get_cloud_service()
  103. try:
  104. result = await cloud.verify_code(request.email, request.code)
  105. if result.get("success") and cloud.access_token:
  106. await store_token(db, cloud.access_token, request.email)
  107. return CloudLoginResponse(
  108. success=result.get("success", False),
  109. needs_verification=False,
  110. message=result.get("message", "Unknown error"),
  111. )
  112. except BambuCloudAuthError as e:
  113. raise HTTPException(status_code=401, detail=str(e))
  114. except BambuCloudError as e:
  115. raise HTTPException(status_code=500, detail=str(e))
  116. @router.post("/token", response_model=CloudAuthStatus)
  117. async def set_token(request: CloudTokenRequest, db: AsyncSession = Depends(get_db)):
  118. """
  119. Set access token directly.
  120. For users who already have a token (e.g., from Bambu Studio).
  121. """
  122. cloud = get_cloud_service()
  123. cloud.set_token(request.access_token)
  124. # Verify token works by trying to get profile
  125. try:
  126. await cloud.get_user_profile()
  127. await store_token(db, request.access_token, "token-auth")
  128. return CloudAuthStatus(is_authenticated=True, email="token-auth")
  129. except BambuCloudError:
  130. cloud.logout()
  131. raise HTTPException(status_code=401, detail="Invalid token")
  132. @router.post("/logout")
  133. async def logout(db: AsyncSession = Depends(get_db)):
  134. """Log out of Bambu Cloud."""
  135. cloud = get_cloud_service()
  136. cloud.logout()
  137. await clear_token(db)
  138. return {"success": True}
  139. @router.get("/settings", response_model=SlicerSettingsResponse)
  140. async def get_slicer_settings(
  141. version: str = "02.04.00.70",
  142. db: AsyncSession = Depends(get_db),
  143. ):
  144. """
  145. Get all slicer settings (filament, printer, process presets).
  146. Requires authentication.
  147. """
  148. token, _ = await get_stored_token(db)
  149. if not token:
  150. raise HTTPException(status_code=401, detail="Not authenticated")
  151. cloud = get_cloud_service()
  152. cloud.set_token(token)
  153. if not cloud.is_authenticated:
  154. raise HTTPException(status_code=401, detail="Not authenticated")
  155. try:
  156. data = await cloud.get_slicer_settings(version)
  157. result = SlicerSettingsResponse()
  158. # Map API keys to our types (API uses 'print' for process presets)
  159. type_mapping = {
  160. "filament": "filament",
  161. "printer": "printer",
  162. "print": "process", # API calls it 'print', we call it 'process'
  163. }
  164. for api_key, our_type in type_mapping.items():
  165. type_data = data.get(api_key, {})
  166. # Combine public and private presets, private (user's own) first
  167. all_settings = type_data.get("private", []) + type_data.get("public", [])
  168. parsed = []
  169. for s in all_settings:
  170. parsed.append(SlicerSetting(
  171. setting_id=s.get("setting_id", s.get("id", "")),
  172. name=s.get("name", "Unknown"),
  173. type=our_type,
  174. version=s.get("version"),
  175. user_id=s.get("user_id"),
  176. updated_time=s.get("updated_time"),
  177. ))
  178. setattr(result, our_type, parsed)
  179. return result
  180. except BambuCloudAuthError:
  181. await clear_token(db)
  182. raise HTTPException(status_code=401, detail="Authentication expired")
  183. except BambuCloudError as e:
  184. raise HTTPException(status_code=500, detail=str(e))
  185. @router.get("/settings/{setting_id}")
  186. async def get_setting_detail(setting_id: str, db: AsyncSession = Depends(get_db)):
  187. """
  188. Get detailed information for a specific setting/preset.
  189. Returns the full preset configuration.
  190. """
  191. token, _ = await get_stored_token(db)
  192. if not token:
  193. raise HTTPException(status_code=401, detail="Not authenticated")
  194. cloud = get_cloud_service()
  195. cloud.set_token(token)
  196. if not cloud.is_authenticated:
  197. raise HTTPException(status_code=401, detail="Not authenticated")
  198. try:
  199. data = await cloud.get_setting_detail(setting_id)
  200. return data
  201. except BambuCloudAuthError:
  202. await clear_token(db)
  203. raise HTTPException(status_code=401, detail="Authentication expired")
  204. except BambuCloudError as e:
  205. raise HTTPException(status_code=500, detail=str(e))
  206. @router.get("/devices", response_model=list[CloudDevice])
  207. async def get_devices(db: AsyncSession = Depends(get_db)):
  208. """
  209. Get list of bound printer devices.
  210. Returns printers registered to the user's Bambu account.
  211. """
  212. token, _ = await get_stored_token(db)
  213. if not token:
  214. raise HTTPException(status_code=401, detail="Not authenticated")
  215. cloud = get_cloud_service()
  216. cloud.set_token(token)
  217. if not cloud.is_authenticated:
  218. raise HTTPException(status_code=401, detail="Not authenticated")
  219. try:
  220. data = await cloud.get_devices()
  221. devices = data.get("devices", [])
  222. return [
  223. CloudDevice(
  224. dev_id=d.get("dev_id", ""),
  225. name=d.get("name", "Unknown"),
  226. dev_model_name=d.get("dev_model_name"),
  227. dev_product_name=d.get("dev_product_name"),
  228. online=d.get("online", False),
  229. )
  230. for d in devices
  231. ]
  232. except BambuCloudAuthError:
  233. await clear_token(db)
  234. raise HTTPException(status_code=401, detail="Authentication expired")
  235. except BambuCloudError as e:
  236. raise HTTPException(status_code=500, detail=str(e))
  237. @router.post("/settings")
  238. async def create_setting(request: SlicerSettingCreate, db: AsyncSession = Depends(get_db)):
  239. """
  240. Create a new slicer preset/setting.
  241. Creates a new preset on Bambu Cloud. The preset inherits from a base preset
  242. and only stores the delta (modified values).
  243. Type should be: 'filament', 'print', or 'printer'
  244. """
  245. token, _ = await get_stored_token(db)
  246. if not token:
  247. raise HTTPException(status_code=401, detail="Not authenticated")
  248. cloud = get_cloud_service()
  249. cloud.set_token(token)
  250. if not cloud.is_authenticated:
  251. raise HTTPException(status_code=401, detail="Not authenticated")
  252. try:
  253. data = await cloud.create_setting(
  254. preset_type=request.type,
  255. name=request.name,
  256. base_id=request.base_id,
  257. setting=request.setting,
  258. version=request.version,
  259. )
  260. return data
  261. except BambuCloudAuthError:
  262. await clear_token(db)
  263. raise HTTPException(status_code=401, detail="Authentication expired")
  264. except BambuCloudError as e:
  265. raise HTTPException(status_code=500, detail=str(e))
  266. @router.put("/settings/{setting_id}")
  267. async def update_setting(
  268. setting_id: str,
  269. request: SlicerSettingUpdate,
  270. db: AsyncSession = Depends(get_db),
  271. ):
  272. """
  273. Update an existing slicer preset/setting.
  274. Updates the preset's name and/or settings on Bambu Cloud.
  275. """
  276. token, _ = await get_stored_token(db)
  277. if not token:
  278. raise HTTPException(status_code=401, detail="Not authenticated")
  279. cloud = get_cloud_service()
  280. cloud.set_token(token)
  281. if not cloud.is_authenticated:
  282. raise HTTPException(status_code=401, detail="Not authenticated")
  283. try:
  284. data = await cloud.update_setting(
  285. setting_id=setting_id,
  286. name=request.name,
  287. setting=request.setting,
  288. )
  289. return data
  290. except BambuCloudAuthError:
  291. await clear_token(db)
  292. raise HTTPException(status_code=401, detail="Authentication expired")
  293. except BambuCloudError as e:
  294. raise HTTPException(status_code=500, detail=str(e))
  295. @router.delete("/settings/{setting_id}", response_model=SlicerSettingDeleteResponse)
  296. async def delete_setting(setting_id: str, db: AsyncSession = Depends(get_db)):
  297. """
  298. Delete a slicer preset/setting.
  299. Removes the preset from Bambu Cloud. This cannot be undone.
  300. """
  301. token, _ = await get_stored_token(db)
  302. if not token:
  303. raise HTTPException(status_code=401, detail="Not authenticated")
  304. cloud = get_cloud_service()
  305. cloud.set_token(token)
  306. if not cloud.is_authenticated:
  307. raise HTTPException(status_code=401, detail="Not authenticated")
  308. try:
  309. result = await cloud.delete_setting(setting_id)
  310. return SlicerSettingDeleteResponse(
  311. success=result.get("success", True),
  312. message=result.get("message", "Setting deleted"),
  313. )
  314. except BambuCloudAuthError:
  315. await clear_token(db)
  316. raise HTTPException(status_code=401, detail="Authentication expired")
  317. except BambuCloudError as e:
  318. raise HTTPException(status_code=500, detail=str(e))
  319. # Path to field definition files
  320. FIELDS_DATA_DIR = Path(__file__).parent.parent.parent / "data"
  321. # Cache for field definitions (loaded once)
  322. _fields_cache: dict[str, dict] = {}
  323. def _load_fields(preset_type: str) -> dict:
  324. """Load field definitions from JSON file."""
  325. if preset_type in _fields_cache:
  326. return _fields_cache[preset_type]
  327. # Map API type names to file names
  328. file_map = {
  329. "filament": "filament_fields.json",
  330. "print": "process_fields.json",
  331. "process": "process_fields.json",
  332. "printer": "printer_fields.json",
  333. }
  334. filename = file_map.get(preset_type)
  335. if not filename:
  336. raise HTTPException(status_code=400, detail=f"Unknown preset type: {preset_type}")
  337. file_path = FIELDS_DATA_DIR / filename
  338. if not file_path.exists():
  339. raise HTTPException(status_code=404, detail=f"Field definitions not found for: {preset_type}")
  340. with open(file_path, "r") as f:
  341. data = json.load(f)
  342. _fields_cache[preset_type] = data
  343. return data
  344. @router.get("/fields/{preset_type}")
  345. async def get_preset_fields(preset_type: Literal["filament", "print", "process", "printer"]):
  346. """
  347. Get field definitions for a preset type.
  348. Returns a list of field definitions including:
  349. - key: The setting key name
  350. - label: Human-readable label
  351. - type: Field type (text, number, boolean, select)
  352. - category: Grouping category
  353. - description: Field description
  354. - options: For select fields, available options
  355. - unit: Unit of measurement (if applicable)
  356. - min/max/step: For number fields, validation constraints
  357. """
  358. data = _load_fields(preset_type)
  359. return data
  360. @router.get("/fields")
  361. async def get_all_preset_fields():
  362. """
  363. Get all field definitions for all preset types.
  364. Returns field definitions organized by type.
  365. """
  366. return {
  367. "filament": _load_fields("filament"),
  368. "process": _load_fields("process"),
  369. "printer": _load_fields("printer"),
  370. }