virtual_printers.py 14 KB

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