virtual_printers.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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. # Imported at module scope so tests can patch
  12. # backend.app.api.routes.virtual_printers.tailscale_service.
  13. from backend.app.services.virtual_printer.tailscale import tailscale_service
  14. logger = logging.getLogger(__name__)
  15. router = APIRouter(prefix="/virtual-printers", tags=["virtual-printers"])
  16. class TailscaleStatusResponse(BaseModel):
  17. available: bool
  18. fqdn: str
  19. hostname: str
  20. tailnet_name: str
  21. tailscale_ips: list[str]
  22. error: str | None
  23. class VirtualPrinterCreate(BaseModel):
  24. name: str = "Bambuddy"
  25. enabled: bool = False
  26. mode: str = "immediate"
  27. model: str | None = None
  28. access_code: str | None = None
  29. target_printer_id: int | None = None
  30. auto_dispatch: bool = True
  31. bind_ip: str | None = None
  32. remote_interface_ip: str | None = None
  33. class VirtualPrinterUpdate(BaseModel):
  34. name: str | None = None
  35. enabled: bool | None = None
  36. mode: str | None = None
  37. model: str | None = None
  38. access_code: str | None = None
  39. target_printer_id: int | None = None
  40. auto_dispatch: bool | None = None
  41. bind_ip: str | None = None
  42. remote_interface_ip: str | None = None
  43. tailscale_disabled: bool | None = None
  44. def _resolve_printer_model(printer_model: str | None) -> str | None:
  45. """Map a printer's model (display name or SSDP code) to a valid VP SSDP model code.
  46. Printers store display names like 'X1C' while VPs need SSDP codes like 'BL-P001'.
  47. """
  48. if not printer_model:
  49. return None
  50. from backend.app.services.virtual_printer import VIRTUAL_PRINTER_MODELS
  51. from backend.app.services.virtual_printer.manager import DISPLAY_NAME_TO_MODEL_CODE
  52. # Already a valid SSDP model code
  53. if printer_model in VIRTUAL_PRINTER_MODELS:
  54. return printer_model
  55. # Map display name to SSDP code
  56. return DISPLAY_NAME_TO_MODEL_CODE.get(printer_model)
  57. def _vp_to_dict(vp, status: dict | None = None) -> dict:
  58. """Convert VirtualPrinter model to response dict."""
  59. from backend.app.services.virtual_printer import VIRTUAL_PRINTER_MODELS
  60. from backend.app.services.virtual_printer.manager import DEFAULT_VIRTUAL_PRINTER_MODEL, _get_serial_for_model
  61. model_code = vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL
  62. serial = _get_serial_for_model(model_code, vp.serial_suffix)
  63. return {
  64. "id": vp.id,
  65. "name": vp.name,
  66. "enabled": vp.enabled,
  67. "mode": vp.mode,
  68. "model": model_code,
  69. "model_name": VIRTUAL_PRINTER_MODELS.get(model_code, model_code),
  70. "access_code_set": bool(vp.access_code),
  71. "serial": serial,
  72. "target_printer_id": vp.target_printer_id,
  73. "auto_dispatch": vp.auto_dispatch,
  74. "bind_ip": vp.bind_ip,
  75. "remote_interface_ip": vp.remote_interface_ip,
  76. "tailscale_disabled": vp.tailscale_disabled,
  77. "position": vp.position,
  78. "status": status or {"running": False, "pending_files": 0},
  79. }
  80. @router.get("")
  81. async def list_virtual_printers(
  82. db: AsyncSession = Depends(get_db),
  83. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  84. ):
  85. """List all virtual printers with status."""
  86. from backend.app.models.virtual_printer import VirtualPrinter
  87. from backend.app.services.virtual_printer import VIRTUAL_PRINTER_MODELS, virtual_printer_manager
  88. result = await db.execute(select(VirtualPrinter).order_by(VirtualPrinter.position, VirtualPrinter.id))
  89. vps = result.scalars().all()
  90. printers = []
  91. for vp in vps:
  92. instance = virtual_printer_manager.get_instance(vp.id)
  93. status = instance.get_status() if instance else {"running": False, "pending_files": 0}
  94. printers.append(_vp_to_dict(vp, status))
  95. return {
  96. "printers": printers,
  97. "models": VIRTUAL_PRINTER_MODELS,
  98. }
  99. @router.post("")
  100. async def create_virtual_printer(
  101. body: VirtualPrinterCreate,
  102. db: AsyncSession = Depends(get_db),
  103. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  104. ):
  105. """Create a new virtual printer."""
  106. from backend.app.models.virtual_printer import VirtualPrinter
  107. from backend.app.services.virtual_printer import VIRTUAL_PRINTER_MODELS, virtual_printer_manager
  108. from backend.app.services.virtual_printer.manager import DEFAULT_VIRTUAL_PRINTER_MODEL
  109. # Validate mode
  110. if body.mode not in ("immediate", "review", "print_queue", "proxy"):
  111. return JSONResponse(status_code=400, content={"detail": "Invalid mode"})
  112. # Validate model
  113. if body.model and body.model not in VIRTUAL_PRINTER_MODELS:
  114. return JSONResponse(
  115. status_code=400,
  116. content={"detail": f"Invalid model. Must be one of: {', '.join(VIRTUAL_PRINTER_MODELS.keys())}"},
  117. )
  118. # Validate access code length
  119. if body.access_code and len(body.access_code) != 8:
  120. return JSONResponse(status_code=400, content={"detail": "Access code must be exactly 8 characters"})
  121. # Validation when enabling
  122. if body.enabled:
  123. if not body.bind_ip:
  124. return JSONResponse(status_code=400, content={"detail": "Bind IP is required when enabling"})
  125. if body.mode == "proxy":
  126. if not body.target_printer_id:
  127. return JSONResponse(status_code=400, content={"detail": "Target printer is required for proxy mode"})
  128. else:
  129. if not body.access_code:
  130. return JSONResponse(status_code=400, content={"detail": "Access code is required when enabling"})
  131. # Validate proxy target printer exists
  132. target_printer = None
  133. if body.target_printer_id:
  134. from backend.app.models.printer import Printer
  135. result = await db.execute(select(Printer).where(Printer.id == body.target_printer_id))
  136. target_printer = result.scalar_one_or_none()
  137. if not target_printer:
  138. return JSONResponse(
  139. status_code=400, content={"detail": f"Printer with ID {body.target_printer_id} not found"}
  140. )
  141. # Validate bind_ip uniqueness (against all enabled VPs)
  142. if body.bind_ip:
  143. result = await db.execute(
  144. select(VirtualPrinter).where(
  145. VirtualPrinter.bind_ip == body.bind_ip,
  146. VirtualPrinter.enabled == True, # noqa: E712
  147. )
  148. )
  149. if result.scalar_one_or_none():
  150. return JSONResponse(status_code=400, content={"detail": f"Bind IP {body.bind_ip} is already in use"})
  151. # Generate next serial suffix
  152. result = await db.execute(select(VirtualPrinter.serial_suffix).order_by(VirtualPrinter.id.desc()))
  153. last_suffix = result.scalar()
  154. if last_suffix:
  155. try:
  156. next_num = int(last_suffix) + 1
  157. new_suffix = str(next_num).zfill(9)
  158. except ValueError:
  159. new_suffix = "391800002"
  160. else:
  161. new_suffix = "391800001"
  162. # Get next position
  163. result = await db.execute(select(VirtualPrinter.position).order_by(VirtualPrinter.position.desc()))
  164. last_pos = result.scalar()
  165. next_pos = (last_pos or 0) + 1
  166. vp = VirtualPrinter(
  167. name=body.name,
  168. enabled=body.enabled,
  169. mode=body.mode,
  170. model=body.model
  171. or _resolve_printer_model(target_printer.model if target_printer and body.mode == "proxy" else None)
  172. or DEFAULT_VIRTUAL_PRINTER_MODEL,
  173. access_code=body.access_code,
  174. target_printer_id=body.target_printer_id,
  175. auto_dispatch=body.auto_dispatch,
  176. bind_ip=body.bind_ip,
  177. remote_interface_ip=body.remote_interface_ip,
  178. serial_suffix=new_suffix,
  179. position=next_pos,
  180. )
  181. db.add(vp)
  182. await db.commit()
  183. await db.refresh(vp)
  184. logger.info("Created virtual printer: %s (id=%d)", vp.name, vp.id)
  185. # Sync services if enabled
  186. if body.enabled:
  187. try:
  188. await virtual_printer_manager.sync_from_db()
  189. except Exception as e:
  190. logger.error("Failed to start virtual printer after create: %s", e)
  191. return _vp_to_dict(vp)
  192. @router.get("/tailscale-status", response_model=TailscaleStatusResponse)
  193. async def get_tailscale_status(
  194. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  195. ) -> TailscaleStatusResponse:
  196. """Return current Tailscale availability and machine identity.
  197. Used by the frontend to indicate whether virtual printer TLS is backed
  198. by a trusted Let's Encrypt certificate or a self-signed CA.
  199. """
  200. status = await tailscale_service.get_status()
  201. return TailscaleStatusResponse(
  202. available=status.available,
  203. fqdn=status.fqdn,
  204. hostname=status.hostname,
  205. tailnet_name=status.tailnet_name,
  206. tailscale_ips=status.tailscale_ips,
  207. error=status.error,
  208. )
  209. @router.get("/{vp_id}")
  210. async def get_virtual_printer(
  211. vp_id: int,
  212. db: AsyncSession = Depends(get_db),
  213. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  214. ):
  215. """Get a single virtual printer with status."""
  216. from backend.app.models.virtual_printer import VirtualPrinter
  217. from backend.app.services.virtual_printer import virtual_printer_manager
  218. result = await db.execute(select(VirtualPrinter).where(VirtualPrinter.id == vp_id))
  219. vp = result.scalar_one_or_none()
  220. if not vp:
  221. return JSONResponse(status_code=404, content={"detail": "Virtual printer not found"})
  222. instance = virtual_printer_manager.get_instance(vp.id)
  223. status = instance.get_status() if instance else {"running": False, "pending_files": 0}
  224. return _vp_to_dict(vp, status)
  225. @router.put("/{vp_id}")
  226. async def update_virtual_printer(
  227. vp_id: int,
  228. body: VirtualPrinterUpdate,
  229. db: AsyncSession = Depends(get_db),
  230. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  231. ):
  232. """Update a virtual printer."""
  233. from backend.app.models.virtual_printer import VirtualPrinter
  234. from backend.app.services.virtual_printer import VIRTUAL_PRINTER_MODELS, virtual_printer_manager
  235. result = await db.execute(select(VirtualPrinter).where(VirtualPrinter.id == vp_id))
  236. vp = result.scalar_one_or_none()
  237. if not vp:
  238. return JSONResponse(status_code=404, content={"detail": "Virtual printer not found"})
  239. logger.debug(
  240. "Update VP %d: body=%s, current state: mode=%s, enabled=%s, access_code_set=%s, bind_ip=%s, target=%s",
  241. vp_id,
  242. body.model_dump(exclude_unset=True),
  243. vp.mode,
  244. vp.enabled,
  245. bool(vp.access_code),
  246. vp.bind_ip,
  247. vp.target_printer_id,
  248. )
  249. # Apply updates
  250. if body.name is not None:
  251. vp.name = body.name
  252. if body.mode is not None:
  253. if body.mode not in ("immediate", "review", "print_queue", "proxy"):
  254. return JSONResponse(status_code=400, content={"detail": "Invalid mode"})
  255. vp.mode = body.mode
  256. if body.model is not None:
  257. if body.model not in VIRTUAL_PRINTER_MODELS:
  258. return JSONResponse(
  259. status_code=400,
  260. content={"detail": f"Invalid model. Must be one of: {', '.join(VIRTUAL_PRINTER_MODELS.keys())}"},
  261. )
  262. vp.model = body.model
  263. if body.access_code is not None:
  264. if body.access_code and len(body.access_code) != 8:
  265. return JSONResponse(status_code=400, content={"detail": "Access code must be exactly 8 characters"})
  266. vp.access_code = body.access_code
  267. if body.target_printer_id is not None:
  268. from backend.app.models.printer import Printer
  269. result = await db.execute(select(Printer).where(Printer.id == body.target_printer_id))
  270. target_printer = result.scalar_one_or_none()
  271. if not target_printer:
  272. return JSONResponse(
  273. status_code=400, content={"detail": f"Printer with ID {body.target_printer_id} not found"}
  274. )
  275. vp.target_printer_id = body.target_printer_id
  276. # Auto-inherit model from target printer in proxy mode (unless user explicitly set model)
  277. if body.model is None and vp.mode == "proxy" and target_printer.model:
  278. vp.model = _resolve_printer_model(target_printer.model) or target_printer.model
  279. if body.auto_dispatch is not None:
  280. vp.auto_dispatch = body.auto_dispatch
  281. if body.bind_ip is not None:
  282. vp.bind_ip = body.bind_ip
  283. if body.remote_interface_ip is not None:
  284. vp.remote_interface_ip = body.remote_interface_ip
  285. if body.tailscale_disabled is not None:
  286. vp.tailscale_disabled = body.tailscale_disabled
  287. # Auto-inherit model when switching to proxy mode with existing target printer
  288. if body.mode == "proxy" and body.model is None and body.target_printer_id is None and vp.target_printer_id:
  289. from backend.app.models.printer import Printer as PrinterModel
  290. result = await db.execute(select(PrinterModel).where(PrinterModel.id == vp.target_printer_id))
  291. existing_target = result.scalar_one_or_none()
  292. if existing_target and existing_target.model:
  293. vp.model = _resolve_printer_model(existing_target.model) or existing_target.model
  294. # Determine final enabled state
  295. explicitly_enabling = body.enabled is True
  296. new_enabled = body.enabled if body.enabled is not None else vp.enabled
  297. effective_mode = vp.mode
  298. if explicitly_enabling:
  299. # User is explicitly toggling on — enforce all requirements
  300. if not vp.bind_ip:
  301. logger.warning("Update VP %d rejected: no bind_ip", vp_id)
  302. return JSONResponse(status_code=400, content={"detail": "Bind IP is required when enabling"})
  303. # Validate bind_ip uniqueness (against all enabled VPs)
  304. existing = await db.execute(
  305. select(VirtualPrinter).where(
  306. VirtualPrinter.bind_ip == vp.bind_ip,
  307. VirtualPrinter.id != vp_id,
  308. VirtualPrinter.enabled == True, # noqa: E712
  309. )
  310. )
  311. conflict = existing.scalar_one_or_none()
  312. if conflict:
  313. logger.warning(
  314. "Update VP %d rejected: bind_ip %s already in use by VP %d (enabled=%s, mode=%s)",
  315. vp_id,
  316. vp.bind_ip,
  317. conflict.id,
  318. conflict.enabled,
  319. conflict.mode,
  320. )
  321. return JSONResponse(
  322. status_code=400,
  323. content={"detail": f"Bind IP {vp.bind_ip} is already in use by '{conflict.name}'"},
  324. )
  325. if effective_mode == "proxy":
  326. if not vp.target_printer_id:
  327. logger.warning("Update VP %d rejected: no target_printer_id for proxy mode", vp_id)
  328. return JSONResponse(status_code=400, content={"detail": "Target printer is required for proxy mode"})
  329. else:
  330. if not vp.access_code:
  331. logger.warning(
  332. "Update VP %d rejected: no access_code for non-proxy enable (mode=%s)", vp_id, effective_mode
  333. )
  334. return JSONResponse(status_code=400, content={"detail": "Access code is required when enabling"})
  335. elif new_enabled and body.enabled is None:
  336. # VP is already enabled and user is changing other fields —
  337. # auto-disable if new state doesn't meet requirements
  338. if not vp.bind_ip:
  339. new_enabled = False
  340. elif effective_mode == "proxy":
  341. if not vp.target_printer_id:
  342. new_enabled = False
  343. else:
  344. if not vp.access_code:
  345. new_enabled = False
  346. vp.enabled = new_enabled
  347. await db.commit()
  348. await db.refresh(vp)
  349. logger.info("Updated virtual printer: %s (id=%d)", vp.name, vp.id)
  350. # Sync services
  351. try:
  352. await virtual_printer_manager.sync_from_db()
  353. except Exception as e:
  354. logger.error("Failed to sync virtual printers after update: %s", e)
  355. instance = virtual_printer_manager.get_instance(vp.id)
  356. status = instance.get_status() if instance else {"running": False, "pending_files": 0}
  357. return _vp_to_dict(vp, status)
  358. @router.delete("/{vp_id}")
  359. async def delete_virtual_printer(
  360. vp_id: int,
  361. db: AsyncSession = Depends(get_db),
  362. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  363. ):
  364. """Delete a virtual printer."""
  365. from sqlalchemy import delete as sql_delete
  366. from backend.app.models.virtual_printer import VirtualPrinter
  367. from backend.app.services.virtual_printer import virtual_printer_manager
  368. result = await db.execute(select(VirtualPrinter).where(VirtualPrinter.id == vp_id))
  369. vp = result.scalar_one_or_none()
  370. if not vp:
  371. return JSONResponse(status_code=404, content={"detail": "Virtual printer not found"})
  372. vp_name = vp.name
  373. # Stop instance if running
  374. await virtual_printer_manager.remove_instance(vp_id)
  375. # Delete from DB
  376. await db.execute(sql_delete(VirtualPrinter).where(VirtualPrinter.id == vp_id))
  377. await db.commit()
  378. logger.info("Deleted virtual printer: %s (id=%d)", vp_name, vp_id)
  379. # Resync remaining services
  380. try:
  381. await virtual_printer_manager.sync_from_db()
  382. except Exception as e:
  383. logger.error("Failed to sync virtual printers after delete: %s", e)
  384. return {"detail": "Deleted", "id": vp_id}