virtual_printers.py 24 KB

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