webhook.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. import logging
  2. from fastapi import APIRouter, Depends, HTTPException
  3. from pydantic import BaseModel
  4. from sqlalchemy import select
  5. from sqlalchemy.ext.asyncio import AsyncSession
  6. from backend.app.api.routes.print_queue import _assert_can_queue_archive
  7. from backend.app.core.auth import (
  8. ApiKeyActor,
  9. api_key_printer_scope,
  10. check_webhook_permission,
  11. ensure_api_key_printer_access,
  12. get_api_key,
  13. is_auth_enabled,
  14. queue_review_required_for,
  15. resolve_apikey_owner,
  16. )
  17. from backend.app.core.database import get_db
  18. from backend.app.models.api_key import APIKey
  19. from backend.app.models.archive import PrintArchive
  20. from backend.app.models.print_queue import PrintQueueItem
  21. from backend.app.models.printer import Printer
  22. from backend.app.schemas.printer import HMSErrorResponse, hms_error_responses
  23. from backend.app.services.print_confirmation import confirm_outcome_for_new_queue_item
  24. from backend.app.services.print_control import stop_print_by_user
  25. from backend.app.services.printer_manager import printer_manager
  26. from backend.app.services.queue_position import next_queue_position
  27. logger = logging.getLogger(__name__)
  28. router = APIRouter(prefix="/webhook", tags=["webhook"])
  29. # Request schemas
  30. class QueueAddRequest(BaseModel):
  31. archive_id: int
  32. printer_id: int
  33. project_id: int | None = None
  34. scheduled_time: str | None = None # ISO format datetime
  35. require_previous_success: bool = False
  36. auto_off_after: bool = False
  37. class QueueAddResponse(BaseModel):
  38. id: int
  39. archive_id: int
  40. printer_id: int
  41. position: int
  42. status: str
  43. message: str
  44. class PrinterStatusResponse(BaseModel):
  45. id: int
  46. name: str
  47. # The printer's own serial, so a client can tell printers apart by what
  48. # they report rather than by Bambuddy's row id (#2919).
  49. serial_number: str
  50. connected: bool
  51. state: str | None
  52. current_print: str | None
  53. progress: float | None
  54. # Minutes, as the printer reports it. Kept for existing clients;
  55. # remaining_seconds is the same estimate in seconds, the unit the
  56. # notification pipeline uses (#2919).
  57. remaining_time: int | None
  58. remaining_seconds: int | None = None
  59. layer_num: int | None = None
  60. total_layers: int | None = None
  61. # Bambu's id for the running job. A new value marks a new print, even when
  62. # two prints of the same file run back to back between two polls. None
  63. # when the job has no id: Bambu reports "0" or "" for local prints (for
  64. # example one started on the printer), the same reading main.py uses.
  65. subtask_id: str | None = None
  66. # Live HMS faults, in the same shape as GET /printers/{id}/status. They
  67. # tell a filament runout apart from someone pressing pause.
  68. hms_errors: list[HMSErrorResponse] = []
  69. class QueueStatusResponse(BaseModel):
  70. printer_id: int
  71. printer_name: str
  72. pending: int
  73. printing: int
  74. items: list[dict]
  75. def _job_id(subtask_id) -> str | None:
  76. """The printer's job id as text, or None when the job has none.
  77. Stored as the printer sent it, so coerce: a numeric id would fail
  78. validation and turn a status poll into a 500.
  79. """
  80. if subtask_id is None:
  81. return None
  82. value = str(subtask_id).strip()
  83. return None if value in ("", "0") else value
  84. # Webhook endpoints
  85. @router.post("/queue/add", response_model=QueueAddResponse)
  86. async def webhook_add_to_queue(
  87. data: QueueAddRequest,
  88. api_key: APIKey = Depends(get_api_key),
  89. db: AsyncSession = Depends(get_db),
  90. ):
  91. """Add a print to the queue via webhook.
  92. Requires 'can_queue' permission.
  93. """
  94. await check_webhook_permission(db, api_key, "queue")
  95. await ensure_api_key_printer_access(db, api_key, data.printer_id)
  96. # Verify archive exists and passes the same source gate as POST /queue/,
  97. # with the key acting for its owner within its printers.
  98. result = await db.execute(select(PrintArchive).where(PrintArchive.id == data.archive_id))
  99. archive = result.scalar_one_or_none()
  100. if not archive:
  101. raise HTTPException(status_code=404, detail="Archive not found")
  102. # Auth off: no owner to act for, as on POST /queue/; the key's printers still apply.
  103. actor = ApiKeyActor(api_key, await resolve_apikey_owner(db, api_key)) if await is_auth_enabled(db) else None
  104. _assert_can_queue_archive(archive, actor, await api_key_printer_scope(db, api_key))
  105. # Verify printer exists
  106. result = await db.execute(select(Printer).where(Printer.id == data.printer_id))
  107. printer = result.scalar_one_or_none()
  108. if not printer:
  109. raise HTTPException(status_code=404, detail="Printer not found")
  110. # Append to the end of the queue: positions are one sequence across all
  111. # pending items, not one per printer (#3200).
  112. next_position = await next_queue_position(db)
  113. # Parse scheduled time if provided
  114. scheduled_time = None
  115. if data.scheduled_time:
  116. from datetime import datetime
  117. try:
  118. scheduled_time = datetime.fromisoformat(data.scheduled_time.replace("Z", "+00:00"))
  119. except ValueError:
  120. raise HTTPException(status_code=400, detail="Invalid scheduled_time format")
  121. # Create queue item
  122. queue_item = PrintQueueItem(
  123. printer_id=data.printer_id,
  124. archive_id=data.archive_id,
  125. project_id=data.project_id,
  126. position=next_position,
  127. scheduled_time=scheduled_time,
  128. require_previous_success=data.require_previous_success,
  129. auto_off_after=data.auto_off_after,
  130. # No dialog to pick this per job, so the install-wide default decides
  131. # whether the finished print asks for a verdict (#1898).
  132. confirm_outcome=await confirm_outcome_for_new_queue_item(db),
  133. # Attribute to the key's owner so the item shows up under `queue:read_own`
  134. # for the person whose key it is. Legacy keys predating per-user ownership
  135. # have no `user_id`, and those rows stay ownerless.
  136. created_by_id=api_key.user_id,
  137. # Waits for someone to start it unless the owner may print without review (#1620)
  138. manual_start=await is_auth_enabled(db) and queue_review_required_for(await resolve_apikey_owner(db, api_key)),
  139. )
  140. db.add(queue_item)
  141. await db.flush()
  142. await db.refresh(queue_item)
  143. return QueueAddResponse(
  144. id=queue_item.id,
  145. archive_id=queue_item.archive_id,
  146. printer_id=queue_item.printer_id,
  147. position=queue_item.position,
  148. status=queue_item.status,
  149. message=f"Added to queue at position {queue_item.position}",
  150. )
  151. @router.post("/printer/{printer_id}/start")
  152. async def webhook_start_print(
  153. printer_id: int,
  154. api_key: APIKey = Depends(get_api_key),
  155. db: AsyncSession = Depends(get_db),
  156. ):
  157. """Trigger the next manual-start queue item on a printer.
  158. Mirrors `POST /print-queue/{item_id}/start`: clears `manual_start` on
  159. the next pending item so the scheduler picks it up — which handles
  160. FTP upload, AMS mapping, and all print options (timelapse,
  161. bed_levelling, etc.) correctly via the queue's stored fields. The
  162. previous implementation called `printer_manager.start_print()`
  163. directly with `archive_id` as the filename arg and no print options,
  164. bypassing the upload step entirely and discarding the user's
  165. workflow choices — it 500'd before ever reaching the printer.
  166. Requires 'can_control_printer' permission.
  167. """
  168. await check_webhook_permission(db, api_key, "control_printer")
  169. await ensure_api_key_printer_access(db, api_key, printer_id)
  170. # Get printer
  171. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  172. printer = result.scalar_one_or_none()
  173. if not printer:
  174. raise HTTPException(status_code=404, detail="Printer not found")
  175. # Get next pending queue item
  176. result = await db.execute(
  177. select(PrintQueueItem)
  178. .where(
  179. PrintQueueItem.printer_id == printer_id,
  180. PrintQueueItem.status == "pending",
  181. )
  182. .order_by(PrintQueueItem.position)
  183. .limit(1)
  184. )
  185. queue_item = result.scalar_one_or_none()
  186. if not queue_item:
  187. raise HTTPException(status_code=404, detail="No pending prints in queue")
  188. # Starting a waiting job is a review decision (#1620): a key whose owner
  189. # needs review for their own jobs can't make one for anybody's
  190. if (
  191. queue_item.manual_start
  192. and await is_auth_enabled(db)
  193. and queue_review_required_for(await resolve_apikey_owner(db, api_key))
  194. ):
  195. raise HTTPException(
  196. status_code=403,
  197. detail="The next job waits for review: someone who can manage all queue jobs has to start it",
  198. )
  199. # Clear manual_start so the scheduler will dispatch. If the item was
  200. # already auto-dispatchable this is a no-op; the scheduler will still
  201. # pick it up on its next tick.
  202. queue_item.manual_start = False
  203. await db.commit()
  204. await db.refresh(queue_item)
  205. logger.info("Webhook started queue item %s on printer %s", queue_item.id, printer_id)
  206. return {"message": "Print started", "queue_item_id": queue_item.id}
  207. # States in which a print can be stopped, as with the Stop button on the
  208. # printer card: printing or paused.
  209. _STOPPABLE_STATES = ("RUNNING", "PAUSE")
  210. def _stop_current_print(printer_id: int) -> None:
  211. """Stop the print on the user's behalf (cancel and stop are the same command)."""
  212. try:
  213. sent = stop_print_by_user(printer_id)
  214. except Exception as e:
  215. logger.error("Failed to stop print on printer %s: %s", printer_id, e)
  216. raise HTTPException(status_code=500, detail=str(e))
  217. if not sent:
  218. raise HTTPException(status_code=503, detail="Printer not connected")
  219. @router.post("/printer/{printer_id}/stop")
  220. async def webhook_stop_print(
  221. printer_id: int,
  222. api_key: APIKey = Depends(get_api_key),
  223. db: AsyncSession = Depends(get_db),
  224. ):
  225. """Stop the current print on a printer.
  226. Requires 'can_control_printer' permission.
  227. """
  228. await check_webhook_permission(db, api_key, "control_printer")
  229. await ensure_api_key_printer_access(db, api_key, printer_id)
  230. status = printer_manager.get_status(printer_id)
  231. # `printer_manager.get_status(...)` returns a ``PrinterState`` dataclass
  232. # (see backend/app/services/bambu_mqtt.py), not a dict — `.get(...)` on it
  233. # raises AttributeError and surfaces as a generic 500 (#1584).
  234. if not status or not status.connected:
  235. raise HTTPException(status_code=503, detail="Printer not connected")
  236. if status.state not in _STOPPABLE_STATES:
  237. raise HTTPException(status_code=409, detail="No print in progress")
  238. _stop_current_print(printer_id)
  239. return {"message": "Print stopped"}
  240. @router.post("/printer/{printer_id}/cancel")
  241. async def webhook_cancel_print(
  242. printer_id: int,
  243. api_key: APIKey = Depends(get_api_key),
  244. db: AsyncSession = Depends(get_db),
  245. ):
  246. """Cancel the current print on a printer.
  247. Requires 'can_control_printer' permission.
  248. """
  249. await check_webhook_permission(db, api_key, "control_printer")
  250. await ensure_api_key_printer_access(db, api_key, printer_id)
  251. status = printer_manager.get_status(printer_id)
  252. # Same dataclass-not-dict shape as stop_print above (#1584).
  253. if not status or not status.connected:
  254. raise HTTPException(status_code=503, detail="Printer not connected")
  255. if status.state not in _STOPPABLE_STATES:
  256. raise HTTPException(status_code=409, detail="No print to cancel")
  257. _stop_current_print(printer_id)
  258. return {"message": "Print cancelled"}
  259. @router.get("/printer/{printer_id}/status", response_model=PrinterStatusResponse)
  260. async def webhook_get_printer_status(
  261. printer_id: int,
  262. api_key: APIKey = Depends(get_api_key),
  263. db: AsyncSession = Depends(get_db),
  264. ):
  265. """Get status of a printer.
  266. Requires 'can_read_status' permission.
  267. """
  268. await check_webhook_permission(db, api_key, "read_status")
  269. await ensure_api_key_printer_access(db, api_key, printer_id)
  270. # Get printer
  271. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  272. printer = result.scalar_one_or_none()
  273. if not printer:
  274. raise HTTPException(status_code=404, detail="Printer not found")
  275. status = printer_manager.get_status(printer_id)
  276. # `printer_manager.get_status(...)` returns a ``PrinterState`` dataclass —
  277. # attribute access, not dict lookup. The previous `.get(...)` calls raised
  278. # AttributeError and surfaced as a generic 500 for any printer that
  279. # actually had a status row (#1584).
  280. if status is None:
  281. return PrinterStatusResponse(
  282. id=printer.id,
  283. name=printer.name,
  284. serial_number=printer.serial_number,
  285. connected=False,
  286. state=None,
  287. current_print=None,
  288. progress=None,
  289. remaining_time=None,
  290. )
  291. return PrinterStatusResponse(
  292. id=printer.id,
  293. name=printer.name,
  294. serial_number=printer.serial_number,
  295. connected=status.connected,
  296. state=status.state,
  297. current_print=status.current_print,
  298. progress=status.progress,
  299. remaining_time=status.remaining_time,
  300. remaining_seconds=status.remaining_time * 60 if status.remaining_time is not None else None,
  301. layer_num=status.layer_num,
  302. total_layers=status.total_layers,
  303. subtask_id=_job_id(status.subtask_id),
  304. hms_errors=hms_error_responses(status.hms_errors),
  305. )
  306. @router.get("/queue", response_model=list[QueueStatusResponse])
  307. async def webhook_get_queue_status(
  308. printer_id: int | None = None,
  309. api_key: APIKey = Depends(get_api_key),
  310. db: AsyncSession = Depends(get_db),
  311. ):
  312. """Get queue status for all printers or a specific printer.
  313. Requires 'can_read_status' permission.
  314. """
  315. await check_webhook_permission(db, api_key, "read_status")
  316. # Get printers
  317. if printer_id:
  318. await ensure_api_key_printer_access(db, api_key, printer_id)
  319. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  320. printers = result.scalars().all()
  321. else:
  322. result = await db.execute(select(Printer))
  323. printers = result.scalars().all()
  324. # Only the printers the key (and its owner) may reach
  325. scope = await api_key_printer_scope(db, api_key)
  326. printers = [p for p in printers if scope.allows(p.id)]
  327. response = []
  328. for printer in printers:
  329. # Get queue items
  330. result = await db.execute(
  331. select(PrintQueueItem)
  332. .where(
  333. PrintQueueItem.printer_id == printer.id,
  334. PrintQueueItem.status.in_(["pending", "printing"]),
  335. )
  336. .order_by(PrintQueueItem.position)
  337. )
  338. items = result.scalars().all()
  339. pending_count = sum(1 for i in items if i.status == "pending")
  340. printing_count = sum(1 for i in items if i.status == "printing")
  341. response.append(
  342. QueueStatusResponse(
  343. printer_id=printer.id,
  344. printer_name=printer.name,
  345. pending=pending_count,
  346. printing=printing_count,
  347. items=[
  348. {
  349. "id": item.id,
  350. "archive_id": item.archive_id,
  351. "position": item.position,
  352. "status": item.status,
  353. }
  354. for item in items
  355. ],
  356. )
  357. )
  358. return response