slicer_presets.py 32 KB

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