virtual_printers.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. import logging
  2. from fastapi import APIRouter, Depends
  3. from fastapi.responses import JSONResponse
  4. from pydantic import BaseModel
  5. from sqlalchemy import select
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from backend.app.core.auth import RequirePermissionIfAuthEnabled
  8. from backend.app.core.database import get_db
  9. from backend.app.core.permissions import Permission
  10. from backend.app.models.user import User
  11. from backend.app.schemas.virtual_printer import VPDiagnosticResult
  12. # Imported at module scope so tests can patch
  13. # backend.app.api.routes.virtual_printers.tailscale_service.
  14. from backend.app.services.virtual_printer.tailscale import tailscale_service
  15. logger = logging.getLogger(__name__)
  16. router = APIRouter(prefix="/virtual-printers", tags=["virtual-printers"])
  17. class TailscaleStatusResponse(BaseModel):
  18. available: bool
  19. fqdn: str
  20. hostname: str
  21. tailnet_name: str
  22. tailscale_ips: list[str]
  23. error: str | None
  24. class VirtualPrinterCreate(BaseModel):
  25. name: str = "Bambuddy"
  26. enabled: bool = False
  27. mode: str = "archive"
  28. model: str | None = None
  29. access_code: str | None = None
  30. target_printer_id: int | None = None
  31. auto_dispatch: bool = True
  32. queue_force_color_match: bool = False
  33. gcode_injection: bool = False
  34. bind_ip: str | None = None
  35. remote_interface_ip: str | None = None
  36. class VirtualPrinterUpdate(BaseModel):
  37. name: str | None = None
  38. enabled: bool | None = None
  39. mode: str | None = None
  40. model: str | None = None
  41. access_code: str | None = None
  42. target_printer_id: int | None = None
  43. auto_dispatch: bool | None = None
  44. queue_force_color_match: bool | None = None
  45. gcode_injection: bool | None = None
  46. bind_ip: str | None = None
  47. remote_interface_ip: str | None = None
  48. tailscale_disabled: bool | None = None
  49. def _resolve_printer_model(printer_model: str | None) -> str | None:
  50. """Map a printer's model (display name or SSDP code) to a valid VP SSDP model code.
  51. Printers store display names like 'X1C' while VPs need SSDP codes like 'BL-P001'.
  52. """
  53. if not printer_model:
  54. return None
  55. from backend.app.services.virtual_printer import VIRTUAL_PRINTER_MODELS
  56. from backend.app.services.virtual_printer.manager import DISPLAY_NAME_TO_MODEL_CODE
  57. # Already a valid SSDP model code
  58. if printer_model in VIRTUAL_PRINTER_MODELS:
  59. return printer_model
  60. # Map display name to SSDP code
  61. return DISPLAY_NAME_TO_MODEL_CODE.get(printer_model)
  62. async def _vp_to_dict(vp, db: AsyncSession, status: dict | None = None) -> dict:
  63. """Convert VirtualPrinter model to response dict.
  64. In proxy mode the surfaced serial is the target printer's actual serial
  65. (what the bridge advertises over SSDP / what slicers see), not the
  66. self-generated suffix. Archive / queue / review keep the self-generated
  67. serial since those modes never speak the target's identity.
  68. """
  69. from backend.app.models.printer import Printer
  70. from backend.app.models.virtual_printer import VP_MODE_PROXY
  71. from backend.app.services.virtual_printer import VIRTUAL_PRINTER_MODELS
  72. from backend.app.services.virtual_printer.manager import DEFAULT_VIRTUAL_PRINTER_MODEL, _get_serial_for_model
  73. model_code = vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL
  74. serial = _get_serial_for_model(model_code, vp.serial_suffix)
  75. if vp.mode == VP_MODE_PROXY and vp.target_printer_id:
  76. result = await db.execute(select(Printer.serial_number).where(Printer.id == vp.target_printer_id))
  77. target_serial = result.scalar_one_or_none()
  78. if target_serial:
  79. serial = target_serial
  80. return {
  81. "id": vp.id,
  82. "name": vp.name,
  83. "enabled": vp.enabled,
  84. "mode": vp.mode,
  85. "model": model_code,
  86. "model_name": VIRTUAL_PRINTER_MODELS.get(model_code, model_code),
  87. "access_code_set": bool(vp.access_code),
  88. "serial": serial,
  89. "target_printer_id": vp.target_printer_id,
  90. "auto_dispatch": vp.auto_dispatch,
  91. "queue_force_color_match": vp.queue_force_color_match,
  92. "gcode_injection": vp.gcode_injection,
  93. "bind_ip": vp.bind_ip,
  94. "remote_interface_ip": vp.remote_interface_ip,
  95. "tailscale_disabled": vp.tailscale_disabled,
  96. "position": vp.position,
  97. "status": status or {"running": False, "pending_files": 0},
  98. }
  99. @router.get("")
  100. async def list_virtual_printers(
  101. db: AsyncSession = Depends(get_db),
  102. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  103. ):
  104. """List all virtual printers with status."""
  105. from backend.app.models.virtual_printer import VirtualPrinter
  106. from backend.app.services.virtual_printer import VIRTUAL_PRINTER_MODELS, virtual_printer_manager
  107. result = await db.execute(select(VirtualPrinter).order_by(VirtualPrinter.position, VirtualPrinter.id))
  108. vps = result.scalars().all()
  109. printers = []
  110. for vp in vps:
  111. instance = virtual_printer_manager.get_instance(vp.id)
  112. status = instance.get_status() if instance else {"running": False, "pending_files": 0}
  113. printers.append(await _vp_to_dict(vp, db, status))
  114. return {
  115. "printers": printers,
  116. "models": VIRTUAL_PRINTER_MODELS,
  117. }
  118. @router.post("")
  119. async def create_virtual_printer(
  120. body: VirtualPrinterCreate,
  121. db: AsyncSession = Depends(get_db),
  122. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  123. ):
  124. """Create a new virtual printer."""
  125. from backend.app.models.virtual_printer import VP_MODE_VALUES, VirtualPrinter, normalize_vp_mode
  126. from backend.app.services.virtual_printer import VIRTUAL_PRINTER_MODELS, virtual_printer_manager
  127. from backend.app.services.virtual_printer.manager import DEFAULT_VIRTUAL_PRINTER_MODEL
  128. # Accept both canonical and legacy wire values so older clients (forks /
  129. # mobile shortcuts / scripted setups) still work; normalize before write.
  130. body.mode = normalize_vp_mode(body.mode) or body.mode
  131. if body.mode not in VP_MODE_VALUES:
  132. return JSONResponse(status_code=400, content={"detail": "Invalid mode"})
  133. # Validate model
  134. if body.model and body.model not in VIRTUAL_PRINTER_MODELS:
  135. return JSONResponse(
  136. status_code=400,
  137. content={"detail": f"Invalid model. Must be one of: {', '.join(VIRTUAL_PRINTER_MODELS.keys())}"},
  138. )
  139. # Validate access code length
  140. if body.access_code and len(body.access_code) != 8:
  141. return JSONResponse(status_code=400, content={"detail": "Access code must be exactly 8 characters"})
  142. # Validation when enabling. Non-proxy VPs with a target printer derive
  143. # their access code from the target (the bridge forwards the slicer's
  144. # auth bytes through to the real printer, so the codes MUST match),
  145. # so a separately-supplied access_code isn't required in that case.
  146. if body.enabled:
  147. if not body.bind_ip:
  148. return JSONResponse(status_code=400, content={"detail": "Bind IP is required when enabling"})
  149. if body.mode == "proxy":
  150. if not body.target_printer_id:
  151. return JSONResponse(status_code=400, content={"detail": "Target printer is required for proxy mode"})
  152. else:
  153. if not body.access_code and not body.target_printer_id:
  154. return JSONResponse(status_code=400, content={"detail": "Access code is required when enabling"})
  155. # Validate proxy target printer exists
  156. target_printer = None
  157. if body.target_printer_id:
  158. from backend.app.models.printer import Printer
  159. result = await db.execute(select(Printer).where(Printer.id == body.target_printer_id))
  160. target_printer = result.scalar_one_or_none()
  161. if not target_printer:
  162. return JSONResponse(
  163. status_code=400, content={"detail": f"Printer with ID {body.target_printer_id} not found"}
  164. )
  165. # Validate bind_ip uniqueness (against all enabled VPs)
  166. if body.bind_ip:
  167. result = await db.execute(
  168. select(VirtualPrinter).where(
  169. VirtualPrinter.bind_ip == body.bind_ip,
  170. VirtualPrinter.enabled == True, # noqa: E712
  171. )
  172. )
  173. if result.scalar_one_or_none():
  174. return JSONResponse(status_code=400, content={"detail": f"Bind IP {body.bind_ip} is already in use"})
  175. # Force-inherit the access code from the target printer for non-proxy VPs.
  176. # The non-proxy bridge (Immediate / Review / Queue with a target set) forwards
  177. # the slicer's MQTT / RTSPS auth bytes through to the real printer, so any
  178. # value the user supplied here would silently break the bridge if it didn't
  179. # match the printer's code. The UI now renders the field read-only when a
  180. # target is set; this is the belt-and-braces backstop for any non-UI client.
  181. effective_access_code = body.access_code
  182. if body.mode != "proxy" and target_printer is not None:
  183. effective_access_code = target_printer.access_code
  184. # Generate next serial suffix
  185. result = await db.execute(select(VirtualPrinter.serial_suffix).order_by(VirtualPrinter.id.desc()))
  186. last_suffix = result.scalar()
  187. if last_suffix:
  188. try:
  189. next_num = int(last_suffix) + 1
  190. new_suffix = str(next_num).zfill(9)
  191. except ValueError:
  192. new_suffix = "391800002"
  193. else:
  194. new_suffix = "391800001"
  195. # Get next position
  196. result = await db.execute(select(VirtualPrinter.position).order_by(VirtualPrinter.position.desc()))
  197. last_pos = result.scalar()
  198. next_pos = (last_pos or 0) + 1
  199. vp = VirtualPrinter(
  200. name=body.name,
  201. enabled=body.enabled,
  202. mode=body.mode,
  203. model=body.model
  204. or _resolve_printer_model(target_printer.model if target_printer and body.mode == "proxy" else None)
  205. or DEFAULT_VIRTUAL_PRINTER_MODEL,
  206. access_code=effective_access_code,
  207. target_printer_id=body.target_printer_id,
  208. auto_dispatch=body.auto_dispatch,
  209. queue_force_color_match=body.queue_force_color_match,
  210. gcode_injection=body.gcode_injection,
  211. bind_ip=body.bind_ip,
  212. remote_interface_ip=body.remote_interface_ip,
  213. serial_suffix=new_suffix,
  214. position=next_pos,
  215. )
  216. db.add(vp)
  217. await db.commit()
  218. await db.refresh(vp)
  219. logger.info("Created virtual printer: %s (id=%d)", vp.name, vp.id)
  220. # Sync services if enabled
  221. if body.enabled:
  222. try:
  223. await virtual_printer_manager.sync_from_db()
  224. except Exception as e:
  225. logger.error("Failed to start virtual printer after create: %s", e)
  226. return await _vp_to_dict(vp, db)
  227. @router.get("/tailscale-status", response_model=TailscaleStatusResponse)
  228. async def get_tailscale_status(
  229. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  230. ) -> TailscaleStatusResponse:
  231. """Return current Tailscale availability and machine identity.
  232. Used by the frontend to indicate whether virtual printer TLS is backed
  233. by a trusted Let's Encrypt certificate or a self-signed CA.
  234. """
  235. status = await tailscale_service.get_status()
  236. return TailscaleStatusResponse(
  237. available=status.available,
  238. fqdn=status.fqdn,
  239. hostname=status.hostname,
  240. tailnet_name=status.tailnet_name,
  241. tailscale_ips=status.tailscale_ips,
  242. error=status.error,
  243. )
  244. @router.get("/ca-certificate")
  245. async def get_ca_certificate(
  246. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  247. ):
  248. """Return the shared virtual-printer CA certificate (PEM) for slicer trust import.
  249. One CA is shared by every virtual printer — the user imports it into their
  250. slicer's trust store once. Only the public certificate is returned; the CA
  251. private key never leaves the backend.
  252. """
  253. from backend.app.services.virtual_printer import virtual_printer_manager
  254. try:
  255. return virtual_printer_manager.get_ca_certificate_info()
  256. except Exception as e:
  257. logger.error("Failed to obtain virtual printer CA certificate: %s", e)
  258. return JSONResponse(status_code=500, content={"detail": "Could not generate the CA certificate"})
  259. @router.get("/{vp_id}/diagnostic", response_model=VPDiagnosticResult)
  260. async def diagnose_virtual_printer(
  261. vp_id: int,
  262. db: AsyncSession = Depends(get_db),
  263. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  264. ):
  265. """Run setup diagnostics for a virtual printer.
  266. Probes the VP's own bind IP and services so the user can self-diagnose the
  267. common "my virtual printer doesn't show up in the slicer" failures.
  268. """
  269. from backend.app.models.virtual_printer import VirtualPrinter
  270. from backend.app.services.virtual_printer import virtual_printer_manager
  271. from backend.app.services.virtual_printer.diagnostic import run_vp_diagnostic
  272. result = await db.execute(select(VirtualPrinter).where(VirtualPrinter.id == vp_id))
  273. vp = result.scalar_one_or_none()
  274. if not vp:
  275. return JSONResponse(status_code=404, content={"detail": "Virtual printer not found"})
  276. instance = virtual_printer_manager.get_instance(vp.id)
  277. return await run_vp_diagnostic(vp, instance)
  278. @router.get("/{vp_id}")
  279. async def get_virtual_printer(
  280. vp_id: int,
  281. db: AsyncSession = Depends(get_db),
  282. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  283. ):
  284. """Get a single virtual printer with status."""
  285. from backend.app.models.virtual_printer import VirtualPrinter
  286. from backend.app.services.virtual_printer import virtual_printer_manager
  287. result = await db.execute(select(VirtualPrinter).where(VirtualPrinter.id == vp_id))
  288. vp = result.scalar_one_or_none()
  289. if not vp:
  290. return JSONResponse(status_code=404, content={"detail": "Virtual printer not found"})
  291. instance = virtual_printer_manager.get_instance(vp.id)
  292. status = instance.get_status() if instance else {"running": False, "pending_files": 0}
  293. return await _vp_to_dict(vp, db, status)
  294. @router.put("/{vp_id}")
  295. async def update_virtual_printer(
  296. vp_id: int,
  297. body: VirtualPrinterUpdate,
  298. db: AsyncSession = Depends(get_db),
  299. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  300. ):
  301. """Update a virtual printer."""
  302. from backend.app.models.virtual_printer import VirtualPrinter
  303. from backend.app.services.virtual_printer import VIRTUAL_PRINTER_MODELS, virtual_printer_manager
  304. result = await db.execute(select(VirtualPrinter).where(VirtualPrinter.id == vp_id))
  305. vp = result.scalar_one_or_none()
  306. if not vp:
  307. return JSONResponse(status_code=404, content={"detail": "Virtual printer not found"})
  308. # Redact the access code before logging — model_dump otherwise includes
  309. # the plaintext value at DEBUG, violating the project no-secrets-in-logs
  310. # rule. Replace with a marker that still signals "the user changed it"
  311. # vs "the user didn't touch this field".
  312. _safe_body = body.model_dump(exclude_unset=True)
  313. if "access_code" in _safe_body:
  314. _safe_body["access_code"] = "***"
  315. logger.debug(
  316. "Update VP %d: body=%s, current state: mode=%s, enabled=%s, access_code_set=%s, bind_ip=%s, target=%s",
  317. vp_id,
  318. _safe_body,
  319. vp.mode,
  320. vp.enabled,
  321. bool(vp.access_code),
  322. vp.bind_ip,
  323. vp.target_printer_id,
  324. )
  325. # Apply updates
  326. if body.name is not None:
  327. vp.name = body.name
  328. if body.mode is not None:
  329. from backend.app.models.virtual_printer import VP_MODE_VALUES, normalize_vp_mode
  330. canonical_mode = normalize_vp_mode(body.mode) or body.mode
  331. if canonical_mode not in VP_MODE_VALUES:
  332. return JSONResponse(status_code=400, content={"detail": "Invalid mode"})
  333. vp.mode = canonical_mode
  334. if body.model is not None:
  335. if body.model not in VIRTUAL_PRINTER_MODELS:
  336. return JSONResponse(
  337. status_code=400,
  338. content={"detail": f"Invalid model. Must be one of: {', '.join(VIRTUAL_PRINTER_MODELS.keys())}"},
  339. )
  340. vp.model = body.model
  341. if body.access_code is not None:
  342. if body.access_code and len(body.access_code) != 8:
  343. return JSONResponse(status_code=400, content={"detail": "Access code must be exactly 8 characters"})
  344. vp.access_code = body.access_code
  345. if body.target_printer_id is not None:
  346. from backend.app.models.printer import Printer
  347. result = await db.execute(select(Printer).where(Printer.id == body.target_printer_id))
  348. target_printer = result.scalar_one_or_none()
  349. if not target_printer:
  350. return JSONResponse(
  351. status_code=400, content={"detail": f"Printer with ID {body.target_printer_id} not found"}
  352. )
  353. vp.target_printer_id = body.target_printer_id
  354. # Auto-inherit model from target printer in proxy mode (unless user explicitly set model)
  355. if body.model is None and vp.mode == "proxy" and target_printer.model:
  356. vp.model = _resolve_printer_model(target_printer.model) or target_printer.model
  357. if body.auto_dispatch is not None:
  358. vp.auto_dispatch = body.auto_dispatch
  359. if body.queue_force_color_match is not None:
  360. vp.queue_force_color_match = body.queue_force_color_match
  361. if body.gcode_injection is not None:
  362. vp.gcode_injection = body.gcode_injection
  363. if body.bind_ip is not None:
  364. vp.bind_ip = body.bind_ip
  365. if body.remote_interface_ip is not None:
  366. vp.remote_interface_ip = body.remote_interface_ip
  367. if body.tailscale_disabled is not None:
  368. vp.tailscale_disabled = body.tailscale_disabled
  369. # Auto-inherit model when switching to proxy mode with existing target printer
  370. if body.mode == "proxy" and body.model is None and body.target_printer_id is None and vp.target_printer_id:
  371. from backend.app.models.printer import Printer as PrinterModel
  372. result = await db.execute(select(PrinterModel).where(PrinterModel.id == vp.target_printer_id))
  373. existing_target = result.scalar_one_or_none()
  374. if existing_target and existing_target.model:
  375. vp.model = _resolve_printer_model(existing_target.model) or existing_target.model
  376. # Force-inherit the access code from the target printer for non-proxy VPs.
  377. # See create_virtual_printer for the rationale: the bridge forwards slicer
  378. # auth bytes through, so the VP's code MUST equal the target's. This block
  379. # runs after every patch (whether or not access_code or target were in the
  380. # body), so changing the target also resyncs the code, and an explicit
  381. # access_code submitted alongside a target is silently overridden.
  382. if vp.mode != "proxy" and vp.target_printer_id is not None:
  383. from backend.app.models.printer import Printer as PrinterModelAC
  384. result = await db.execute(select(PrinterModelAC).where(PrinterModelAC.id == vp.target_printer_id))
  385. target_for_ac = result.scalar_one_or_none()
  386. if target_for_ac is not None and vp.access_code != target_for_ac.access_code:
  387. vp.access_code = target_for_ac.access_code
  388. # Determine final enabled state
  389. explicitly_enabling = body.enabled is True
  390. new_enabled = body.enabled if body.enabled is not None else vp.enabled
  391. effective_mode = vp.mode
  392. if explicitly_enabling:
  393. # User is explicitly toggling on — enforce all requirements
  394. if not vp.bind_ip:
  395. logger.warning("Update VP %d rejected: no bind_ip", vp_id)
  396. return JSONResponse(status_code=400, content={"detail": "Bind IP is required when enabling"})
  397. # Validate bind_ip uniqueness (against all enabled VPs)
  398. existing = await db.execute(
  399. select(VirtualPrinter).where(
  400. VirtualPrinter.bind_ip == vp.bind_ip,
  401. VirtualPrinter.id != vp_id,
  402. VirtualPrinter.enabled == True, # noqa: E712
  403. )
  404. )
  405. conflict = existing.scalar_one_or_none()
  406. if conflict:
  407. logger.warning(
  408. "Update VP %d rejected: bind_ip %s already in use by VP %d (enabled=%s, mode=%s)",
  409. vp_id,
  410. vp.bind_ip,
  411. conflict.id,
  412. conflict.enabled,
  413. conflict.mode,
  414. )
  415. return JSONResponse(
  416. status_code=400,
  417. content={"detail": f"Bind IP {vp.bind_ip} is already in use by '{conflict.name}'"},
  418. )
  419. if effective_mode == "proxy":
  420. if not vp.target_printer_id:
  421. logger.warning("Update VP %d rejected: no target_printer_id for proxy mode", vp_id)
  422. return JSONResponse(status_code=400, content={"detail": "Target printer is required for proxy mode"})
  423. else:
  424. if not vp.access_code:
  425. logger.warning(
  426. "Update VP %d rejected: no access_code for non-proxy enable (mode=%s)", vp_id, effective_mode
  427. )
  428. return JSONResponse(status_code=400, content={"detail": "Access code is required when enabling"})
  429. elif new_enabled and body.enabled is None:
  430. # VP is already enabled and user is changing other fields —
  431. # auto-disable if new state doesn't meet requirements
  432. if not vp.bind_ip:
  433. new_enabled = False
  434. elif effective_mode == "proxy":
  435. if not vp.target_printer_id:
  436. new_enabled = False
  437. else:
  438. if not vp.access_code:
  439. new_enabled = False
  440. vp.enabled = new_enabled
  441. await db.commit()
  442. await db.refresh(vp)
  443. logger.info("Updated virtual printer: %s (id=%d)", vp.name, vp.id)
  444. # Sync services
  445. try:
  446. await virtual_printer_manager.sync_from_db()
  447. except Exception as e:
  448. logger.error("Failed to sync virtual printers after update: %s", e)
  449. instance = virtual_printer_manager.get_instance(vp.id)
  450. status = instance.get_status() if instance else {"running": False, "pending_files": 0}
  451. return await _vp_to_dict(vp, db, status)
  452. @router.delete("/{vp_id}")
  453. async def delete_virtual_printer(
  454. vp_id: int,
  455. db: AsyncSession = Depends(get_db),
  456. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  457. ):
  458. """Delete a virtual printer."""
  459. from sqlalchemy import delete as sql_delete
  460. from backend.app.models.virtual_printer import VirtualPrinter
  461. from backend.app.services.virtual_printer import virtual_printer_manager
  462. result = await db.execute(select(VirtualPrinter).where(VirtualPrinter.id == vp_id))
  463. vp = result.scalar_one_or_none()
  464. if not vp:
  465. return JSONResponse(status_code=404, content={"detail": "Virtual printer not found"})
  466. vp_name = vp.name
  467. # Stop instance if running
  468. await virtual_printer_manager.remove_instance(vp_id)
  469. # Mark any PendingUpload rows that referenced this VP's upload_dir as
  470. # discarded — without this the rows live on as phantom entries in
  471. # /pending-uploads/ pointing at file paths that no longer exist, and
  472. # the user only learns they're orphaned by trying to archive one and
  473. # getting a flip-to-discarded on file-missing.
  474. upload_prefix = str(virtual_printer_manager._base_dir / "uploads" / str(vp_id))
  475. try:
  476. from backend.app.models.pending_upload import PendingUpload
  477. stale = await db.execute(select(PendingUpload).where(PendingUpload.file_path.startswith(upload_prefix)))
  478. for pending in stale.scalars().all():
  479. pending.status = "discarded"
  480. await db.flush()
  481. except Exception as e:
  482. logger.error("Failed to discard orphan PendingUpload rows for VP %d: %s", vp_id, e)
  483. # Delete from DB
  484. await db.execute(sql_delete(VirtualPrinter).where(VirtualPrinter.id == vp_id))
  485. await db.commit()
  486. # Remove the on-disk upload directory after the DB commit succeeds, so
  487. # a crash between commit and rmtree only leaves orphan files (vs orphan
  488. # rows pointing at a now-missing tree).
  489. upload_dir = virtual_printer_manager._base_dir / "uploads" / str(vp_id)
  490. if upload_dir.exists():
  491. import shutil
  492. shutil.rmtree(upload_dir, ignore_errors=True)
  493. logger.info("Deleted virtual printer: %s (id=%d)", vp_name, vp_id)
  494. # Resync remaining services
  495. try:
  496. await virtual_printer_manager.sync_from_db()
  497. except Exception as e:
  498. logger.error("Failed to sync virtual printers after delete: %s", e)
  499. return {"detail": "Deleted", "id": vp_id}