slicer_presets.py 31 KB

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