virtual_printers.py 31 KB

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