virtual_printers.py 24 KB

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