slicer_presets.py 28 KB

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