printer.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. from datetime import datetime
  2. from pydantic import BaseModel, Field, field_validator, model_validator
  3. from backend.app.utils.printer_models import supports_nozzle_flow_type
  4. class PrinterBase(BaseModel):
  5. name: str = Field(..., min_length=1, max_length=100)
  6. serial_number: str = Field(..., min_length=1, max_length=50)
  7. @field_validator("serial_number")
  8. @classmethod
  9. def _normalize_serial_number(cls, v: str) -> str:
  10. """Uppercase and trim the serial number.
  11. Bambu serial numbers are uppercase alphanumeric, and the MQTT report
  12. topic ``device/<serial>/report`` is case-sensitive. A serial entered
  13. in the wrong case (or with stray whitespace) connects and subscribes
  14. without error but never receives a message — the printer publishes to
  15. the correctly-cased topic, so every status field stays unknown (#1465).
  16. Normalising on input makes the subscribed topic always match.
  17. """
  18. normalized = v.strip().upper()
  19. if not normalized:
  20. raise ValueError("serial_number must not be blank")
  21. return normalized
  22. ip_address: str = Field(
  23. ...,
  24. max_length=253,
  25. pattern=r"^(\d{1,3}(\.\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*)$",
  26. )
  27. model: str | None = None
  28. location: str | None = None # Group/location name
  29. auto_archive: bool = True
  30. external_camera_url: str | None = None
  31. external_camera_type: str | None = None # "mjpeg", "rtsp", "snapshot", "usb"
  32. external_camera_enabled: bool = False
  33. external_camera_snapshot_url: str | None = None # Optional single-frame override; #1177
  34. camera_rotation: int = 0 # 0, 90, 180, 270 degrees
  35. class PrinterCreate(PrinterBase):
  36. # access_code lives on the input shapes only — never on the default
  37. # PrinterResponse. Direct exposure on PRINTERS_READ would let a Viewer
  38. # connect to the printer's MQTT and bypass Bambuddy's RBAC.
  39. access_code: str = Field(..., min_length=1, max_length=20)
  40. class PlateDetectionROI(BaseModel):
  41. """Region of interest for plate detection (percentages 0.0-1.0)."""
  42. x: float = Field(..., ge=0.0, le=1.0) # X start %
  43. y: float = Field(..., ge=0.0, le=1.0) # Y start %
  44. w: float = Field(..., ge=0.0, le=1.0) # Width %
  45. h: float = Field(..., ge=0.0, le=1.0) # Height %
  46. class PrinterUpdate(BaseModel):
  47. name: str | None = None
  48. ip_address: str | None = Field(
  49. default=None,
  50. max_length=253,
  51. pattern=r"^(\d{1,3}(\.\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*)$",
  52. )
  53. access_code: str | None = None
  54. model: str | None = None
  55. location: str | None = None
  56. is_active: bool | None = None
  57. auto_archive: bool | None = None
  58. print_hours_offset: float | None = None
  59. external_camera_url: str | None = None
  60. external_camera_type: str | None = None
  61. external_camera_enabled: bool | None = None
  62. external_camera_snapshot_url: str | None = None # #1177
  63. camera_rotation: int | None = None # 0, 90, 180, 270 degrees
  64. plate_detection_enabled: bool | None = None
  65. plate_detection_roi: PlateDetectionROI | None = None
  66. class PrinterResponse(PrinterBase):
  67. id: int
  68. is_active: bool
  69. nozzle_count: int = 1 # 1 or 2, auto-detected from MQTT
  70. # Whether the model is sold with both Standard and High Flow nozzles, so a
  71. # K-profile's flow type is a real choice rather than a meaningless field.
  72. # Derived from the model, not from nozzle_count — see
  73. # printer_models.supports_nozzle_flow_type.
  74. supports_nozzle_flow_type: bool = True
  75. print_hours_offset: float = 0.0
  76. external_camera_url: str | None = None
  77. external_camera_type: str | None = None
  78. external_camera_enabled: bool = False
  79. external_camera_snapshot_url: str | None = None # #1177
  80. camera_rotation: int = 0 # 0, 90, 180, 270 degrees
  81. plate_detection_enabled: bool = False
  82. plate_detection_roi: PlateDetectionROI | None = None
  83. created_at: datetime
  84. updated_at: datetime
  85. class Config:
  86. from_attributes = True
  87. @classmethod
  88. def from_orm_with_roi(cls, printer) -> "PrinterResponse":
  89. """Create response from ORM model, converting ROI fields to nested object."""
  90. data = {
  91. "id": printer.id,
  92. "name": printer.name,
  93. "serial_number": printer.serial_number,
  94. "ip_address": printer.ip_address,
  95. "model": printer.model,
  96. "location": printer.location,
  97. "auto_archive": printer.auto_archive,
  98. "external_camera_url": printer.external_camera_url,
  99. "external_camera_type": printer.external_camera_type,
  100. "external_camera_enabled": printer.external_camera_enabled,
  101. "external_camera_snapshot_url": printer.external_camera_snapshot_url,
  102. "camera_rotation": printer.camera_rotation,
  103. "is_active": printer.is_active,
  104. "nozzle_count": printer.nozzle_count,
  105. "supports_nozzle_flow_type": supports_nozzle_flow_type(printer.model),
  106. "print_hours_offset": printer.print_hours_offset,
  107. "plate_detection_enabled": printer.plate_detection_enabled,
  108. "created_at": printer.created_at,
  109. "updated_at": printer.updated_at,
  110. }
  111. # Build ROI object if any ROI field is set
  112. if any(
  113. [
  114. printer.plate_detection_roi_x is not None,
  115. printer.plate_detection_roi_y is not None,
  116. printer.plate_detection_roi_w is not None,
  117. printer.plate_detection_roi_h is not None,
  118. ]
  119. ):
  120. data["plate_detection_roi"] = PlateDetectionROI(
  121. x=printer.plate_detection_roi_x or 0.15,
  122. y=printer.plate_detection_roi_y or 0.35,
  123. w=printer.plate_detection_roi_w or 0.70,
  124. h=printer.plate_detection_roi_h or 0.55,
  125. )
  126. return cls(**data)
  127. class PrinterResponseWithSecret(PrinterResponse):
  128. """PrinterResponse + access_code. Returned ONLY to callers with
  129. PRINTERS_UPDATE (Admin / Operator JWTs, or single-trust auth-disabled mode).
  130. Viewers and API keys never receive this shape — they get the bare
  131. PrinterResponse without access_code, since holding the access_code lets
  132. the caller talk to the printer's MQTT directly and bypass Bambuddy's RBAC.
  133. """
  134. access_code: str
  135. class HMSErrorResponse(BaseModel):
  136. code: str
  137. attr: int = 0 # Attribute value for constructing wiki URL
  138. module: int
  139. severity: int # 1=fatal, 2=serious, 3=common, 4=info
  140. actions: list[str] = [] # List of user-facing action keys (e.g. "CHECK_FILAMENT")
  141. job_id: str | None = None # Optional job ID for actions that require it (e.g. "CHECK_ASSISTANT")
  142. # Canonical hex identifier the firmware uses to match HMS-related commands.
  143. # 16 chars for `hms[]`-array faults (full 64-bit attr+code), 8 chars for
  144. # `print_error` faults. The frontend echoes this back as
  145. # HmsActionBody.print_error so we send the firmware-recognised key, not the
  146. # truncated short_code that historically caused silent command rejection
  147. # (#1830, H2D wrong-plate verification).
  148. full_code: str = ""
  149. # The bundled catalogue's sentence for this fault, so a client does not have
  150. # to carry its own copy of the same table to tell a user why a print halted
  151. # (#2926). English only and not localized — the catalogue ships one language.
  152. # None when the catalogue does not cover the code, which is common for
  153. # `hms[]`-array faults: those resolve through a lossy collapse of their
  154. # 16-char identifier and many land on no key at all (#2728). A client should
  155. # treat null as "no text available", never as "no fault" — `full_code` is
  156. # what identifies the fault, and it is always present.
  157. description: str | None = None
  158. class AMSTray(BaseModel):
  159. id: int
  160. tray_color: str | None = None
  161. tray_type: str | None = None
  162. tray_sub_brands: str | None = None # Full name like "PLA Basic", "PETG HF"
  163. tray_id_name: str | None = None # Bambu filament ID like "A00-Y2" (can decode to color)
  164. tray_info_idx: str | None = None # Filament preset ID like "GFA00"
  165. remain: int = 0
  166. k: float | None = None # Pressure advance value (from tray or K-profile lookup)
  167. cali_idx: int | None = None # Calibration index for K-profile lookup
  168. tag_uid: str | None = None # RFID tag UID (any tag)
  169. tray_uuid: str | None = None # Bambu Lab spool UUID (32-char hex)
  170. nozzle_temp_min: int | None = None # Min nozzle temperature
  171. nozzle_temp_max: int | None = None # Max nozzle temperature
  172. drying_temp: int | None = None # RFID-recommended drying temp
  173. drying_time: int | None = None # RFID-recommended drying time (hours)
  174. state: int | None = None # AMS tray state: 9=empty, 10=spool present not loaded, 11=loaded
  175. # Firmware's authoritative "spool physically present" bit (from tray_exist_bits).
  176. # True for a non-RFID spool the firmware can't identify — the UI shows "?" rather
  177. # than "Empty" (#2527). None when the bitmask was unavailable (→ state-based fallback).
  178. exists: bool | None = None
  179. class AMSUnit(BaseModel):
  180. id: int
  181. humidity: int | None = None
  182. temp: float | None = None
  183. is_ams_ht: bool = False # True for AMS-HT (single spool), False for regular AMS (4 spools)
  184. tray: list[AMSTray] = []
  185. serial_number: str = "" # AMS unit serial number (sn from MQTT)
  186. sw_ver: str = "" # AMS firmware version (from get_version info.module)
  187. dry_time: int = 0 # Minutes remaining (0 = not drying, >0 = drying active)
  188. dry_status: int = 0 # 0=Off, 1=Checking, 2=Drying, 3=Cooling, 4=Stopping, 5=Error
  189. dry_sub_status: int = 0 # 0=Off, 1=Heating, 2=Dehumidify
  190. dry_sf_reason: list[int] = [] # Cannot-dry reasons from firmware (see CannotDryReason)
  191. dry_target_temp: int | None = None # Active-cycle target °C (Bambu doesn't echo this)
  192. dry_filament: str | None = None # Active-cycle filament name we sent
  193. module_type: str = "" # "ams", "n3f", "n3s"
  194. class NozzleInfoResponse(BaseModel):
  195. nozzle_type: str = "" # "stainless_steel" or "hardened_steel"
  196. nozzle_diameter: str = "" # e.g., "0.4"
  197. class NozzleRackSlot(BaseModel):
  198. """H2C nozzle rack slot (6-position tool-changer dock)."""
  199. id: int = 0
  200. nozzle_type: str = ""
  201. nozzle_diameter: str = ""
  202. wear: int | None = None
  203. stat: int | None = None # Nozzle status (e.g. mounted/docked)
  204. max_temp: int = 0 # Max temperature rating °C (0 = not set)
  205. serial_number: str = "" # Nozzle serial number
  206. filament_color: str = "" # RGBA hex ("00000000" = no filament)
  207. filament_id: str = "" # Bambu filament ID
  208. filament_type: str = "" # Material type (e.g. "PLA", "PETG")
  209. class AmsLabelBody(BaseModel):
  210. label: str = Field(..., min_length=1, max_length=100)
  211. ams_serial: str = Field(default="", max_length=50)
  212. class HmsActionBody(BaseModel):
  213. # Canonical hex identifier (HMSErrorResponse.full_code): 8 chars for
  214. # `print_error`-sourced faults, 16 chars for `hms[]`-array faults whose
  215. # full 64-bit code is the firmware's matching key. Length-bounded to
  216. # those two valid shapes to keep stray input from reaching the dispatcher.
  217. print_error: str = Field(..., min_length=8, max_length=16, pattern=r"^[0-9A-Fa-f]{8}([0-9A-Fa-f]{8})?$")
  218. # One of the HMSAction enum values. Length-capped to keep stray input from
  219. # reaching the dispatcher's `match` statement.
  220. action: str = Field(..., min_length=1, max_length=64)
  221. # The `subtask_id` snapshot from the HMSError that surfaced this dialog.
  222. # Bambu echoes it back in HMS-aware commands. Optional for idle errors.
  223. job_id: str | None = Field(default=None, max_length=64)
  224. class FilaSwitchResponse(BaseModel):
  225. """Filament Track Switch (FTS) state — accessory that mediates AMS-to-extruder routing.
  226. When installed, the AMS info field reports bits 8-11 = 0xE (uninitialized)
  227. because slots are dynamically routed via the FTS rather than tied to a
  228. specific extruder. Frontend uses `installed` to suppress the per-extruder
  229. slot filter in the print modal. See #1162.
  230. """
  231. installed: bool = False
  232. # in[track] = currently loaded slot for that track (-1 = empty)
  233. in_slots: list[int] = []
  234. # out[track] = extruder this track terminates at (0 = right, 1 = left)
  235. out_extruders: list[int] = []
  236. stat: int = 0
  237. info: int = 0
  238. # Whether the switch is set up: every AMS bound to one of its two inlets.
  239. # A load cannot be routed until it is, so the UI blocks on this rather than
  240. # sending a command the firmware will drop.
  241. ready: bool = False
  242. class ExtruderSlotResponse(BaseModel):
  243. """Which AMS slot one hotend is currently fed from.
  244. From ``device.extruder.info[i].snow``. Needed because ``tray_now`` is a
  245. single printer-wide value: on a dual-nozzle machine with both hotends
  246. loaded it names only one of them, so it cannot say which hotend holds a
  247. given slot.
  248. """
  249. # None when the hotend is not fed from any slot.
  250. ams_id: int | None = None
  251. slot_id: int | None = None
  252. has_filament: bool = False
  253. class PrintOptionsResponse(BaseModel):
  254. """AI detection and print options from xcam data."""
  255. # Core AI detectors
  256. spaghetti_detector: bool = False
  257. print_halt: bool = False
  258. halt_print_sensitivity: str = "medium" # Spaghetti sensitivity
  259. first_layer_inspector: bool = False
  260. printing_monitor: bool = False
  261. buildplate_marker_detector: bool = False
  262. allow_skip_parts: bool = False
  263. # Additional AI detectors (decoded from cfg bitmask)
  264. nozzle_clumping_detector: bool = True
  265. nozzle_clumping_sensitivity: str = "medium"
  266. pileup_detector: bool = True
  267. pileup_sensitivity: str = "medium"
  268. airprint_detector: bool = True
  269. airprint_sensitivity: str = "medium"
  270. auto_recovery_step_loss: bool = True
  271. filament_tangle_detect: bool = False
  272. class PrinterStatus(BaseModel):
  273. id: int
  274. name: str
  275. connected: bool
  276. state: str | None = None
  277. current_print: str | None = None
  278. subtask_name: str | None = None
  279. gcode_file: str | None = None
  280. progress: float | None = None
  281. remaining_time: int | None = None
  282. layer_num: int | None = None
  283. total_layers: int | None = None
  284. temperatures: dict | None = None
  285. cover_url: str | None = None
  286. hms_errors: list[HMSErrorResponse] = []
  287. ams: list[AMSUnit] = []
  288. ams_exists: bool = False
  289. vt_tray: list[AMSTray] = [] # Virtual tray / external spool(s)
  290. sdcard: bool = False # SD card inserted
  291. store_to_sdcard: bool = False # Store sent files on SD card
  292. timelapse: bool = False # Timelapse recording active
  293. ipcam: bool = False # Live view enabled
  294. wifi_signal: int | None = None # WiFi signal strength in dBm
  295. wired_network: bool = False # Ethernet connection detected
  296. door_open: bool = False # Enclosure door open (X1/P1S/P2S/H2*)
  297. nozzles: list[NozzleInfoResponse] = [] # Nozzle hardware info (index 0=left/primary, 1=right)
  298. nozzle_rack: list[NozzleRackSlot] = [] # H2C 6-nozzle tool-changer rack
  299. print_options: PrintOptionsResponse | None = None # AI detection and print options
  300. # Calibration stage tracking
  301. stg_cur: int = -1 # Current stage number (-1 = not calibrating)
  302. stg_cur_name: str | None = None # Human-readable current stage name
  303. stg: list[int] = [] # List of stage numbers in calibration sequence
  304. # Air conditioning mode (0=cooling, 1=heating)
  305. airduct_mode: int = 0
  306. # Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  307. speed_level: int = 2
  308. # Chamber light on/off
  309. chamber_light: bool = False
  310. # Active extruder for dual nozzle (0=right, 1=left)
  311. active_extruder: int = 0
  312. # AMS mapping for dual nozzle: which AMS is connected to which nozzle
  313. ams_mapping: list[int] = []
  314. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right, 1=left
  315. ams_extruder_map: dict[str, int] = {}
  316. # Filament Track Switch (FTS) accessory — when installed, AMS reports
  317. # bits 8-11 = 0xE (uninitialized) and routing is dynamic via the FTS. See #1162.
  318. fila_switch: FilaSwitchResponse | None = None
  319. # Per-AMS FTS inlet binding: {ams_id: "A" | "B"}, from AMS info bits 24-27.
  320. # Which of the switch's two inlets each AMS is plumbed into, as set on the
  321. # printer's "Manual AMS Setup" screen. Empty unless an FTS is installed —
  322. # an FTS-bound AMS reaches BOTH nozzles, so it has no entry in
  323. # ams_extruder_map and must not be labelled left or right.
  324. ams_switch_inlet: dict[str, str] = {}
  325. # Which AMS slot each hotend is fed from, keyed by extruder id as a string
  326. # ("0" = right/main, "1" = left/deputy). Empty on printers that do not
  327. # report ``device.extruder.info``.
  328. extruder_slots: dict[str, ExtruderSlotResponse] = {}
  329. # Currently loaded tray (global ID): 254 = external spool, 255 = no filament
  330. tray_now: int = 255
  331. # Runout / filament-replacement guidance (#2587). Populated only while the
  332. # print is PAUSED. Both are globalised tray IDs (ams_id*4+slot, or 128-135 for
  333. # AMS-HT, or 254 for external) so the frontend can highlight them with the same
  334. # logic it uses for tray_now:
  335. # expected_tray = the slot the firmware now expects filament in (from tray_tar).
  336. # None when idle, not paused, or the slot can't be resolved
  337. # (multi-AMS ambiguity) — the UI then says "check the printer".
  338. # previous_tray = the slot loaded before the pause, i.e. the one that ran out
  339. # (from tray_pre). None when unknown.
  340. expected_tray: int | None = None
  341. previous_tray: int | None = None
  342. # AMS status for filament change tracking
  343. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration
  344. ams_status_main: int = 0
  345. # Sub status: specific step within filament change (when main=1)
  346. # Known values: 4=retraction, 6=load verification, 7=purge
  347. ams_status_sub: int = 0
  348. # mc_print_sub_stage - filament change step indicator used by OrcaSlicer/BambuStudio
  349. mc_print_sub_stage: int = 0
  350. # Timestamp of last AMS data update (for RFID refresh detection)
  351. last_ams_update: float = 0.0
  352. # Number of printable objects in current print (for skip objects feature)
  353. printable_objects_count: int = 0
  354. # Fan speeds (0-100 percentage, None if not available for this model)
  355. cooling_fan_speed: int | None = None # Part cooling fan
  356. big_fan1_speed: int | None = None # Auxiliary fan
  357. big_fan2_speed: int | None = None # Chamber/exhaust fan
  358. heatbreak_fan_speed: int | None = None # Hotend heatbreak fan
  359. # Left auxiliary part cooling fan (optional P2S/X2D accessory, airduct part id 10).
  360. # None = not installed / not reported by this model.
  361. left_aux_fan_speed: int | None = None
  362. # Chamber exhaust fan present (P2S/X2D External Exhaust Fan kit; airduct part id 3).
  363. exhaust_fan_present: bool = False
  364. # Firmware version (from info.module[name="ota"].sw_ver)
  365. firmware_version: str | None = None
  366. # Developer LAN mode: True = enabled, False = disabled (MQTT encryption), None = unknown
  367. developer_mode: bool | None = None
  368. # AMS Filament Backup ("auto-switch" to a second spool when one runs out).
  369. # True = ON, False = OFF, None = unknown / unsupported (A1 family — protocol field
  370. # not yet identified). UI treats None as "status unavailable", not as a hard disable.
  371. ams_filament_backup: bool | None = None
  372. # Queue: printer is awaiting the user to acknowledge the build plate is cleared
  373. # after a finished/failed print. Persisted across restarts (#961).
  374. awaiting_plate_clear: bool = False
  375. # AMS drying support
  376. supports_drying: bool = False
  377. # AMS "Print While Drying" — drying mid-print. Verified per Bambu wiki release notes;
  378. # see _DRY_WHILE_PRINTING_MIN_FIRMWARE in printer_manager.py for the matrix.
  379. supports_drying_while_printing: bool = False
  380. # The AMS can dry, but only from the printer's own screen (P1 series, #2533).
  381. # supports_drying is False on these; the UI keeps the control visible but disabled
  382. # and says why, rather than dropping it without explanation.
  383. drying_screen_only: bool = False
  384. # Active chamber heater (responds to M141). True only for H2C/H2D/H2DPro/H2S/X2D.
  385. supports_chamber_heater: bool = False
  386. # Linked archive for the active print (resolved via subtask_id). Frontend uses
  387. # this to fetch plate metadata and show the plate name when the source 3MF is
  388. # multi-plate (#881 follow-up).
  389. current_archive_id: int | None = None
  390. # 1-indexed plate number parsed from gcode_file (e.g. /Metadata/plate_2.gcode).
  391. # Set for every active print regardless of plate count; the frontend decides
  392. # whether to render it based on current_archive_id's is_multi_plate flag.
  393. current_plate_id: int | None = None
  394. class DiagnosticCheck(BaseModel):
  395. """One connection-diagnostic check result.
  396. ``id`` is a stable key (port_mqtt, port_ftps, port_rtsps, network_mode,
  397. subnet, mqtt_auth, developer_mode); the frontend renders the localized
  398. title and fix text from id + status. ``params`` carries interpolation
  399. values (e.g. network mode, IP addresses) for that text.
  400. """
  401. id: str
  402. status: str # "pass" | "fail" | "warn" | "skip"
  403. params: dict = Field(default_factory=dict)
  404. class PrinterDiagnosticResult(BaseModel):
  405. """Result of a printer connection diagnostic run."""
  406. printer_id: int | None = None
  407. ip_address: str
  408. overall: str # "ok" | "warnings" | "problems"
  409. checks: list[DiagnosticCheck]
  410. class DiagnosticRequest(BaseModel):
  411. """Pre-save (Add Printer) connection diagnostic request.
  412. serial_number + access_code are optional: when both are present the
  413. diagnostic also probes MQTT credentials, otherwise only the
  414. network-level checks run.
  415. """
  416. ip_address: str
  417. serial_number: str | None = None
  418. access_code: str | None = None
  419. class PrinterFilesDownloadRequest(BaseModel):
  420. """Printer paths selected for a bulk download."""
  421. paths: list[str] = Field(..., max_length=1000)
  422. sizes: dict[str, int] = Field(default_factory=dict, max_length=1000)
  423. @model_validator(mode="after")
  424. def _validate_sizes(self):
  425. """Validate optional FTP-reported sizes used for early rejection."""
  426. if self.sizes and set(self.sizes) != set(self.paths):
  427. raise ValueError("A size is required for every selected printer path")
  428. if any(size < 0 for size in self.sizes.values()):
  429. raise ValueError("Printer file sizes must not be negative")
  430. return self
  431. class PrinterFilesJobRequest(PrinterFilesDownloadRequest):
  432. """Browser preparation request, including native download presentation."""
  433. filename: str = Field(default="printer-files.zip", min_length=1, max_length=255)
  434. as_zip: bool = True