virtual_printers.py 21 KB

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