slicer_presets.py 41 KB

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