virtual_printers.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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. logger.debug(
  279. "Update VP %d: body=%s, current state: mode=%s, enabled=%s, access_code_set=%s, bind_ip=%s, target=%s",
  280. vp_id,
  281. body.model_dump(exclude_unset=True),
  282. vp.mode,
  283. vp.enabled,
  284. bool(vp.access_code),
  285. vp.bind_ip,
  286. vp.target_printer_id,
  287. )
  288. # Apply updates
  289. if body.name is not None:
  290. vp.name = body.name
  291. if body.mode is not None:
  292. if body.mode not in ("immediate", "review", "print_queue", "proxy"):
  293. return JSONResponse(status_code=400, content={"detail": "Invalid mode"})
  294. vp.mode = body.mode
  295. if body.model is not None:
  296. if body.model not in VIRTUAL_PRINTER_MODELS:
  297. return JSONResponse(
  298. status_code=400,
  299. content={"detail": f"Invalid model. Must be one of: {', '.join(VIRTUAL_PRINTER_MODELS.keys())}"},
  300. )
  301. vp.model = body.model
  302. if body.access_code is not None:
  303. if body.access_code and len(body.access_code) != 8:
  304. return JSONResponse(status_code=400, content={"detail": "Access code must be exactly 8 characters"})
  305. vp.access_code = body.access_code
  306. if body.target_printer_id is not None:
  307. from backend.app.models.printer import Printer
  308. result = await db.execute(select(Printer).where(Printer.id == body.target_printer_id))
  309. target_printer = result.scalar_one_or_none()
  310. if not target_printer:
  311. return JSONResponse(
  312. status_code=400, content={"detail": f"Printer with ID {body.target_printer_id} not found"}
  313. )
  314. vp.target_printer_id = body.target_printer_id
  315. # Auto-inherit model from target printer in proxy mode (unless user explicitly set model)
  316. if body.model is None and vp.mode == "proxy" and target_printer.model:
  317. vp.model = _resolve_printer_model(target_printer.model) or target_printer.model
  318. if body.auto_dispatch is not None:
  319. vp.auto_dispatch = body.auto_dispatch
  320. if body.queue_force_color_match is not None:
  321. vp.queue_force_color_match = body.queue_force_color_match
  322. if body.bind_ip is not None:
  323. vp.bind_ip = body.bind_ip
  324. if body.remote_interface_ip is not None:
  325. vp.remote_interface_ip = body.remote_interface_ip
  326. if body.tailscale_disabled is not None:
  327. vp.tailscale_disabled = body.tailscale_disabled
  328. # Auto-inherit model when switching to proxy mode with existing target printer
  329. if body.mode == "proxy" and body.model is None and body.target_printer_id is None and vp.target_printer_id:
  330. from backend.app.models.printer import Printer as PrinterModel
  331. result = await db.execute(select(PrinterModel).where(PrinterModel.id == vp.target_printer_id))
  332. existing_target = result.scalar_one_or_none()
  333. if existing_target and existing_target.model:
  334. vp.model = _resolve_printer_model(existing_target.model) or existing_target.model
  335. # Determine final enabled state
  336. explicitly_enabling = body.enabled is True
  337. new_enabled = body.enabled if body.enabled is not None else vp.enabled
  338. effective_mode = vp.mode
  339. if explicitly_enabling:
  340. # User is explicitly toggling on — enforce all requirements
  341. if not vp.bind_ip:
  342. logger.warning("Update VP %d rejected: no bind_ip", vp_id)
  343. return JSONResponse(status_code=400, content={"detail": "Bind IP is required when enabling"})
  344. # Validate bind_ip uniqueness (against all enabled VPs)
  345. existing = await db.execute(
  346. select(VirtualPrinter).where(
  347. VirtualPrinter.bind_ip == vp.bind_ip,
  348. VirtualPrinter.id != vp_id,
  349. VirtualPrinter.enabled == True, # noqa: E712
  350. )
  351. )
  352. conflict = existing.scalar_one_or_none()
  353. if conflict:
  354. logger.warning(
  355. "Update VP %d rejected: bind_ip %s already in use by VP %d (enabled=%s, mode=%s)",
  356. vp_id,
  357. vp.bind_ip,
  358. conflict.id,
  359. conflict.enabled,
  360. conflict.mode,
  361. )
  362. return JSONResponse(
  363. status_code=400,
  364. content={"detail": f"Bind IP {vp.bind_ip} is already in use by '{conflict.name}'"},
  365. )
  366. if effective_mode == "proxy":
  367. if not vp.target_printer_id:
  368. logger.warning("Update VP %d rejected: no target_printer_id for proxy mode", vp_id)
  369. return JSONResponse(status_code=400, content={"detail": "Target printer is required for proxy mode"})
  370. else:
  371. if not vp.access_code:
  372. logger.warning(
  373. "Update VP %d rejected: no access_code for non-proxy enable (mode=%s)", vp_id, effective_mode
  374. )
  375. return JSONResponse(status_code=400, content={"detail": "Access code is required when enabling"})
  376. elif new_enabled and body.enabled is None:
  377. # VP is already enabled and user is changing other fields —
  378. # auto-disable if new state doesn't meet requirements
  379. if not vp.bind_ip:
  380. new_enabled = False
  381. elif effective_mode == "proxy":
  382. if not vp.target_printer_id:
  383. new_enabled = False
  384. else:
  385. if not vp.access_code:
  386. new_enabled = False
  387. vp.enabled = new_enabled
  388. await db.commit()
  389. await db.refresh(vp)
  390. logger.info("Updated virtual printer: %s (id=%d)", vp.name, vp.id)
  391. # Sync services
  392. try:
  393. await virtual_printer_manager.sync_from_db()
  394. except Exception as e:
  395. logger.error("Failed to sync virtual printers after update: %s", e)
  396. instance = virtual_printer_manager.get_instance(vp.id)
  397. status = instance.get_status() if instance else {"running": False, "pending_files": 0}
  398. return _vp_to_dict(vp, status)
  399. @router.delete("/{vp_id}")
  400. async def delete_virtual_printer(
  401. vp_id: int,
  402. db: AsyncSession = Depends(get_db),
  403. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  404. ):
  405. """Delete a virtual printer."""
  406. from sqlalchemy import delete as sql_delete
  407. from backend.app.models.virtual_printer import VirtualPrinter
  408. from backend.app.services.virtual_printer import virtual_printer_manager
  409. result = await db.execute(select(VirtualPrinter).where(VirtualPrinter.id == vp_id))
  410. vp = result.scalar_one_or_none()
  411. if not vp:
  412. return JSONResponse(status_code=404, content={"detail": "Virtual printer not found"})
  413. vp_name = vp.name
  414. # Stop instance if running
  415. await virtual_printer_manager.remove_instance(vp_id)
  416. # Delete from DB
  417. await db.execute(sql_delete(VirtualPrinter).where(VirtualPrinter.id == vp_id))
  418. await db.commit()
  419. logger.info("Deleted virtual printer: %s (id=%d)", vp_name, vp_id)
  420. # Resync remaining services
  421. try:
  422. await virtual_printer_manager.sync_from_db()
  423. except Exception as e:
  424. logger.error("Failed to sync virtual printers after delete: %s", e)
  425. return {"detail": "Deleted", "id": vp_id}