slicer_presets.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  1. """Unified slicer-preset listing for the SliceModal (#wiki / Cloud-aware presets).
  2. Returns the printer/process/filament options grouped by source tier in
  3. priority order — cloud (per-user, live-fetched) > local (DB-backed
  4. imports) > standard (slicer-bundled stock fallback). Name-based dedup is
  5. applied so a preset that exists in multiple tiers only appears in the
  6. highest-priority one. Cloud failure modes (signed out / expired / network)
  7. are surfaced via a status field so the modal can render a precise banner
  8. without faking an "ok with empty list" response.
  9. """
  10. from __future__ import annotations
  11. import hashlib
  12. import json
  13. import logging
  14. import time
  15. from fastapi import APIRouter, Depends, HTTPException, Query
  16. from sqlalchemy import select
  17. from sqlalchemy.ext.asyncio import AsyncSession
  18. from backend.app.api.routes.cloud import resolve_api_key_cloud_owner
  19. from backend.app.api.routes.orca_cloud import (
  20. _ORCA_TYPE_TO_BAMBU,
  21. _build_authenticated_service as _build_orca_service,
  22. _load_credentials as _load_orca_credentials,
  23. )
  24. from backend.app.core.auth import (
  25. ApiKeyActor,
  26. RequestPrinterScope,
  27. RequirePermissionIfAuthEnabled,
  28. is_auth_enabled,
  29. require_ownership_permission,
  30. )
  31. from backend.app.core.config import settings as app_settings
  32. from backend.app.core.database import get_db
  33. from backend.app.core.permissions import Permission
  34. from backend.app.core.printer_scope import PrinterScope
  35. from backend.app.models.local_preset import LocalPreset
  36. from backend.app.models.printer import Printer
  37. from backend.app.models.slot_preset import SlotPresetMapping
  38. from backend.app.models.user import User
  39. from backend.app.schemas.slicer import PresetRef
  40. from backend.app.schemas.slicer_presets import (
  41. LoadedSpoolPreset,
  42. LoadedSpoolPrinter,
  43. LoadedSpoolsResponse,
  44. LoadedSpoolTray,
  45. LoadedSpoolUnit,
  46. UnifiedPreset,
  47. UnifiedPresetsBySlot,
  48. UnifiedPresetsResponse,
  49. )
  50. from backend.app.services.bambu_cloud import (
  51. BambuCloudAuthError,
  52. BambuCloudError,
  53. BambuCloudService,
  54. )
  55. from backend.app.services.bambu_cloud_credentials import get_stored_token
  56. from backend.app.services.orca_cloud import (
  57. OrcaCloudAuthError,
  58. OrcaCloudError,
  59. )
  60. from backend.app.services.preset_resolver import resolve_preset_ref
  61. from backend.app.services.printer_manager import printer_manager
  62. from backend.app.services.slicer_api import (
  63. SlicerApiError,
  64. SlicerApiService,
  65. SlicerApiUnavailableError,
  66. )
  67. from backend.app.utils.printer_models import (
  68. PRINTER_MODEL_MAP,
  69. normalize_printer_model,
  70. normalize_printer_model_id,
  71. )
  72. logger = logging.getLogger(__name__)
  73. router = APIRouter(prefix="/slicer", tags=["Slicer Presets"])
  74. # In-process cache for the bundled-profile list. The slicer sidecar walks a
  75. # read-only filesystem inside its own container, so the list only changes
  76. # across sidecar rebuilds — a long TTL is safe and avoids a sidecar round-trip
  77. # on every modal open. Per-user cache is unnecessary because bundled profiles
  78. # are global.
  79. _BUNDLED_TTL_S = 3600.0
  80. _bundled_cache: tuple[float, dict[str, list[UnifiedPreset]]] | None = None
  81. # Per-user cache for the cloud preset list. Cache key is (user_id, token_hash):
  82. # keying on the token hash means a logout/login or token-change automatically
  83. # invalidates the entry without needing the cloud-auth route handlers to call
  84. # back into this module. 5 minutes balances "users see their freshly-saved
  85. # presets quickly" against "a busy install doesn't hit the cloud once per
  86. # modal open per user".
  87. _CLOUD_TTL_S = 300.0
  88. _cloud_cache: dict[tuple[int, str], tuple[float, dict[str, list[UnifiedPreset]]]] = {}
  89. # Same shape for Orca Cloud — keyed on (user_id, access_token-fingerprint).
  90. _orca_cloud_cache: dict[tuple[int, str], tuple[float, dict[str, list[UnifiedPreset]]]] = {}
  91. def _token_fingerprint(token: str) -> str:
  92. """Short stable hash of the cloud token for use as a cache-key component.
  93. Storing only the hash means we can safely keep multiple per-(user, token)
  94. entries without leaking the token via the in-process dict."""
  95. return hashlib.sha256(token.encode("utf-8")).hexdigest()[:16]
  96. _CLOUD_TYPE_TO_SLOT = {
  97. "filament": "filament",
  98. "printer": "printer",
  99. "print": "process", # Bambu Cloud calls process presets "print"
  100. }
  101. def _empty_slots() -> dict[str, list[UnifiedPreset]]:
  102. return {"printer": [], "process": [], "filament": []}
  103. async def _fetch_cloud_presets(
  104. db: AsyncSession, user: User | None, *, refresh: bool = False
  105. ) -> tuple[dict[str, list[UnifiedPreset]], str]:
  106. """Return (slots, cloud_status). Slots are empty when cloud_status != 'ok'.
  107. Defence-in-depth: even if a stored cloud_token survived a permission
  108. revocation (admin reset, legacy state), users without ``CLOUD_AUTH`` are
  109. treated as not-authenticated for this endpoint — the cloud tier never
  110. surfaces for them. This keeps the per-tier visibility consistent with the
  111. /cloud/* endpoint suite that already gates on CLOUD_AUTH.
  112. ``refresh=True`` skips the in-process cache for this call (used by the
  113. SliceModal's manual Refresh button so a user who just deleted a preset
  114. in Bambu Studio / Handy can pick up the change without waiting for the
  115. 5-minute TTL to expire). The fresh result is still written back to the
  116. cache so subsequent non-refresh callers benefit.
  117. """
  118. if user is not None and not user.has_permission(Permission.CLOUD_AUTH.value):
  119. return _empty_slots(), "not_authenticated"
  120. # The sign-in stored without a user is the auth-off install's, not one for
  121. # a caller who has none while auth is on.
  122. if user is None and await is_auth_enabled(db):
  123. return _empty_slots(), "not_authenticated"
  124. token, _email, region = await get_stored_token(db, user)
  125. if not token:
  126. return _empty_slots(), "not_authenticated"
  127. user_key = user.id if user is not None else 0
  128. cache_key = (user_key, _token_fingerprint(token))
  129. now = time.monotonic()
  130. if not refresh:
  131. cached = _cloud_cache.get(cache_key)
  132. if cached and now - cached[0] < _CLOUD_TTL_S:
  133. return cached[1], "ok"
  134. cloud = BambuCloudService(region=region)
  135. cloud.set_token(token)
  136. try:
  137. try:
  138. raw = await cloud.get_slicer_settings()
  139. except BambuCloudAuthError:
  140. # Don't clear the token here — the cloud-status endpoint owns that
  141. # lifecycle. Just report expired so the UI can prompt re-auth.
  142. return _empty_slots(), "expired"
  143. except BambuCloudError as e:
  144. logger.warning("Cloud preset fetch failed for user %s: %s", user_key, e)
  145. return _empty_slots(), "unreachable"
  146. except Exception as e: # noqa: BLE001 — defensive: never crash the modal
  147. logger.warning("Cloud preset fetch unexpected error for user %s: %s", user_key, e)
  148. return _empty_slots(), "unreachable"
  149. slots = _empty_slots()
  150. for cloud_type, slot in _CLOUD_TYPE_TO_SLOT.items():
  151. type_data = raw.get(cloud_type, {})
  152. # The cloud splits presets into "private" (the user's own) and "public"
  153. # (Bambu's stock cloud presets). Both are valid choices — surface them
  154. # in the natural order private → public so a user's customisations
  155. # appear above the stock entries with the same names. Stock entries
  156. # that share names with private ones get deduped out within the cloud
  157. # tier itself.
  158. seen_names: set[str] = set()
  159. for entry in type_data.get("private", []) + type_data.get("public", []):
  160. name = entry.get("name")
  161. setting_id = entry.get("setting_id") or entry.get("id")
  162. if not name or not setting_id or name in seen_names:
  163. continue
  164. seen_names.add(name)
  165. slots[slot].append(UnifiedPreset(id=setting_id, name=name, source="cloud"))
  166. # Cloud filament presets carry no metadata in this response on
  167. # purpose: the per-preset detail endpoint
  168. # (/v1/iot-service/api/slicer/setting/{id}) is rate-limited at roughly
  169. # 10/sec per token, so fetching N filament presets to enrich them
  170. # one-by-one trips Bambu's limiter and returns 429 on every request
  171. # for users with large preset libraries (#1150 follow-up).
  172. #
  173. # The metadata-enrich pass (see _enrich_cloud_metadata) compensates:
  174. # a Bambu Cloud entry without its own filament_type/colour inherits
  175. # those values from a same-named local / orca_cloud / standard entry
  176. # so it can still score for type/colour matches in pickFilamentForSlot.
  177. _cloud_cache[cache_key] = (now, slots)
  178. return slots, "ok"
  179. finally:
  180. await cloud.close()
  181. async def _fetch_orca_cloud_presets(
  182. db: AsyncSession, user: User | None, *, refresh: bool = False
  183. ) -> tuple[dict[str, list[UnifiedPreset]], str]:
  184. """Mirror of :func:`_fetch_cloud_presets` but for Orca Cloud. Same status
  185. vocabulary (``ok`` / ``not_authenticated`` / ``expired`` / ``unreachable``),
  186. same caching shape, same defence-in-depth permission gate
  187. (``orca_cloud:auth`` rather than ``cloud:auth``).
  188. Filament metadata (``filament_type`` / ``filament_colour``) is extracted
  189. from the profile's inline ``content`` dict — unlike Bambu Cloud where
  190. we'd have to fetch each setting separately and hit a rate limit, Orca's
  191. ``/sync/pull`` already returns full content per profile, so the metadata
  192. enrichment is free here.
  193. """
  194. if user is not None and not user.has_permission(Permission.ORCA_CLOUD_AUTH.value):
  195. return _empty_slots(), "not_authenticated"
  196. if user is None and await is_auth_enabled(db):
  197. return _empty_slots(), "not_authenticated"
  198. creds = await _load_orca_credentials(db, user)
  199. if not creds.token:
  200. return _empty_slots(), "not_authenticated"
  201. user_key = user.id if user is not None else 0
  202. cache_key = (user_key, _token_fingerprint(creds.token))
  203. now = time.monotonic()
  204. if not refresh:
  205. cached = _orca_cloud_cache.get(cache_key)
  206. if cached and now - cached[0] < _CLOUD_TTL_S:
  207. return cached[1], "ok"
  208. try:
  209. svc = await _build_orca_service(db, user)
  210. except HTTPException as e:
  211. # ``_build_orca_service`` raises 401 when the token is missing,
  212. # the refresh-token rotation failed, or the JIT refresh hit Orca's
  213. # backend and got rejected; 502 when Orca is unreachable. Translate
  214. # to the status vocabulary the SliceModal expects.
  215. if e.status_code == 401:
  216. return _empty_slots(), "expired"
  217. return _empty_slots(), "unreachable"
  218. try:
  219. try:
  220. raw_profiles = await svc.list_profiles()
  221. except OrcaCloudAuthError:
  222. return _empty_slots(), "expired"
  223. except OrcaCloudError as e:
  224. logger.warning("Orca Cloud preset fetch failed for user %s: %s", user_key, e)
  225. return _empty_slots(), "unreachable"
  226. except Exception as e: # noqa: BLE001 — defensive: never crash the modal
  227. logger.warning("Orca Cloud preset fetch unexpected error for user %s: %s", user_key, e)
  228. return _empty_slots(), "unreachable"
  229. slots = _empty_slots()
  230. for entry in raw_profiles:
  231. content = entry.get("content") if isinstance(entry, dict) else None
  232. if not isinstance(content, dict):
  233. continue
  234. slot = _ORCA_TYPE_TO_BAMBU.get(str(content.get("type", "")))
  235. if slot is None:
  236. continue
  237. preset_id = entry.get("id")
  238. name = entry.get("name") or preset_id
  239. if not preset_id or not name:
  240. continue
  241. filament_type: str | None = None
  242. filament_colour: str | None = None
  243. if slot == "filament":
  244. # Bambu/Orca filament profiles store these as single-element
  245. # arrays (the historical multi-extruder shape). Extract the
  246. # first non-empty element for both.
  247. ft = content.get("filament_type")
  248. if isinstance(ft, list) and ft and isinstance(ft[0], str):
  249. filament_type = ft[0]
  250. elif isinstance(ft, str):
  251. filament_type = ft
  252. fc = content.get("default_filament_colour")
  253. if isinstance(fc, list) and fc and isinstance(fc[0], str):
  254. filament_colour = fc[0]
  255. elif isinstance(fc, str):
  256. filament_colour = fc
  257. preset = UnifiedPreset(
  258. id=str(preset_id),
  259. name=str(name),
  260. source="orca_cloud",
  261. filament_type=filament_type,
  262. filament_colour=filament_colour,
  263. )
  264. if slot in ("process", "filament"):
  265. # The profile's own compatible-printer list, straight out of
  266. # the content Orca already hands us (#2628). Without it the
  267. # SliceModal falls back to reading the printer out of the
  268. # profile NAME — and a profile whose name carries no model
  269. # ("Overture PLA Matte @0.2") then reads as "can't tell",
  270. # which the picker treats as usable and auto-picks for a
  271. # printer the profile was never built for.
  272. preset.compatible_printers = _content_compatible_printers(content)
  273. elif slot == "printer":
  274. preset.inherits = _content_inherits(content)
  275. slots[slot].append(preset)
  276. _orca_cloud_cache[cache_key] = (now, slots)
  277. return slots, "ok"
  278. finally:
  279. await svc.close()
  280. async def _fetch_local_presets(db: AsyncSession) -> dict[str, list[UnifiedPreset]]:
  281. """Local imports — no caching needed, single indexed DB read."""
  282. result = await db.execute(select(LocalPreset).order_by(LocalPreset.name))
  283. presets = result.scalars().all()
  284. slots = _empty_slots()
  285. type_to_slot = {"filament": "filament", "printer": "printer", "process": "process"}
  286. for p in presets:
  287. slot = type_to_slot.get(p.preset_type)
  288. if slot is None:
  289. continue
  290. preset = UnifiedPreset(id=str(p.id), name=p.name, source="local")
  291. if slot == "filament":
  292. preset.filament_type, preset.filament_colour = _parse_filament_metadata(p.setting)
  293. if slot in ("process", "filament"):
  294. # Precise compatibility link — the slicer's own compatible_printers
  295. # list, captured at import time. Lets the SliceModal filter the
  296. # process / filament dropdowns by the selected printer without
  297. # falling back to the @BBL name matcher.
  298. preset.compatible_printers = _parse_compatible_printers(p.compatible_printers)
  299. elif slot == "printer":
  300. # The preset it was saved from (#3250); see UnifiedPreset.inherits.
  301. preset.inherits = (p.inherits or "").strip() or None
  302. slots[slot].append(preset)
  303. return slots
  304. def _content_inherits(content: dict) -> str | None:
  305. """The preset a profile was saved from, out of its content dict (#3250)."""
  306. raw = content.get("inherits") if isinstance(content, dict) else None
  307. if not isinstance(raw, str):
  308. return None
  309. return raw.strip() or None
  310. def _content_compatible_printers(content: dict) -> list[str] | None:
  311. """Pull ``compatible_printers`` out of a profile content dict.
  312. Serves both callers that have one: an Orca Cloud profile's inline
  313. ``content``, and an entry of the sidecar's bundled listing.
  314. Orca profiles carry it as a list of printer-preset names (the same shape
  315. ``orca_profiles.py`` stores on import); a single-printer profile may store
  316. a bare string. Returns ``None`` for missing / empty / malformed values so
  317. the caller leaves the field unset and the SliceModal falls back to the
  318. name-based matcher, rather than treating "no data" as "compatible with
  319. nothing".
  320. """
  321. raw = content.get("compatible_printers")
  322. if isinstance(raw, str):
  323. raw = [raw]
  324. if not isinstance(raw, list):
  325. return None
  326. names = [s.strip() for s in raw if isinstance(s, str) and s.strip()]
  327. return names or None
  328. def _parse_compatible_printers(raw: str | None) -> list[str] | None:
  329. """``LocalPreset.compatible_printers`` stores a JSON array of printer-preset
  330. names. Return the parsed list, or ``None`` on missing / malformed data so
  331. the SliceModal falls back to the name-based matcher for that preset."""
  332. if not raw:
  333. return None
  334. try:
  335. data = json.loads(raw)
  336. except (ValueError, TypeError):
  337. return None
  338. if not isinstance(data, list):
  339. return None
  340. names = [s for s in data if isinstance(s, str) and s.strip()]
  341. return names or None
  342. def _parse_filament_metadata(setting_json: str | None) -> tuple[str | None, str | None]:
  343. """Extract first-slot ``filament_type`` and ``filament_colour`` from a
  344. stored preset JSON. OrcaSlicer stores both as arrays (per-extruder) — we
  345. take the first entry since pre-pick matching is one-slot-at-a-time.
  346. Defensive parse: any error returns (None, None) so a corrupt row never
  347. breaks the listing."""
  348. if not setting_json:
  349. return None, None
  350. try:
  351. data = json.loads(setting_json)
  352. except (ValueError, TypeError):
  353. return None, None
  354. if not isinstance(data, dict):
  355. return None, None
  356. return _first_scalar(data.get("filament_type")), _first_scalar(data.get("filament_colour"))
  357. def _first_scalar(value: object) -> str | None:
  358. if isinstance(value, list) and value:
  359. return value[0] if isinstance(value[0], str) else None
  360. if isinstance(value, str) and value:
  361. return value
  362. return None
  363. async def _fetch_bundled_presets(db: AsyncSession, *, refresh: bool = False) -> dict[str, list[UnifiedPreset]]:
  364. """Standard slicer-bundled profiles via the sidecar's /profiles/bundled.
  365. ``refresh=True`` skips the in-process cache; see _fetch_cloud_presets for
  366. the same shape and rationale.
  367. """
  368. global _bundled_cache
  369. now = time.monotonic()
  370. if not refresh and _bundled_cache and now - _bundled_cache[0] < _BUNDLED_TTL_S:
  371. return _bundled_cache[1]
  372. api_url = await _resolve_slicer_api_url(db)
  373. if not api_url:
  374. # No sidecar configured at all — return empty rather than caching, so
  375. # users who configure one mid-session see results on next open.
  376. return _empty_slots()
  377. try:
  378. async with SlicerApiService(base_url=api_url) as svc:
  379. raw = await svc.list_bundled_profiles()
  380. except SlicerApiError as e:
  381. logger.info("Bundled preset fetch from sidecar at %s failed: %s", api_url, e)
  382. return _empty_slots()
  383. except Exception as e: # noqa: BLE001 — never break the modal on sidecar issues
  384. logger.warning("Bundled preset fetch unexpected error: %s", e)
  385. return _empty_slots()
  386. slots = _empty_slots()
  387. for slot in ("printer", "process", "filament"):
  388. for entry in raw.get(slot, []) or []:
  389. name = entry.get("name")
  390. if not name:
  391. continue
  392. # Bundled presets are addressed by name (the slicer resolves them
  393. # by name during the `inherits:` walk), so name doubles as id.
  394. preset = UnifiedPreset(id=name, name=name, source="standard")
  395. if slot == "filament":
  396. preset.filament_type = entry.get("filament_type")
  397. preset.filament_colour = entry.get("filament_colour")
  398. if slot in ("process", "filament"):
  399. # The slicer's own compatible-printer list, and the only
  400. # truthful answer for several Bambu printers: the bundle ships
  401. # no process preset named after a P1S, an X1, an X1E or an H2D
  402. # Pro -- each one is served by another model's preset that
  403. # names it here. Inferring the printer from the preset NAME
  404. # instead read all 198 as belonging to the model in their
  405. # `@BBL` tag, so a P1S had zero compatible processes, the
  406. # dropdown hid every one of them, and the auto-pick landed on
  407. # an A1 0.2-nozzle process the CLI then refused (#2982).
  408. #
  409. # Older sidecars don't report the field. They return None here,
  410. # which leaves the SliceModal on the name matcher for the
  411. # standard tier -- degraded exactly as before, not broken.
  412. preset.compatible_printers = _content_compatible_printers(entry)
  413. slots[slot].append(preset)
  414. _bundled_cache = (now, slots)
  415. return slots
  416. async def _resolve_slicer_api_url(db: AsyncSession) -> str | None:
  417. """Pick the sidecar URL the bundled-listing fetch should hit.
  418. Mirrors the slice route's resolution at ``library.py:_run_slicer_with_fallback``:
  419. the user's ``preferred_slicer`` setting decides which sidecar Bambuddy
  420. talks to, and the per-install URL setting overrides the env default.
  421. A user who prefers Bambu Studio gets the *bambu-studio-api* sidecar's
  422. bundled list; a user who prefers OrcaSlicer gets the *orca-slicer-api*
  423. sidecar's bundled list. Without this branch the listing would always
  424. hit OrcaSlicer (port 3003) even for BambuStudio installs (port 3001),
  425. leaving the Standard tier permanently empty for them.
  426. """
  427. from backend.app.api.routes.settings import get_setting
  428. preferred = (await get_setting(db, "preferred_slicer")) or "bambu_studio"
  429. if preferred == "orcaslicer":
  430. configured = await get_setting(db, "orcaslicer_api_url")
  431. url = (configured or app_settings.slicer_api_url).strip()
  432. elif preferred == "bambu_studio":
  433. configured = await get_setting(db, "bambu_studio_api_url")
  434. url = (configured or app_settings.bambu_studio_api_url).strip()
  435. else:
  436. # Unknown preference — return None so the bundled tier is empty
  437. # rather than crashing the modal. The slice route raises 400 here;
  438. # we degrade silently because the modal's listing is informational.
  439. logger.warning("Unknown preferred_slicer setting: %r — bundled tier disabled", preferred)
  440. return None
  441. return url or None
  442. def _enrich_cloud_metadata(
  443. orca_cloud: dict[str, list[UnifiedPreset]],
  444. cloud: dict[str, list[UnifiedPreset]],
  445. local: dict[str, list[UnifiedPreset]],
  446. standard: dict[str, list[UnifiedPreset]],
  447. ) -> tuple[
  448. dict[str, list[UnifiedPreset]],
  449. dict[str, list[UnifiedPreset]],
  450. dict[str, list[UnifiedPreset]],
  451. dict[str, list[UnifiedPreset]],
  452. ]:
  453. """Backfill Bambu Cloud filament metadata; do NOT dedup tiers.
  454. Every tier surfaces its full list — a name that exists in both ``local``
  455. and ``orca_cloud`` shows up in BOTH dropdown groups so the user can pick
  456. either source. Tier ORDER (``local > orca_cloud > cloud > standard``)
  457. is communicated by the SliceModal's group rendering and by the
  458. name-collision fallback in ``findPresetByName``; this function does not
  459. enforce it.
  460. Filament metadata merge: a Bambu Cloud entry without its own
  461. ``filament_type`` / ``filament_colour`` (Bambu Cloud doesn't surface
  462. these in the list response for rate-limiting reasons — see
  463. :func:`_fetch_cloud_presets`) inherits values from a same-named entry
  464. in ``local`` / ``orca_cloud`` / ``standard``. This is the only reason
  465. this function exists post-#1712 — without the enrich the Bambu Cloud
  466. tier can't score in ``pickFilamentForSlot``.
  467. Compatibility merge (#2628): the same name bridge carries
  468. ``compatible_printers`` onto any process / filament entry that lacks it.
  469. Bambu Cloud never ships the list, so a profile whose NAME carries no
  470. printer model reads as "compatibility unknown" — which the SliceModal
  471. treats as usable and auto-picks for whatever printer is selected. When
  472. the very same profile is also present as a local import or an Orca Cloud
  473. profile, that copy states the truth; borrowing it turns the auto-pick
  474. into a correctly-rejected mismatch. Only ever fills a gap: an entry that
  475. carries its own list keeps it.
  476. """
  477. # Build a name → metadata lookup from the tiers that carry it (local,
  478. # orca_cloud, standard). Bambu cloud is intentionally skipped — it
  479. # doesn't populate filament_type/colour in the list response. Take
  480. # whichever non-empty entry shows up first.
  481. metadata_by_name: dict[str, tuple[str | None, str | None]] = {}
  482. for tier in (local, orca_cloud, standard):
  483. for p in tier["filament"]:
  484. if p.name in metadata_by_name:
  485. continue
  486. if p.filament_type or p.filament_colour:
  487. metadata_by_name[p.name] = (p.filament_type, p.filament_colour)
  488. # Backfill Bambu Cloud entries that don't have their own metadata.
  489. for p in cloud["filament"]:
  490. if (p.filament_type is None or p.filament_colour is None) and p.name in metadata_by_name:
  491. t, c = metadata_by_name[p.name]
  492. if p.filament_type is None and t is not None:
  493. p.filament_type = t
  494. if p.filament_colour is None and c is not None:
  495. p.filament_colour = c
  496. # Compatibility bridge (#2628). Runs over both slots that carry the
  497. # list, and in both directions between the cloud tiers — whichever copy
  498. # of a profile knows its printers teaches the ones that don't.
  499. for slot in ("process", "filament"):
  500. compat_by_name: dict[str, list[str]] = {}
  501. for tier in (local, orca_cloud, cloud, standard):
  502. for p in tier[slot]:
  503. if p.compatible_printers and p.name not in compat_by_name:
  504. compat_by_name[p.name] = p.compatible_printers
  505. if not compat_by_name:
  506. continue
  507. for tier in (orca_cloud, cloud):
  508. for p in tier[slot]:
  509. if not p.compatible_printers:
  510. borrowed = compat_by_name.get(p.name)
  511. if borrowed:
  512. p.compatible_printers = list(borrowed)
  513. return orca_cloud, cloud, local, standard
  514. @router.get("/printer-models")
  515. def list_printer_models() -> dict[str, str]:
  516. """Canonical Bambu printer-model registry, surfaced for the SliceModal.
  517. Returns the backend's ``PRINTER_MODEL_MAP`` unmodified: keys are the long
  518. "Bambu Lab <model>" form that appears in 3MF metadata and in slicer
  519. printer-preset names, values are the normalized short codes used in
  520. BambuStudio's `@BBL <code>` cloud-preset filenames. The frontend uses this
  521. mapping to classify cloud / standard presets against the selected printer,
  522. which carry no ``compatible_printers`` of their own (#1325 follow-up) -
  523. avoiding a second, manually-maintained model table on the
  524. frontend. No auth gate: this is a static reference dictionary, not
  525. user data.
  526. """
  527. return dict(PRINTER_MODEL_MAP)
  528. @router.get("/preset-values")
  529. async def get_preset_values(
  530. source: str = Query(..., description="Preset tier: 'local', 'cloud', 'orca_cloud' or 'standard'."),
  531. id: str = Query(..., description="Preset id within that tier."),
  532. slot: str = Query("process", description="Preset slot. Only 'process' is supported today."),
  533. db: AsyncSession = Depends(get_db),
  534. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.LIBRARY_UPLOAD),
  535. api_key_cloud_owner: User | None = Depends(resolve_api_key_cloud_owner),
  536. ) -> dict:
  537. """Effective values of a preset, with its ``inherits:`` chain flattened.
  538. Drives the slice modal's process-settings panel: without this the panel can
  539. only show the option schema's compiled-in defaults, so a preset that sets a
  540. 0.42mm line width appears as the C++ default of 0.
  541. The flattening is done by the *sidecar*, deliberately. A "Standard" pick is
  542. only a ``{inherits: "<name>"}`` stub on our side, and even local/cloud
  543. presets are deltas — the values live in the profile tree bundled inside the
  544. running sidecar image. Bambuddy's own ``orca_profiles`` resolver walks
  545. OrcaSlicer's published tree instead, which can disagree with what actually
  546. slices; showing numbers from it would be confidently wrong.
  547. Returns ``{"resolved": false, "values": {}, "reason": "..."}`` rather than
  548. an error whenever the values can't be obtained. ``reason`` is what makes
  549. the fallback actionable: a Bambuddy install pulls its sidecar as
  550. ``SIDECAR_TAG:-latest`` regardless of its own release channel, so the
  551. overwhelmingly common cause is a sidecar older than the endpoint — which
  552. the user fixes by pulling a newer image, if we tell them that instead of
  553. "could not read the values".
  554. """
  555. if slot != "process":
  556. raise HTTPException(status_code=400, detail="Only the 'process' slot is supported")
  557. ref = PresetRef(source=source, id=id)
  558. def unresolved(reason: str) -> dict:
  559. return {"resolved": False, "values": {}, "reason": reason}
  560. try:
  561. # A cloud preset resolves as the key's owner for a key with Allow
  562. # Cloud Access, like the listing below.
  563. profile_json = await resolve_preset_ref(db, current_user or api_key_cloud_owner, ref, slot)
  564. except HTTPException:
  565. # A preset the caller can't resolve is not a reason to break the panel;
  566. # the slice itself will report it properly if they go ahead.
  567. logger.info("Could not resolve %s preset %s for value lookup", slot, id)
  568. return unresolved("preset_unresolved")
  569. api_url = await _resolve_slicer_api_url(db)
  570. if not api_url:
  571. return unresolved("not_configured")
  572. service = SlicerApiService(api_url)
  573. try:
  574. resolved = await service.resolve_profile(profile_json, "process")
  575. except SlicerApiUnavailableError:
  576. return unresolved("sidecar_unavailable")
  577. finally:
  578. await service.close()
  579. if resolved.values is None:
  580. return unresolved(resolved.reason)
  581. return {"resolved": True, "values": resolved.values, "reason": "ok"}
  582. @router.get("/presets", response_model=UnifiedPresetsResponse)
  583. async def list_unified_presets(
  584. db: AsyncSession = Depends(get_db),
  585. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.LIBRARY_UPLOAD),
  586. api_key_cloud_owner: User | None = Depends(resolve_api_key_cloud_owner),
  587. refresh: bool = Query(
  588. False,
  589. description=(
  590. "Bypass the in-process cloud and bundled-preset caches for this "
  591. "request. The SliceModal's Refresh button sets this so users who "
  592. "deleted a preset in Bambu Studio or Bambu Handy don't have to "
  593. "wait for the 5-minute cloud-cache TTL to expire."
  594. ),
  595. ),
  596. ) -> UnifiedPresetsResponse:
  597. """List slicer presets across cloud / local / standard tiers, deduped by name.
  598. Drives the SliceModal preset dropdowns. Permission gate matches the
  599. slice action itself (``LIBRARY_UPLOAD``) so any user who can slice can
  600. see the preset options for the dialog. The cloud branch is independently
  601. gated on ``CLOUD_AUTH`` inside ``_fetch_cloud_presets`` so a user with
  602. only ``LIBRARY_UPLOAD`` doesn't see cloud presets they shouldn't have
  603. access to.
  604. API-keyed callers (which return None from ``current_user``) get the
  605. owner User via ``resolve_api_key_cloud_owner`` when the key has the
  606. cloud-access scope, so the cloud tier surfaces correctly for them
  607. too — matching the slice route (#1182 follow-up).
  608. """
  609. cloud_token_user = current_user or api_key_cloud_owner
  610. orca_cloud, orca_cloud_status = await _fetch_orca_cloud_presets(db, cloud_token_user, refresh=refresh)
  611. cloud, cloud_status = await _fetch_cloud_presets(db, cloud_token_user, refresh=refresh)
  612. local = await _fetch_local_presets(db)
  613. standard = await _fetch_bundled_presets(db, refresh=refresh)
  614. orca_cloud, cloud, local, standard = _enrich_cloud_metadata(orca_cloud, cloud, local, standard)
  615. return UnifiedPresetsResponse(
  616. orca_cloud=UnifiedPresetsBySlot(**orca_cloud),
  617. cloud=UnifiedPresetsBySlot(**cloud),
  618. local=UnifiedPresetsBySlot(**local),
  619. standard=UnifiedPresetsBySlot(**standard),
  620. cloud_status=cloud_status,
  621. orca_cloud_status=orca_cloud_status,
  622. )
  623. def _loaded_spool_tray(raw: dict, ams_id: int, tray_id: int, saved: SlotPresetMapping | None) -> LoadedSpoolTray:
  624. exists = raw.get("exists")
  625. state = raw.get("state")
  626. return LoadedSpoolTray(
  627. ams_id=ams_id,
  628. tray_id=tray_id,
  629. tray_type=raw.get("tray_type") or None,
  630. tray_sub_brands=raw.get("tray_sub_brands") or None,
  631. tray_color=raw.get("tray_color") or None,
  632. tray_info_idx=raw.get("tray_info_idx") or None,
  633. exists=exists if isinstance(exists, bool) else None,
  634. state=state if isinstance(state, int) else None,
  635. saved_preset=(
  636. LoadedSpoolPreset(
  637. preset_id=saved.preset_id,
  638. preset_name=saved.preset_name,
  639. preset_source=saved.preset_source,
  640. tray_info_idx=saved.tray_info_idx,
  641. )
  642. if saved is not None
  643. else None
  644. ),
  645. )
  646. @router.get("/loaded-spools", response_model=LoadedSpoolsResponse)
  647. async def list_loaded_spools(
  648. db: AsyncSession = Depends(get_db),
  649. _: User | None = RequirePermissionIfAuthEnabled(Permission.LIBRARY_UPLOAD, Permission.PRINTERS_READ),
  650. printer_scope: PrinterScope = RequestPrinterScope,
  651. ) -> LoadedSpoolsResponse:
  652. """What is loaded in each connected printer, for the SliceModal's filters (#3172).
  653. One call rather than a status request per printer: the dialog needs every
  654. connected printer at once, and a farm has a hundred of them. Gated on the
  655. slice permission plus printers:read, because it shows what the printer
  656. status does, and limited to the caller's printers (#1727).
  657. Only printers with a live connection are listed: an offline printer can't
  658. say what it has loaded, and its last-known trays may be long gone.
  659. """
  660. query = select(Printer).where(Printer.is_active == True).order_by(Printer.name) # noqa: E712
  661. scope_clause = printer_scope.where_strict(Printer.id)
  662. if scope_clause is not None:
  663. query = query.where(scope_clause)
  664. printers = (await db.execute(query)).scalars().all()
  665. connected: list[tuple[Printer, dict]] = []
  666. for printer in printers:
  667. state = printer_manager.get_status(printer.id)
  668. if state is None or not state.connected:
  669. continue
  670. connected.append((printer, state.raw_data or {}))
  671. if not connected:
  672. return LoadedSpoolsResponse()
  673. mappings = (
  674. (
  675. await db.execute(
  676. select(SlotPresetMapping).where(SlotPresetMapping.printer_id.in_([p.id for p, _ in connected]))
  677. )
  678. )
  679. .scalars()
  680. .all()
  681. )
  682. saved = {(m.printer_id, m.ams_id, m.tray_id): m for m in mappings}
  683. out: list[LoadedSpoolPrinter] = []
  684. for printer, raw_data in connected:
  685. units: list[LoadedSpoolUnit] = []
  686. raw_ams = raw_data.get("ams")
  687. for ams_data in raw_ams if isinstance(raw_ams, list) else []:
  688. if not isinstance(ams_data, dict):
  689. continue
  690. ams_id = int(ams_data.get("id", 0))
  691. raw_trays = [t for t in ams_data.get("tray") or [] if isinstance(t, dict)]
  692. trays = [
  693. _loaded_spool_tray(t, ams_id, int(t.get("id", 0)), saved.get((printer.id, ams_id, int(t.get("id", 0)))))
  694. for t in raw_trays
  695. ]
  696. # Same rule as the printer status: an AMS-HT is a unit id 128-135.
  697. units.append(LoadedSpoolUnit(id=ams_id, is_ams_ht=128 <= ams_id <= 135, trays=trays))
  698. external: list[LoadedSpoolTray] = []
  699. holders = [vt for vt in raw_data.get("vt_tray") or [] if isinstance(vt, dict)]
  700. for vt in holders:
  701. if not vt.get("tray_type"):
  702. continue
  703. # The holders are trays 254 / 255; slot presets key them as AMS 255,
  704. # tray 0 / 1, the way the printer card saves them.
  705. tray_id = int(vt.get("id", 254)) - 254
  706. external.append(_loaded_spool_tray(vt, 255, tray_id, saved.get((printer.id, 255, tray_id))))
  707. out.append(
  708. LoadedSpoolPrinter(
  709. id=printer.id,
  710. name=printer.name,
  711. model=normalize_printer_model_id(printer.model) or normalize_printer_model(printer.model),
  712. ams=units,
  713. external=external,
  714. external_holders=len(holders),
  715. )
  716. )
  717. return LoadedSpoolsResponse(printers=out)
  718. @router.get("/preview-progress/{request_id}")
  719. async def get_preview_slice_progress(
  720. request_id: str,
  721. db: AsyncSession = Depends(get_db),
  722. _: tuple[User | ApiKeyActor | None, bool] = Depends(
  723. require_ownership_permission(
  724. Permission.LIBRARY_READ_ALL,
  725. Permission.LIBRARY_READ_OWN,
  726. )
  727. ),
  728. ):
  729. """Proxy to the sidecar's ``GET /slice/progress/:requestId``.
  730. The SliceModal's filament-requirements call kicks off a real preview
  731. slice on the sidecar to discover which AMS slots the picked plate
  732. actually consumes. That HTTP call holds open for the full slice
  733. duration (multi-second to multi-minute on complex models), and the
  734. browser can't reach the sidecar directly thanks to the same-origin
  735. policy + the sidecar's CORS allowlist. This endpoint forwards the
  736. poll so the modal's inline spinner can show "Generating G-code (45%)"
  737. instead of an opaque elapsed-time counter while the preview runs.
  738. Returns the sidecar's snapshot verbatim, or 404 when the request_id
  739. is unknown / completed and grace-window-expired.
  740. """
  741. import httpx
  742. api_url = await _resolve_slicer_api_url(db)
  743. if not api_url:
  744. raise HTTPException(status_code=503, detail="No slicer sidecar configured")
  745. url = f"{api_url}/slice/progress/{request_id}"
  746. try:
  747. async with httpx.AsyncClient(timeout=5.0) as client:
  748. response = await client.get(url)
  749. except httpx.TimeoutException:
  750. # Busy, not gone: a heavy slice can hold the progress answer past 5 s
  751. # (TO-C14). Still 503, so the poller keeps trying.
  752. raise HTTPException(status_code=503, detail="Slicer sidecar did not answer in time") from None
  753. except httpx.RequestError:
  754. # Sidecar unreachable: surface as 503 instead of 500 so the
  755. # frontend's poller can keep trying without flagging a hard error.
  756. raise HTTPException(status_code=503, detail="Slicer sidecar unreachable") from None
  757. if response.status_code == 404:
  758. raise HTTPException(status_code=404, detail="Progress unavailable")
  759. return response.json()