virtual_printers.py 35 KB

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