virtual_printers.py 15 KB

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