virtual_printers.py 26 KB

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