virtual_printers.py 30 KB

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