archive.py 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051
  1. import hashlib
  2. import html
  3. import json
  4. import logging
  5. import os
  6. import re
  7. import shutil
  8. import zipfile
  9. from datetime import date, datetime, time, timezone
  10. from pathlib import Path
  11. from defusedxml import ElementTree as ET
  12. from sqlalchemy import and_, or_, select, text
  13. from sqlalchemy.exc import IntegrityError
  14. from sqlalchemy.ext.asyncio import AsyncSession
  15. from backend.app.core.config import settings
  16. from backend.app.core.printer_scope import PrinterScope
  17. from backend.app.core.tasks import spawn_background_task
  18. from backend.app.models.archive import PrintArchive
  19. from backend.app.models.filament import Filament
  20. from backend.app.models.printer import Printer
  21. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  22. from backend.app.utils.ffmpeg_output import NO_FFMPEG_OUTPUT, summarize_ffmpeg_stderr
  23. from backend.app.utils.filename import clean_display_name
  24. from backend.app.utils.safe_path import PathTraversalError, assert_under, safe_join_under
  25. from backend.app.utils.threemf_tools import bed_temperature_from_config
  26. logger = logging.getLogger(__name__)
  27. def _copy_and_fsync(src: Path, dst: Path, chunk_size: int = 1024 * 1024) -> None:
  28. """Copy src to dst with an explicit chunked read/write and fsync the dst.
  29. Replacement for shutil.copy2 in the archive pipeline. shutil.copy2 uses
  30. Linux sendfile(), which on some kernels/filesystems has returned a short
  31. count on the first call and truncated the destination for larger 3MF
  32. uploads (#1032, observed on Raspberry Pi OS bookworm / armv7l). An
  33. explicit loop with fsync avoids that path and guarantees the dest bytes
  34. are on disk before the caller inspects them as a ZIP.
  35. """
  36. with src.open("rb") as rf, dst.open("wb") as wf:
  37. while True:
  38. buf = rf.read(chunk_size)
  39. if not buf:
  40. break
  41. wf.write(buf)
  42. wf.flush()
  43. os.fsync(wf.fileno())
  44. shutil.copystat(src, dst)
  45. def resolve_display_stem(filename: str) -> str:
  46. """Return a clean human-readable stem from a 3MF/gcode filename.
  47. Bambu Studio's "Send to printer" dialog typically writes files like
  48. ``Plate_1.gcode.3mf`` (a sliced gcode payload wrapped in a 3MF container).
  49. The naive ``Path(filename).stem`` only drops the last suffix, leaving
  50. ``Plate_1.gcode`` — which then surfaces in the archive UI as a confusing
  51. ``Plate_1.gcode`` rather than ``Plate_1`` (#1152 follow-up).
  52. Strip the recognised print-format suffixes in order:
  53. - ``.gcode.3mf`` → bare stem (Bambu Studio FTP send)
  54. - ``.3mf`` → bare stem
  55. - ``.gcode`` → bare stem (rare standalone gcode upload)
  56. Anything else passes through unchanged.
  57. """
  58. name = Path(filename).name # drop any path components
  59. lower = name.lower()
  60. for suffix in (".gcode.3mf", ".3mf", ".gcode"):
  61. if lower.endswith(suffix):
  62. return name[: -len(suffix)]
  63. return Path(name).stem
  64. def _read_plate_index(plate) -> int | None:
  65. """Return the 1-based index of a ``slice_info.config`` ``<plate>`` element, or None.
  66. Bambu Studio and OrcaSlicer record it as a ``<metadata key="index"
  67. value="N"/>`` child — there is no ``plate_idx`` attribute on ``<plate>``
  68. itself, so an XPath predicate on one never matches (#2522).
  69. """
  70. for meta in plate.findall("metadata"):
  71. if meta.get("key") == "index":
  72. value = meta.get("value")
  73. if not value:
  74. return None
  75. try:
  76. return int(value)
  77. except ValueError:
  78. return None
  79. return None
  80. def plate_indexes_in_3mf(file_path: Path) -> list[int | None]:
  81. """Return one entry per ``<plate>`` a Bambu 3MF declares, in file order.
  82. Reads only ``Metadata/slice_info.config``. An entry is None when that plate
  83. carries no readable index, and the list is empty for a file that could not
  84. be read at all — callers must not confuse either with "this file has plates
  85. and yours is not among them". An unreadable 3MF is a parse this code does
  86. not understand, not evidence about which plate it holds (#2957).
  87. """
  88. try:
  89. with zipfile.ZipFile(file_path, "r") as zf:
  90. if "Metadata/slice_info.config" not in zf.namelist():
  91. return []
  92. root = ET.fromstring(zf.read("Metadata/slice_info.config").decode())
  93. return [_read_plate_index(plate) for plate in root.findall(".//plate")]
  94. except Exception:
  95. return []
  96. def peek_plate_index_in_3mf(file_path: Path) -> int | None:
  97. """Return the plate index a single-plate Bambu 3MF represents, or None.
  98. Reads only ``Metadata/slice_info.config`` to keep this cheap — used by
  99. the print-start callback to verify that the 3MF we just downloaded over
  100. FTP actually matches the plate the printer is running (#1204). The full
  101. ThreeMFParser does much more work and runs later inside ArchiveService.
  102. An all-plates export carries every plate, so "which plate is this file"
  103. has no answer; returning None there keeps the #1204 guard from reading
  104. plate 1 out of such a file, declaring a mismatch against the plate that
  105. is really running, and discarding a perfectly good 3MF (#2522).
  106. """
  107. plates = plate_indexes_in_3mf(file_path)
  108. return plates[0] if len(plates) == 1 else None
  109. _PLATE_SUFFIX_RE = re.compile(r"^(.*?)(\s*-\s*Plate\s+|_plate_)(\d+)$", re.IGNORECASE)
  110. def swap_plate_suffix(name: str | None, target_plate: int) -> str | None:
  111. """Return ``name`` with its trailing plate number replaced, or None.
  112. Bambu Studio names multi-plate uploads ``"<Project> - Plate <N>"`` (and
  113. a lowercase ``"_plate_<N>"`` variant exists too — see
  114. test_print_start_expected_promotion). When MQTT subtask_name lags
  115. across consecutive plates of the same model (#1204) the suffix points
  116. at the previous plate; swapping it gives us the correct upload to
  117. re-fetch from FTP. Returns None if no recognised suffix is present.
  118. """
  119. if not name:
  120. return None
  121. m = _PLATE_SUFFIX_RE.match(name)
  122. if not m:
  123. return None
  124. base, separator, _ = m.groups()
  125. return f"{base}{separator}{target_plate}"
  126. _MESH_OPEN = b"<mesh"
  127. _MESH_CLOSE = b"</mesh>"
  128. _MODEL_READ_CHUNK = 1024 * 1024
  129. def read_3dmodel_without_meshes(zf: zipfile.ZipFile, model_path: str = "3D/3dmodel.model") -> str:
  130. """Return the model XML with every ``<mesh>...</mesh>`` body left out.
  131. The metadata scans only want ``<metadata>`` elements and the URLs inside
  132. them, but a plain 3MF keeps its geometry inline in this same entry: a
  133. combined plate's is hundreds of MB of vertex and triangle rows (#3162).
  134. Streaming past the meshes keeps memory to the non-geometry part. The
  135. entry can't simply be cut at ``<resources>``: BambuStudio writes its
  136. MakerWorld metadata after ``</build>``. Mesh bodies hold only numbers, and
  137. a ``<`` inside a metadata value is escaped, so nothing a scan looks for is
  138. dropped.
  139. """
  140. out = bytearray()
  141. pending = b""
  142. in_mesh = False
  143. with zf.open(model_path) as fh:
  144. while chunk := fh.read(_MODEL_READ_CHUNK):
  145. data = pending + chunk
  146. pos = 0
  147. while True:
  148. if in_mesh:
  149. end = data.find(_MESH_CLOSE, pos)
  150. if end == -1:
  151. # Keep enough of the tail to match a tag split across chunks.
  152. pending = data[max(pos, len(data) - len(_MESH_CLOSE) + 1) :]
  153. break
  154. pos = end + len(_MESH_CLOSE)
  155. in_mesh = False
  156. else:
  157. start = data.find(_MESH_OPEN, pos)
  158. if start == -1:
  159. keep = max(pos, len(data) - len(_MESH_OPEN) + 1)
  160. out += data[pos:keep]
  161. pending = data[keep:]
  162. break
  163. out += data[pos:start]
  164. pos = start + len(_MESH_OPEN)
  165. in_mesh = True
  166. if not in_mesh:
  167. out += pending
  168. return out.decode("utf-8", errors="ignore")
  169. # How much of a plate's G-code to scan for header/config values. The header
  170. # block ends in the first kilobyte; the CONFIG_BLOCK that follows it carries
  171. # layer_height 14-25KB in (measured across the sliced 3MFs on hand, Bambu
  172. # Studio and OrcaSlicer alike), so 4KB — what this used to read — could only
  173. # ever see the header.
  174. _GCODE_SCAN_BYTES = 64 * 1024
  175. class ThreeMFParser:
  176. """Parser for Bambu Lab 3MF files."""
  177. def __init__(self, file_path: Path, plate_number: int | None = None):
  178. self.file_path = file_path
  179. self.plate_number = plate_number # Which plate was printed (1, 2, 3, etc.)
  180. self.metadata: dict = {}
  181. def parse(self) -> dict:
  182. """Extract metadata from 3MF file."""
  183. try:
  184. with zipfile.ZipFile(self.file_path, "r") as zf:
  185. self._parse_slice_info(zf) # Now sets self.plate_number from slice_info
  186. self._parse_project_settings(zf)
  187. self._parse_gcode_header(zf)
  188. self._parse_3dmodel(zf)
  189. self._extract_thumbnail(zf) # Uses correct plate_number for thumbnail
  190. # Enhance print_name with plate info if this is a multi-plate export
  191. plate_index = self.metadata.get("_plate_index")
  192. if plate_index and plate_index > 1:
  193. # Append plate number to distinguish from other plates
  194. existing_name = self.metadata.get("print_name", "")
  195. if existing_name and f"Plate {plate_index}" not in existing_name:
  196. self.metadata["print_name"] = f"{existing_name} - Plate {plate_index}"
  197. # ALWAYS prefer slice_info values - they contain ONLY filaments actually used in print
  198. # project_settings contains ALL configured filaments (AMS slots), not just used ones
  199. if self.metadata.get("_slice_filament_type"):
  200. self.metadata["filament_type"] = self.metadata["_slice_filament_type"]
  201. if self.metadata.get("_slice_filament_color"):
  202. self.metadata["filament_color"] = self.metadata["_slice_filament_color"]
  203. # Clean up internal keys
  204. self.metadata.pop("_slice_filament_type", None)
  205. self.metadata.pop("_slice_filament_color", None)
  206. self.metadata.pop("_plate_index", None)
  207. except Exception as e:
  208. # Return whatever metadata was extracted before the error, but
  209. # surface the failure so corrupted / truncated 3MF archives are
  210. # visible in support bundles (#1032).
  211. logger.warning(
  212. "ThreeMFParser: failed to parse %s: %s(%s) — returning partial metadata",
  213. self.file_path,
  214. type(e).__name__,
  215. e,
  216. )
  217. return self.metadata
  218. def _parse_slice_info(self, zf: zipfile.ZipFile):
  219. """Parse slice_info.config for print settings and printable objects."""
  220. try:
  221. if "Metadata/slice_info.config" in zf.namelist():
  222. content = zf.read("Metadata/slice_info.config").decode()
  223. root = ET.fromstring(content)
  224. # Extract printer_model_id from plate metadata
  225. # Format: <plate><metadata key="printer_model_id" value="C11" /></plate>
  226. for meta in root.findall(".//metadata"):
  227. key = meta.get("key")
  228. value = meta.get("value")
  229. if key == "printer_model_id" and value:
  230. from backend.app.utils.printer_models import normalize_printer_model_id
  231. normalized = normalize_printer_model_id(value)
  232. if normalized:
  233. self.metadata["sliced_for_model"] = normalized
  234. break
  235. # Loop every <plate> so multi-plate exports get summed file-level
  236. # totals. Pre-fix, this used `root.find(".//plate")` which
  237. # returned only the first plate — file-level `print_time_seconds`
  238. # / `filament_used_grams` reflected plate 1 alone, and the
  239. # archive card / project rollup under-reported by the number
  240. # of plates (#1593). Per-plate breakdown is still served by
  241. # the dedicated `/plates` endpoint.
  242. plates = root.findall(".//plate")
  243. summed_time = 0
  244. summed_grams = 0.0
  245. any_time_seen = False
  246. any_grams_seen = False
  247. for plate in plates:
  248. # Plate-level fields that only make sense at the file
  249. # level when there's exactly one plate. ``plate_number``
  250. # / ``_plate_index`` describe which plate the export
  251. # represents — meaningless for an all-plates 3MF, so we
  252. # only record them in the single-plate case. ``bed_type``
  253. # is also single-valued; we take the first plate's value
  254. # as a best-effort default for the archive metadata.
  255. plate_index_value: int | None = None
  256. for meta in plate.findall("metadata"):
  257. key = meta.get("key")
  258. value = meta.get("value")
  259. if key == "index" and value:
  260. try:
  261. plate_index_value = int(value)
  262. except ValueError:
  263. pass # Skip non-numeric plate index
  264. elif key == "prediction" and value:
  265. try:
  266. summed_time += int(value)
  267. any_time_seen = True
  268. except ValueError:
  269. pass
  270. elif key == "weight" and value:
  271. try:
  272. summed_grams += float(value)
  273. any_grams_seen = True
  274. except ValueError:
  275. pass
  276. elif key == "curr_bed_type" and value and "bed_type" not in self.metadata:
  277. self.metadata["bed_type"] = value
  278. # Per-plate object lists are only kept at the file level
  279. # when there's one plate — the skip-object affordance
  280. # operates on the plate being printed, which is the
  281. # `/plates` endpoint's job for multi-plate exports.
  282. if len(plates) == 1:
  283. if plate_index_value is not None:
  284. if not self.plate_number:
  285. self.plate_number = plate_index_value
  286. self.metadata["_plate_index"] = plate_index_value
  287. printable_objects: dict[int, str] = {}
  288. for obj in plate.findall("object"):
  289. identify_id = obj.get("identify_id")
  290. name = obj.get("name")
  291. skipped = obj.get("skipped", "false")
  292. if identify_id and name and skipped.lower() != "true":
  293. try:
  294. printable_objects[int(identify_id)] = name
  295. except ValueError:
  296. pass # Skip objects with non-numeric identify_id
  297. if printable_objects:
  298. self.metadata["printable_objects"] = printable_objects
  299. if any_time_seen:
  300. self.metadata["print_time_seconds"] = summed_time
  301. if any_grams_seen:
  302. self.metadata["filament_used_grams"] = round(summed_grams, 2)
  303. # Get filament info from filaments ACTUALLY USED in the print
  304. # slice_info has <filament id="1" type="PLA" color="#FFFFFF" used_g="100" />
  305. # Only include filaments where used_g > 0
  306. filaments = root.findall(".//filament")
  307. if filaments:
  308. # Collect unique filament types and colors for filaments that are actually used
  309. types = []
  310. colors = []
  311. for f in filaments:
  312. # Check if this filament is actually used in the print
  313. used_g = f.get("used_g", "0")
  314. try:
  315. used_amount = float(used_g)
  316. except (ValueError, TypeError):
  317. used_amount = 0
  318. # Only include if used_g > 0 (filament is actually consumed)
  319. if used_amount > 0:
  320. ftype = f.get("type")
  321. fcolor = f.get("color")
  322. if ftype and ftype not in types:
  323. types.append(ftype)
  324. if fcolor and fcolor not in colors:
  325. colors.append(fcolor)
  326. if types:
  327. self.metadata["_slice_filament_type"] = ", ".join(types)
  328. if colors:
  329. self.metadata["_slice_filament_color"] = ",".join(colors)
  330. # Collect per-slot filament usage for tracking & notifications
  331. filament_slots = []
  332. for f in filaments:
  333. slot_id = f.get("id")
  334. used_g_str = f.get("used_g", "0")
  335. try:
  336. used_g = float(used_g_str)
  337. except (ValueError, TypeError):
  338. used_g = 0
  339. if used_g > 0 and slot_id:
  340. filament_slots.append(
  341. {
  342. "slot_id": int(slot_id),
  343. "used_g": round(used_g, 2),
  344. "type": f.get("type", ""),
  345. "color": f.get("color", ""),
  346. }
  347. )
  348. if filament_slots:
  349. self.metadata["filament_slots"] = filament_slots
  350. except Exception:
  351. pass # Skip unparseable slice_info metadata
  352. def _parse_project_settings(self, zf: zipfile.ZipFile):
  353. """Parse project settings for print configuration."""
  354. try:
  355. if "Metadata/project_settings.config" in zf.namelist():
  356. content = zf.read("Metadata/project_settings.config").decode()
  357. try:
  358. data = json.loads(content)
  359. self._extract_filament_info(data)
  360. self._extract_print_settings(data)
  361. except json.JSONDecodeError:
  362. pass # Skip malformed project_settings JSON
  363. except Exception:
  364. pass # Skip unreadable project settings file
  365. def _printed_plate_gcode(self, gcode_files: list[str]) -> str:
  366. """Return the G-code entry for the plate this archive is about.
  367. ``plate_number`` is known for a plate-specific export (slice_info sets
  368. it) and picking blindly is wrong there: a project sliced with plate 2
  369. at 0.08 and plate 1 at 0.2 would otherwise report plate 1's numbers.
  370. Falls back to the lowest plate index, then to zip order, so a file
  371. whose entries are named some other way still parses as it did before.
  372. """
  373. if self.plate_number:
  374. wanted = f"Metadata/plate_{self.plate_number}.gcode"
  375. if wanted in gcode_files:
  376. return wanted
  377. def plate_index(name: str) -> int:
  378. match = re.search(r"plate_(\d+)\.gcode$", name)
  379. return int(match.group(1)) if match else 10**6
  380. return min(gcode_files, key=lambda name: (plate_index(name), gcode_files.index(name)))
  381. def _parse_gcode_header(self, zf: zipfile.ZipFile):
  382. """Parse the printed plate's G-code for what only it can settle.
  383. The plate's own G-code is the file the printer executes, so where it
  384. disagrees with ``project_settings.config`` — the *project's* record,
  385. which a multi-plate or per-plate-modified export can leave describing
  386. a different plate entirely — the G-code wins.
  387. """
  388. try:
  389. gcode_files = [f for f in zf.namelist() if f.endswith(".gcode")]
  390. if not gcode_files:
  391. return
  392. gcode_path = self._printed_plate_gcode(gcode_files)
  393. # 64KB, not 4KB: the header block ends within the first kilobyte,
  394. # but the CONFIG_BLOCK that carries layer_height starts right after
  395. # it and the keys are alphabetical, so layer_height lands 14-25KB
  396. # in on real files. The read is decompress-on-demand, so the cost
  397. # of the wider window is a few tens of KB per archived file.
  398. with zf.open(gcode_path) as f:
  399. header = f.read(_GCODE_SCAN_BYTES).decode("utf-8", errors="ignore")
  400. # Look for "; total layer number: XX" pattern
  401. match = re.search(r";\s*total\s+layer\s+number[:\s]+(\d+)", header, re.IGNORECASE)
  402. if match:
  403. self.metadata["total_layers"] = int(match.group(1))
  404. # Layer height, overriding project_settings.config when both are
  405. # present. The project config records the project's settings and can
  406. # describe a plate other than this one; the plate's G-code is what
  407. # the printer executes, so it decides. Anchored to the line start so keys ending in
  408. # "layer_height" (independent_support_layer_height) can't match.
  409. match = re.search(r"^;\s*layer_height\s*=\s*([\d.]+)\s*$", header, re.IGNORECASE | re.MULTILINE)
  410. if match:
  411. try:
  412. self.metadata["layer_height"] = float(match.group(1))
  413. except ValueError:
  414. pass # Malformed value: keep whatever project_settings gave us
  415. # Total filament usage. The slicer writes the print's totals into
  416. # the G-code header ("; total filament weight [g] : 126.26"). Only
  417. # a fallback — slice_info.config is more authoritative when present
  418. # — but it covers sliced outputs whose slice_info lacks per-filament
  419. # used_g, and it's the slicer's own figure regardless.
  420. if "filament_used_grams" not in self.metadata:
  421. match = re.search(r";\s*total\s+filament\s+weight\s*\[g\]\s*:\s*([\d.]+)", header, re.IGNORECASE)
  422. if match:
  423. self.metadata["filament_used_grams"] = float(match.group(1))
  424. if "filament_used_mm" not in self.metadata:
  425. match = re.search(r";\s*total\s+filament\s+length\s*\[mm\]\s*:\s*([\d.]+)", header, re.IGNORECASE)
  426. if match:
  427. self.metadata["filament_used_mm"] = float(match.group(1))
  428. # Look for printer_model in gcode header (fallback if not found in slice_info)
  429. # Format: "; printer_model = Bambu Lab X1 Carbon" or "; printer_model = X1C"
  430. if "sliced_for_model" not in self.metadata:
  431. match = re.search(r";\s*printer_model\s*=\s*(.+)", header, re.IGNORECASE)
  432. if match:
  433. from backend.app.utils.printer_models import normalize_printer_model
  434. raw_model = match.group(1).strip()
  435. self.metadata["sliced_for_model"] = normalize_printer_model(raw_model)
  436. except Exception:
  437. pass # G-code header parsing is best-effort; metadata may come from other sources
  438. def _extract_filament_info(self, data: dict):
  439. """Extract filament info from project settings — includes support
  440. materials so a PLA-model / PVA-support project shows both on the
  441. archive card badge (#1881).
  442. Earlier code filtered by ``filament_is_support``; that hid PVA
  443. (and any other soluble/breakaway support material) from the card
  444. even when the user had explicitly configured it, and made source
  445. 3MFs look single-material until the print completed. slice_info
  446. (parsed separately) is still preferred when present — it lists
  447. only filaments the print actually consumes, this fallback only
  448. runs on unsliced source 3MFs.
  449. """
  450. try:
  451. filament_types = data.get("filament_type", [])
  452. filament_colors = data.get("filament_colour", [])
  453. if not filament_types:
  454. return
  455. unique_types: list[str] = []
  456. for ftype in filament_types:
  457. if ftype and ftype not in unique_types:
  458. unique_types.append(ftype)
  459. unique_colors: list[str] = []
  460. for color in filament_colors:
  461. if color and color not in unique_colors:
  462. unique_colors.append(color)
  463. if unique_types:
  464. self.metadata["filament_type"] = ", ".join(unique_types)
  465. if unique_colors:
  466. self.metadata["filament_color"] = ",".join(unique_colors)
  467. except Exception:
  468. pass # Filament info is optional; fall back to slice_info values
  469. def _extract_print_settings(self, data: dict):
  470. """Extract print settings from JSON config."""
  471. try:
  472. # Layer height - usually an array, get first value
  473. if "layer_height" in data:
  474. val = data["layer_height"]
  475. if isinstance(val, list) and val:
  476. self.metadata["layer_height"] = float(val[0])
  477. elif isinstance(val, (int, float, str)):
  478. self.metadata["layer_height"] = float(val)
  479. # Nozzle diameter
  480. if "nozzle_diameter" in data:
  481. val = data["nozzle_diameter"]
  482. if isinstance(val, list) and val:
  483. self.metadata["nozzle_diameter"] = float(val[0])
  484. elif isinstance(val, (int, float, str)):
  485. self.metadata["nozzle_diameter"] = float(val)
  486. # Bed temperature, for the plate this project is sliced for. This
  487. # used to look for `bed_temperature` alone, a key BambuStudio does
  488. # not write -- so every archive from a Bambu slice stored NULL, and
  489. # preheat fell back to a configured bed temperature on every job
  490. # (#2989). Orca-exported 3MFs keep working through the generic keys.
  491. bed_temperature = bed_temperature_from_config(data)
  492. if bed_temperature is not None:
  493. self.metadata["bed_temperature"] = bed_temperature
  494. # Nozzle temperature
  495. for key in ["nozzle_temperature_initial_layer", "nozzle_temperature"]:
  496. if key in data:
  497. val = data[key]
  498. if isinstance(val, list) and val:
  499. self.metadata["nozzle_temperature"] = int(float(val[0]))
  500. elif isinstance(val, (int, float, str)):
  501. self.metadata["nozzle_temperature"] = int(float(val))
  502. break
  503. # Printer model (extract and normalize)
  504. if "printer_model" in data:
  505. from backend.app.utils.printer_models import normalize_printer_model
  506. self.metadata["sliced_for_model"] = normalize_printer_model(data["printer_model"])
  507. # Build plate type — only set from project_settings if slice_info didn't already
  508. # provide it (slice_info is more authoritative as it reflects the exported plate).
  509. if "bed_type" not in self.metadata and "curr_bed_type" in data:
  510. val = data["curr_bed_type"]
  511. if isinstance(val, str) and val.strip():
  512. self.metadata["bed_type"] = val.strip()
  513. except Exception:
  514. pass # Print settings are optional; missing values are left unset
  515. def _parse_3dmodel(self, zf: zipfile.ZipFile):
  516. """Parse 3D/3dmodel.model for MakerWorld metadata."""
  517. try:
  518. model_path = "3D/3dmodel.model"
  519. if model_path not in zf.namelist():
  520. return
  521. content = read_3dmodel_without_meshes(zf, model_path)
  522. # Parse XML metadata elements
  523. # MakerWorld adds metadata like: <metadata name="Designer">username</metadata>
  524. metadata_pattern = r'<metadata\s+name="([^"]+)"[^>]*>([^<]*)</metadata>'
  525. matches = re.findall(metadata_pattern, content)
  526. # 3MF metadata values are XML-encoded — `&` becomes `&amp;`, etc.
  527. # ProjectPageParser learned this the hard way: BambuStudio sometimes
  528. # writes triple-encoded payloads (`&amp;amp;amp;`), so we unescape
  529. # in a loop until the string stabilises. Without this, a Title like
  530. # "Foo & Bar" lands in the DB as raw "Foo &amp; Bar" and React then
  531. # double-escapes it on render to "Foo &amp;amp; Bar" (#1658).
  532. makerworld_fields = {}
  533. for name, value in matches:
  534. decoded = value.strip()
  535. prev = None
  536. while prev != decoded:
  537. prev = decoded
  538. decoded = html.unescape(decoded)
  539. makerworld_fields[name] = decoded
  540. # Check for direct MakerWorld URL in content
  541. url_pattern = r'https?://makerworld\.com/[^\s<>"\']+/models/(\d+)'
  542. url_match = re.search(url_pattern, content)
  543. if url_match:
  544. self.metadata["makerworld_url"] = url_match.group(0)
  545. self.metadata["makerworld_model_id"] = url_match.group(1)
  546. # Extract model ID from DSM reference in image URLs
  547. # Format: https://makerworld.bblmw.com/makerworld/model/DSM00000001275614/...
  548. # The numeric part (1275614) is the MakerWorld model ID
  549. if "makerworld_url" not in self.metadata:
  550. dsm_pattern = r"DSM0+(\d+)"
  551. dsm_match = re.search(dsm_pattern, content)
  552. if dsm_match:
  553. model_id = dsm_match.group(1)
  554. self.metadata["makerworld_url"] = f"https://makerworld.com/en/models/{model_id}"
  555. self.metadata["makerworld_model_id"] = model_id
  556. # Store designer info
  557. if "Designer" in makerworld_fields:
  558. self.metadata["designer"] = makerworld_fields["Designer"]
  559. if "Title" in makerworld_fields:
  560. self.metadata["print_name"] = makerworld_fields["Title"]
  561. except Exception:
  562. pass # MakerWorld/3dmodel metadata is optional
  563. def _extract_thumbnail(self, zf: zipfile.ZipFile):
  564. """Extract thumbnail image from 3MF.
  565. If a plate_number was specified, try to use that plate's thumbnail first.
  566. """
  567. thumbnail_paths = []
  568. # If a specific plate was printed, try that thumbnail first
  569. if self.plate_number:
  570. thumbnail_paths.append(f"Metadata/plate_{self.plate_number}.png")
  571. # Fallback to default paths
  572. thumbnail_paths.extend(
  573. [
  574. "Metadata/plate_1.png",
  575. "Metadata/thumbnail.png",
  576. "Metadata/model_thumbnail.png",
  577. # Project-wide thumbnail BambuStudio embeds at upload time. We
  578. # only reach this when BS hasn't written a per-plate
  579. # ``Metadata/plate_N.png`` — most notably the #1493 cross-class
  580. # re-slice path where ``--arrange`` rearranges objects but the
  581. # CLI then doesn't emit a fresh per-plate preview. The
  582. # ``_middle`` size is the editor-quality variant (~500 KB);
  583. # ``_small`` and ``_3mf`` are smaller alternates if it's not
  584. # present. Without this fallback the re-sliced archive cards
  585. # render without a cover image.
  586. "Auxiliaries/.thumbnails/thumbnail_middle.png",
  587. "Auxiliaries/.thumbnails/thumbnail_small.png",
  588. "Auxiliaries/.thumbnails/thumbnail_3mf.png",
  589. ]
  590. )
  591. for thumb_path in thumbnail_paths:
  592. if thumb_path in zf.namelist():
  593. self.metadata["_thumbnail_data"] = zf.read(thumb_path)
  594. self.metadata["_thumbnail_ext"] = ".png"
  595. break
  596. def extract_printable_objects_from_archive(
  597. file_path: Path, plate_number: int | None = None
  598. ) -> tuple[dict[int, dict], list | None]:
  599. """Objects and plate bbox for an archived print, read off local disk.
  600. The archive of a running print usually holds the very 3MF the printer is
  601. executing, so the object list can be rebuilt without asking the printer for
  602. a file we already have -- 15 MB over FTPS from a machine that is mid-print,
  603. in the case this was written for. Returns empty when the archive has
  604. no readable 3MF, which is the caller's signal to fall back to the printer.
  605. """
  606. if not file_path.is_file() or not str(file_path).endswith(".3mf"):
  607. return {}, None
  608. try:
  609. data = file_path.read_bytes()
  610. except OSError:
  611. return {}, None
  612. return extract_printable_objects_from_3mf(data, plate_number=plate_number, include_positions=True)
  613. def extract_printable_objects_from_3mf(
  614. data: bytes, plate_number: int | None = None, include_positions: bool = False
  615. ) -> dict[int, str] | dict[int, dict] | tuple[dict[int, dict], list | None]:
  616. """Extract printable objects from 3MF file bytes.
  617. This is a lightweight function used during print start to get the list
  618. of objects that can be skipped.
  619. Args:
  620. data: Raw bytes of the 3MF file
  621. plate_number: Which plate was printed (1-based), or None for first plate
  622. include_positions: If True, return tuple of (objects dict, bbox_all)
  623. Returns:
  624. If include_positions=False: Dictionary mapping identify_id (int) to object name (str)
  625. If include_positions=True: Tuple of (dict mapping identify_id to {name, x, y}, bbox_all list or None)
  626. """
  627. from io import BytesIO
  628. printable_objects: dict = {}
  629. bbox_all: list | None = None
  630. try:
  631. with zipfile.ZipFile(BytesIO(data), "r") as zf:
  632. if "Metadata/slice_info.config" not in zf.namelist():
  633. return printable_objects
  634. content = zf.read("Metadata/slice_info.config").decode()
  635. root = ET.fromstring(content)
  636. plates = root.findall(".//plate")
  637. if not plates:
  638. return printable_objects
  639. # Pick the plate that is actually printing. An all-plates export
  640. # lists every plate, so without this we offered the objects (and
  641. # the marker positions) of plate 1 whatever the printer was
  642. # running (#2522). Falling back to the first plate keeps the
  643. # single-plate export — the common case — working when the caller
  644. # has no plate to give us.
  645. plate = None
  646. if plate_number is not None:
  647. plate = next((p for p in plates if _read_plate_index(p) == plate_number), None)
  648. if plate is None:
  649. plate = plates[0]
  650. # Derive plate_idx from the plate we settled on, never from the
  651. # requested one: on a fallback they differ, and plate_idx also
  652. # selects the plate_N.json the positions come from.
  653. plate_idx = _read_plate_index(plate) or 1
  654. # Load position data from plate_N.json if we need positions
  655. # Build a lookup by name - use list to handle duplicate names
  656. bbox_by_name: dict[str, list[list]] = {}
  657. if include_positions:
  658. plate_json_path = f"Metadata/plate_{plate_idx}.json"
  659. if plate_json_path in zf.namelist():
  660. try:
  661. plate_json = json.loads(zf.read(plate_json_path).decode())
  662. # Get bbox_all - the bounding box of all objects (used for image bounds)
  663. bbox_all = plate_json.get("bbox_all")
  664. for bbox_obj in plate_json.get("bbox_objects", []):
  665. obj_name = bbox_obj.get("name")
  666. bbox = bbox_obj.get("bbox", [])
  667. if obj_name and len(bbox) >= 4:
  668. if obj_name not in bbox_by_name:
  669. bbox_by_name[obj_name] = []
  670. bbox_by_name[obj_name].append(bbox)
  671. except (json.JSONDecodeError, KeyError):
  672. pass # Position data is optional; objects will lack x/y coordinates
  673. # Extract objects from slice_info.config
  674. for obj in plate.findall("object"):
  675. identify_id = obj.get("identify_id")
  676. name = obj.get("name")
  677. skipped = obj.get("skipped", "false")
  678. if identify_id and name and skipped.lower() != "true":
  679. try:
  680. obj_id = int(identify_id)
  681. if include_positions:
  682. x, y = None, None
  683. # Match by name - pop first bbox to handle duplicates
  684. bboxes = bbox_by_name.get(name)
  685. if bboxes:
  686. bbox = bboxes.pop(0)
  687. # Calculate center from bbox [x_min, y_min, x_max, y_max]
  688. x = (bbox[0] + bbox[2]) / 2
  689. y = (bbox[1] + bbox[3]) / 2
  690. printable_objects[obj_id] = {"name": name, "x": x, "y": y}
  691. else:
  692. printable_objects[obj_id] = name
  693. except ValueError:
  694. pass # Skip objects with non-numeric identify_id
  695. except Exception:
  696. pass # Return empty dict if 3MF is corrupt or unreadable
  697. if include_positions:
  698. return printable_objects, bbox_all
  699. return printable_objects
  700. class ProjectPageParser:
  701. """Parser for extracting project page data from Bambu Lab 3MF files."""
  702. def __init__(self, file_path: Path):
  703. self.file_path = file_path
  704. def parse(self, archive_id: int) -> dict:
  705. """Extract project page metadata and images from 3MF file."""
  706. import html
  707. result = {
  708. "title": None,
  709. "description": None,
  710. "designer": None,
  711. "designer_user_id": None,
  712. "license": None,
  713. "copyright": None,
  714. "creation_date": None,
  715. "modification_date": None,
  716. "origin": None,
  717. "profile_title": None,
  718. "profile_description": None,
  719. "profile_cover": None,
  720. "profile_user_id": None,
  721. "profile_user_name": None,
  722. "design_model_id": None,
  723. "design_profile_id": None,
  724. "design_region": None,
  725. "model_pictures": [],
  726. "profile_pictures": [],
  727. "thumbnails": [],
  728. }
  729. try:
  730. with zipfile.ZipFile(self.file_path, "r") as zf:
  731. # Parse 3D/3dmodel.model for metadata
  732. model_path = "3D/3dmodel.model"
  733. if model_path in zf.namelist():
  734. content = read_3dmodel_without_meshes(zf, model_path)
  735. # Extract metadata elements using regex
  736. # Format: <metadata name="Key">Value</metadata> or <metadata name="Key" />
  737. metadata_pattern = r'<metadata\s+name="([^"]+)"[^>]*>([^<]*)</metadata>'
  738. matches = re.findall(metadata_pattern, content)
  739. field_mapping = {
  740. "Title": "title",
  741. "Description": "description",
  742. "Designer": "designer",
  743. "DesignerUserId": "designer_user_id",
  744. "License": "license",
  745. "Copyright": "copyright",
  746. "CreationDate": "creation_date",
  747. "ModificationDate": "modification_date",
  748. "Origin": "origin",
  749. "ProfileTitle": "profile_title",
  750. "ProfileDescription": "profile_description",
  751. "ProfileCover": "profile_cover",
  752. "ProfileUserId": "profile_user_id",
  753. "ProfileUserName": "profile_user_name",
  754. "DesignModelId": "design_model_id",
  755. "DesignProfileId": "design_profile_id",
  756. "DesignRegion": "design_region",
  757. }
  758. for name, value in matches:
  759. if name in field_mapping:
  760. # Decode HTML entities multiple times (content is often triple-encoded)
  761. decoded = value.strip()
  762. prev = None
  763. while prev != decoded:
  764. prev = decoded
  765. decoded = html.unescape(decoded)
  766. # Normalize non-breaking spaces to regular spaces
  767. decoded = decoded.replace("\xa0", " ")
  768. result[field_mapping[name]] = decoded if decoded else None
  769. # List images in Auxiliaries folder
  770. from urllib.parse import quote
  771. for name in zf.namelist():
  772. if name.startswith("Auxiliaries/Model Pictures/"):
  773. filename = name.split("/")[-1]
  774. if filename:
  775. result["model_pictures"].append(
  776. {
  777. "name": filename,
  778. "path": name,
  779. "url": f"/api/v1/archives/{archive_id}/project-image/{quote(name, safe='')}",
  780. }
  781. )
  782. elif name.startswith("Auxiliaries/Profile Pictures/"):
  783. filename = name.split("/")[-1]
  784. if filename:
  785. result["profile_pictures"].append(
  786. {
  787. "name": filename,
  788. "path": name,
  789. "url": f"/api/v1/archives/{archive_id}/project-image/{quote(name, safe='')}",
  790. }
  791. )
  792. elif name.startswith("Auxiliaries/.thumbnails/"):
  793. filename = name.split("/")[-1]
  794. if filename:
  795. result["thumbnails"].append(
  796. {
  797. "name": filename,
  798. "path": name,
  799. "url": f"/api/v1/archives/{archive_id}/project-image/{quote(name, safe='')}",
  800. }
  801. )
  802. except Exception as e:
  803. result["_error"] = str(e)
  804. return result
  805. def get_image(self, image_path: str) -> tuple[bytes, str] | None:
  806. """Extract an image from the 3MF file.
  807. Returns tuple of (image_data, content_type) or None if not found.
  808. """
  809. try:
  810. with zipfile.ZipFile(self.file_path, "r") as zf:
  811. if image_path in zf.namelist():
  812. data = zf.read(image_path)
  813. # Determine content type from extension
  814. ext = image_path.lower().split(".")[-1]
  815. content_types = {
  816. "png": "image/png",
  817. "jpg": "image/jpeg",
  818. "jpeg": "image/jpeg",
  819. "webp": "image/webp",
  820. "gif": "image/gif",
  821. }
  822. content_type = content_types.get(ext, "application/octet-stream")
  823. return (data, content_type)
  824. except Exception:
  825. pass # Return None if image cannot be extracted from 3MF
  826. return None
  827. def update_metadata(self, updates: dict) -> bool:
  828. """Update project page metadata in the 3MF file.
  829. Args:
  830. updates: Dict with fields to update (title, description, designer, etc.)
  831. Returns:
  832. True if successful, False otherwise.
  833. """
  834. import html
  835. import tempfile
  836. try:
  837. # Read the 3MF file
  838. with zipfile.ZipFile(self.file_path, "r") as zf_read:
  839. # Find and read the 3dmodel.model file
  840. model_path = "3D/3dmodel.model"
  841. if model_path not in zf_read.namelist():
  842. return False
  843. content = zf_read.read(model_path).decode("utf-8")
  844. # Update metadata fields
  845. field_mapping = {
  846. "title": "Title",
  847. "description": "Description",
  848. "designer": "Designer",
  849. "license": "License",
  850. "copyright": "Copyright",
  851. "profile_title": "ProfileTitle",
  852. "profile_description": "ProfileDescription",
  853. }
  854. for field, xml_name in field_mapping.items():
  855. if field in updates and updates[field] is not None:
  856. new_value = html.escape(updates[field])
  857. # Replace existing metadata or we'd need to add it
  858. pattern = rf'(<metadata\s+name="{xml_name}"[^>]*>)[^<]*(</metadata>)'
  859. replacement = rf"\g<1>{new_value}\g<2>"
  860. content = re.sub(pattern, replacement, content)
  861. # Write to a temporary file first
  862. with tempfile.NamedTemporaryFile(delete=False, suffix=".3mf") as tmp:
  863. tmp_path = Path(tmp.name)
  864. # Create new zip with updated content
  865. with zipfile.ZipFile(tmp_path, "w", zipfile.ZIP_DEFLATED) as zf_write:
  866. for item in zf_read.namelist():
  867. if item == model_path:
  868. zf_write.writestr(item, content.encode("utf-8"))
  869. else:
  870. zf_write.writestr(item, zf_read.read(item))
  871. # Replace original file with updated one
  872. shutil.move(tmp_path, self.file_path)
  873. return True
  874. except Exception:
  875. # Clean up temp file if it exists
  876. if "tmp_path" in locals() and tmp_path.exists():
  877. tmp_path.unlink()
  878. return False
  879. async def _null_print_log_thumbnail_paths(db: AsyncSession, archive_id: int) -> None:
  880. """NULL thumbnail_path on PrintLogEntry rows linked to *archive_id*.
  881. Called from both soft- and hard-delete paths before the archive's files
  882. leave disk. The FK on PrintLogEntry.archive_id is ON DELETE SET NULL so
  883. log rows survive the archive — without this clear, their cached
  884. thumbnail_path would still point at a deleted file and the print-log
  885. view would 404-storm on every render (#1348 follow-up). Lazy-NULL on
  886. the GET route self-heals stragglers (e.g. failed prints that never had
  887. a thumbnail written), but eager clear here avoids the one-time storm.
  888. """
  889. from sqlalchemy import update as sa_update
  890. from backend.app.models.print_log import PrintLogEntry
  891. await db.execute(sa_update(PrintLogEntry).where(PrintLogEntry.archive_id == archive_id).values(thumbnail_path=None))
  892. async def _delete_related_queue_items(db: AsyncSession, archive_id: int) -> int:
  893. """Delete every queue item pointing at *archive_id* (#1734).
  894. Called from ``soft_delete_archive``. Hard-delete is covered by the
  895. ``ON DELETE CASCADE`` on ``print_queue.archive_id`` — same end state
  896. via the FK. Pre-#1734 this helper merely flipped pending rows to
  897. ``status='cancelled'`` while leaving every other status alone and
  898. leaving the rows in the DB, which surprised users who expected the
  899. queue lines to disappear when their backing archive went away. Worse,
  900. a Send-All archive backed N queue items (one per plate, #1733) — soft-
  901. deleting that archive left N "cancelled" rows behind, none of which
  902. could ever dispatch.
  903. Now we delete unconditionally regardless of status. ``printing`` rows
  904. are blocked one layer up at the route (``delete_archive`` returns 409
  905. when a related row is mid-print) so we never delete an actively-
  906. running queue row out from under the dispatcher. Completed / failed
  907. / cancelled rows go too — they're queue history, not print history.
  908. PrintLogEntry rows are the authoritative print history and are
  909. untouched (FK ``ON DELETE SET NULL``).
  910. Returns the number of rows removed so the caller can report it.
  911. """
  912. from sqlalchemy import delete as sa_delete
  913. from backend.app.models.print_queue import PrintQueueItem
  914. result = await db.execute(sa_delete(PrintQueueItem).where(PrintQueueItem.archive_id == archive_id))
  915. return result.rowcount or 0
  916. async def _count_related_queue_items(db: AsyncSession, archive_id: int) -> tuple[int, int]:
  917. """Return ``(total, printing)`` queue items linked to *archive_id*.
  918. Used by the archive GET response so the frontend delete-confirm modal
  919. can surface how much the deletion will wipe out, and by the delete
  920. route so it can 409 when a related row is currently printing (#1734).
  921. """
  922. from sqlalchemy import func as sa_func, select as sa_select
  923. from backend.app.models.print_queue import PrintQueueItem
  924. total = (
  925. await db.execute(
  926. sa_select(sa_func.count()).select_from(PrintQueueItem).where(PrintQueueItem.archive_id == archive_id)
  927. )
  928. ).scalar_one()
  929. printing = (
  930. await db.execute(
  931. sa_select(sa_func.count())
  932. .select_from(PrintQueueItem)
  933. .where(
  934. PrintQueueItem.archive_id == archive_id,
  935. PrintQueueItem.status == "printing",
  936. )
  937. )
  938. ).scalar_one()
  939. return int(total or 0), int(printing or 0)
  940. class ArchiveService:
  941. """Service for archiving print jobs."""
  942. def __init__(self, db: AsyncSession):
  943. self.db = db
  944. @staticmethod
  945. def compute_file_hash(file_path: Path) -> str:
  946. """Compute SHA256 hash of a file for duplicate detection."""
  947. sha256 = hashlib.sha256()
  948. with open(file_path, "rb") as f:
  949. # Read in chunks to handle large files
  950. for chunk in iter(lambda: f.read(8192), b""):
  951. sha256.update(chunk)
  952. return sha256.hexdigest()
  953. async def get_duplicate_hashes_and_names(self) -> tuple[set[str], set[tuple[str, str]]]:
  954. """Get all content hashes and (print name, hash) pairs that appear more than once.
  955. For hashes: returns all hashes with > 1 archive (true duplicates).
  956. For name/hash pairs: returns only pairs that have > 1 archive
  957. (i.e., same file archived multiple times, not different files with same name).
  958. Returns a tuple of (duplicate_hashes, duplicate_name_hash_pairs).
  959. """
  960. from sqlalchemy import func
  961. # Soft-deleted archives don't appear in the listing (#1343), so they
  962. # mustn't influence the duplicate-group counts either — otherwise a
  963. # group with 1 live + 4 soft-deleted would still be flagged as a
  964. # duplicate even though the user only sees one row.
  965. result = await self.db.execute(
  966. select(PrintArchive.content_hash)
  967. .where(PrintArchive.content_hash.isnot(None), PrintArchive.deleted_at.is_(None))
  968. .group_by(PrintArchive.content_hash)
  969. .having(func.count(PrintArchive.id) > 1)
  970. )
  971. duplicate_hashes = {row[0] for row in result.all()}
  972. # Find print names that have multiple archives with the SAME hash
  973. # This avoids marking different files with the same name as duplicates
  974. result = await self.db.execute(
  975. select(func.lower(PrintArchive.print_name), PrintArchive.content_hash)
  976. .where(
  977. PrintArchive.print_name.isnot(None),
  978. PrintArchive.content_hash.isnot(None),
  979. PrintArchive.deleted_at.is_(None),
  980. )
  981. .group_by(func.lower(PrintArchive.print_name), PrintArchive.content_hash)
  982. .having(func.count(PrintArchive.id) > 1)
  983. )
  984. duplicate_name_hash_pairs = {(row[0], row[1]) for row in result.all()}
  985. return duplicate_hashes, duplicate_name_hash_pairs
  986. async def find_duplicates(
  987. self,
  988. archive_id: int,
  989. content_hash: str | None = None,
  990. print_name: str | None = None,
  991. makerworld_model_id: str | None = None,
  992. ) -> list[dict]:
  993. """Find duplicate archives based on hash or name matching.
  994. Returns list of dicts with id, print_name, created_at, match_type.
  995. """
  996. duplicates = []
  997. # First, find exact matches by content hash
  998. if content_hash:
  999. result = await self.db.execute(
  1000. select(PrintArchive)
  1001. .where(
  1002. and_(
  1003. PrintArchive.content_hash == content_hash,
  1004. PrintArchive.id != archive_id,
  1005. PrintArchive.deleted_at.is_(None),
  1006. )
  1007. )
  1008. .order_by(PrintArchive.created_at.desc())
  1009. .limit(10)
  1010. )
  1011. for archive in result.scalars().all():
  1012. duplicates.append(
  1013. {
  1014. "id": archive.id,
  1015. "print_name": archive.print_name,
  1016. "created_at": archive.created_at,
  1017. "match_type": "exact",
  1018. }
  1019. )
  1020. # Then, find similar matches by print name or MakerWorld ID
  1021. # Prefer strict name+hash matching when hash exists; fallback to name-only for legacy/manual
  1022. # archives that may not have a content_hash.
  1023. if print_name or makerworld_model_id:
  1024. conditions = [PrintArchive.id != archive_id, PrintArchive.deleted_at.is_(None)]
  1025. name_conditions = []
  1026. if print_name:
  1027. if content_hash:
  1028. # Match if print names are similar AND have the same hash (same file)
  1029. name_conditions.append(
  1030. and_(PrintArchive.print_name.ilike(print_name), PrintArchive.content_hash == content_hash)
  1031. )
  1032. else:
  1033. # Fallback for archives without hash data: match by print name only.
  1034. name_conditions.append(PrintArchive.print_name.ilike(print_name))
  1035. if makerworld_model_id:
  1036. # Match by MakerWorld model ID stored in extra_data
  1037. from backend.app.core.db_dialect import is_sqlite
  1038. if is_sqlite():
  1039. from sqlalchemy import func
  1040. name_conditions.append(
  1041. func.json_extract(PrintArchive.extra_data, "$.makerworld_model_id") == str(makerworld_model_id)
  1042. )
  1043. else:
  1044. name_conditions.append(
  1045. text("(extra_data::jsonb->>'makerworld_model_id') = :mw_id").bindparams(
  1046. mw_id=str(makerworld_model_id)
  1047. )
  1048. )
  1049. if name_conditions:
  1050. conditions.append(or_(*name_conditions))
  1051. result = await self.db.execute(
  1052. select(PrintArchive).where(and_(*conditions)).order_by(PrintArchive.created_at.desc()).limit(10)
  1053. )
  1054. for archive in result.scalars().all():
  1055. # Don't add if already in duplicates (exact match)
  1056. if not any(d["id"] == archive.id for d in duplicates):
  1057. duplicates.append(
  1058. {
  1059. "id": archive.id,
  1060. "print_name": archive.print_name,
  1061. "created_at": archive.created_at,
  1062. "match_type": "similar",
  1063. }
  1064. )
  1065. return duplicates
  1066. async def archive_print(
  1067. self,
  1068. printer_id: int | None,
  1069. source_file: Path,
  1070. print_data: dict | None = None,
  1071. created_by_id: int | None = None,
  1072. original_filename: str | None = None,
  1073. project_id: int | None = None,
  1074. cost_center_id: int | None = None,
  1075. subtask_id: str | None = None,
  1076. prefer_filename_for_name: bool = False,
  1077. plate_id: int | None = None,
  1078. library_file_id: int | None = None,
  1079. slicer_ams_mapping: list[int] | None = None,
  1080. slicer_ams_mapping_printer_id: int | None = None,
  1081. update_archive_id: int | None = None,
  1082. ) -> PrintArchive | None:
  1083. """Archive a 3MF file with metadata.
  1084. Args:
  1085. printer_id: ID of the printer (optional)
  1086. source_file: Path to the 3MF file
  1087. print_data: Print data from MQTT (optional)
  1088. created_by_id: User ID who created this archive (optional, for user tracking)
  1089. original_filename: Original human-readable filename (optional, for library files
  1090. stored with UUID names)
  1091. project_id: Project to associate this archive with (optional, set when triggered
  1092. from the project view)
  1093. library_file_id: Library file this run was dispatched from (optional,
  1094. set by the queue scheduler — powers per-file project progress, #1897)
  1095. subtask_id: MQTT-provided task identifier (optional). Used to match an
  1096. existing archive across a backend restart mid-print so the
  1097. original row can be resumed instead of cancelled (#972).
  1098. prefer_filename_for_name: When True, use the uploaded filename stem as the
  1099. archive's display name even if the 3MF embeds a `print_name` in its
  1100. metadata. Used by virtual-printer flows so users who rename a job in
  1101. BambuStudio's "send to printer" dialog see that name instead of the
  1102. creator-baked title (#1152).
  1103. slicer_ams_mapping: The slicer's own live-resolved AMS-slot pick, to persist
  1104. onto `extra_data.slicer_ams_mapping` for a later reprint to reuse. Deliberately
  1105. a distinct parameter, not read off `print_data["ams_mapping"]` — that key is
  1106. populated on every MQTT print-start callback regardless of source (bambu_mqtt's
  1107. request-topic interception captures it for slicer-direct LAN prints too), so
  1108. promoting it unconditionally would stamp every archive on installs with no
  1109. virtual printer at all. Callers that gate this behind an opt-in (the VP-queue
  1110. "Save AMS mapping" toggle) pass it explicitly; everyone else leaves it unset.
  1111. slicer_ams_mapping_printer_id: The printer `slicer_ams_mapping`'s tray IDs were
  1112. resolved against. Required alongside `slicer_ams_mapping` — a global tray ID
  1113. only means something relative to one printer's specific AMS layout, so a
  1114. mapping saved without knowing which printer it came from can't be safely
  1115. reused later on any printer, including the same one (there'd be no way to
  1116. tell). A model-based VP with no fixed target printer has no valid value to
  1117. pass here and must leave both params unset.
  1118. update_archive_id: Fill in an existing archive row instead of adding one.
  1119. Used to upgrade a no-3MF fallback archive once the file finally arrives
  1120. (#2957). Everything above the row itself — the copy, the parse, the
  1121. thumbnail, the cost — is exactly what a fresh archive does; only the
  1122. destination differs. The row must keep its id: the energy-start reading,
  1123. the timelapse session, ``_active_prints``, the start notification and any
  1124. queue link were all written against it while the print was running, and a
  1125. second row would orphan every one of them. Fields the fallback path
  1126. already established from MQTT (``started_at``, ``subtask_id``,
  1127. ``created_by_id``, ``project_id``) are left alone; the 3MF has nothing
  1128. better to say about them.
  1129. """
  1130. # Verify printer exists if specified
  1131. if printer_id is not None:
  1132. result = await self.db.execute(select(Printer).where(Printer.id == printer_id))
  1133. printer = result.scalar_one_or_none()
  1134. if not printer:
  1135. return None
  1136. # Create archive directory structure
  1137. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  1138. display_stem = resolve_display_stem(original_filename if original_filename else source_file.name)
  1139. archive_name = f"{timestamp}_{display_stem}"
  1140. # Use "unassigned" folder for archives without a printer
  1141. printer_folder = str(printer_id) if printer_id is not None else "unassigned"
  1142. archive_dir = (
  1143. settings.archive_dir / printer_folder / archive_name
  1144. ) # SEC-PATH-OK: printer_folder = str(int|None) → digits or "unassigned"; archive_name = f"{timestamp}_{display_stem}" where resolve_display_stem strips path components via Path(filename).name
  1145. # Removed again if the row is not written (below); only a folder this
  1146. # call created, never another archive's of the same name.
  1147. created_archive_dir = not archive_dir.exists()
  1148. archive_dir.mkdir(parents=True, exist_ok=True)
  1149. # Copy 3MF file with an explicit fsync'd loop (avoids a sendfile
  1150. # short-read quirk that silently truncated 3MF archives on some
  1151. # platforms — see _copy_and_fsync and #1032).
  1152. dest_file = archive_dir / source_file.name
  1153. _copy_and_fsync(source_file, dest_file)
  1154. # If we just archived a 3MF, verify the dest is a valid ZIP before
  1155. # going any further. Staying quiet here is how #1032 escaped review —
  1156. # the archive row was written but every later zipfile.ZipFile() call
  1157. # on the dest failed with "File is not a zip file".
  1158. if (
  1159. source_file.suffix.lower() == ".3mf"
  1160. and zipfile.is_zipfile(source_file)
  1161. and not zipfile.is_zipfile(dest_file)
  1162. ):
  1163. try:
  1164. src_size = source_file.stat().st_size
  1165. dst_size = dest_file.stat().st_size
  1166. except OSError:
  1167. src_size = dst_size = -1
  1168. logger.error(
  1169. "Archive copy corrupted 3MF: src=%s (%s bytes, valid ZIP) -> dst=%s (%s bytes, NOT a ZIP). Refusing to create archive row.",
  1170. source_file,
  1171. src_size,
  1172. dest_file,
  1173. dst_size,
  1174. )
  1175. # Narrow cleanup: remove only the truncated file and the archive
  1176. # directory if it's now empty. archive_dir was created with
  1177. # exist_ok=True so it could in theory pre-date this call (e.g.
  1178. # same-second same-filename collision); rmtree would be too broad.
  1179. try:
  1180. dest_file.unlink()
  1181. except OSError:
  1182. pass
  1183. try:
  1184. archive_dir.rmdir()
  1185. except OSError:
  1186. pass # directory not empty — leave untouched
  1187. return None
  1188. # Compute content hash for duplicate detection
  1189. content_hash = self.compute_file_hash(dest_file)
  1190. # Extract plate number from filename (e.g., "plate_5" from "/data/Metadata/plate_5.gcode")
  1191. plate_number = None
  1192. if print_data:
  1193. filename = print_data.get("filename", "")
  1194. match = re.search(r"plate_(\d+)", filename)
  1195. if match:
  1196. plate_number = int(match.group(1))
  1197. # Parse 3MF metadata
  1198. parser = ThreeMFParser(dest_file, plate_number=plate_number)
  1199. metadata = parser.parse()
  1200. # Save thumbnail if present
  1201. thumbnail_path = None
  1202. if "_thumbnail_data" in metadata:
  1203. thumb_file = archive_dir / f"thumbnail{metadata['_thumbnail_ext']}"
  1204. thumb_file.write_bytes(metadata["_thumbnail_data"])
  1205. thumbnail_path = str(thumb_file.relative_to(settings.base_dir))
  1206. del metadata["_thumbnail_data"]
  1207. del metadata["_thumbnail_ext"]
  1208. # Merge with print data from MQTT
  1209. if print_data:
  1210. metadata["_print_data"] = print_data
  1211. # Promote the slicer's own live-resolved AMS-slot pick, when the caller
  1212. # explicitly opted in (see the `slicer_ams_mapping` param docstring for
  1213. # why this is NOT read off `print_data["ams_mapping"]`), to a stable
  1214. # top-level extra_data key. Lets a later reprint reuse the exact tray
  1215. # the user picked/BambuStudio auto-matched at slice time instead of the
  1216. # scheduler re-deriving one from just the file's static type/color,
  1217. # which can land on the wrong physical spool when that match isn't
  1218. # unique. Top-level (not nested under the `_print_data` diagnostic bag)
  1219. # so API consumers have a single stable path:
  1220. # `archive.extra_data.slicer_ams_mapping`. Stored together with the
  1221. # printer it was resolved against — see `slicer_ams_mapping_printer_id`
  1222. # param docstring — so a later reprint can tell whether it's even
  1223. # applicable before trying to reuse it.
  1224. if slicer_ams_mapping and slicer_ams_mapping_printer_id is not None:
  1225. metadata["slicer_ams_mapping"] = {
  1226. "mapping": slicer_ams_mapping,
  1227. "printer_id": slicer_ams_mapping_printer_id,
  1228. }
  1229. # Determine status and timestamps
  1230. status = print_data.get("status", "completed") if print_data else "archived"
  1231. started_at = datetime.now(timezone.utc) if status == "printing" else None
  1232. completed_at = datetime.now(timezone.utc) if status in ("completed", "failed", "archived") else None
  1233. # Calculate cost based on filament usage and type
  1234. cost = None
  1235. filament_grams = metadata.get("filament_used_grams")
  1236. filament_type = metadata.get("filament_type")
  1237. if filament_grams and filament_type:
  1238. # For multi-material prints, use the first filament type for cost calculation
  1239. primary_type = filament_type.split(",")[0].strip()
  1240. # Look up filament cost_per_kg from database
  1241. filament_result = await self.db.execute(select(Filament).where(Filament.type == primary_type).limit(1))
  1242. filament = filament_result.scalar_one_or_none()
  1243. if filament:
  1244. cost = round((filament_grams / 1000) * filament.cost_per_kg, 2)
  1245. else:
  1246. # Use default filament cost from settings
  1247. from backend.app.api.routes.settings import get_setting
  1248. default_cost_setting = await get_setting(self.db, "default_filament_cost")
  1249. default_cost_per_kg = float(default_cost_setting) if default_cost_setting else 25.0
  1250. cost = round((filament_grams / 1000) * default_cost_per_kg, 2)
  1251. # Calculate quantity from printable objects count
  1252. # printable_objects is a dict of {identify_id: name} for non-skipped objects
  1253. quantity = 1 # Default to 1
  1254. printable_objects = metadata.get("printable_objects")
  1255. if printable_objects and isinstance(printable_objects, dict):
  1256. quantity = len(printable_objects)
  1257. logger.debug("Auto-detected %s parts from 3MF printable objects", quantity)
  1258. # Recovery of an existing fallback row: assign the freshly-parsed values
  1259. # onto it rather than adding a second archive for the same print (#2957).
  1260. if update_archive_id is not None:
  1261. existing = await self.db.get(PrintArchive, update_archive_id)
  1262. if existing is None:
  1263. logger.warning("archive_print: archive %s to update no longer exists", update_archive_id)
  1264. return None
  1265. # `metadata` is freshly parsed from the 3MF, so assigning it drops
  1266. # the row's `no_3mf_available` / `no_3mf_reason` markers as a side
  1267. # effect — which is correct, the archive is no longer a fallback,
  1268. # and it is what stops the Archives banner counting it.
  1269. # `_print_data` is diagnostic history rather than something the 3MF
  1270. # knows about: keep the row's copy for a caller that passed no
  1271. # print_data of its own.
  1272. merged = dict(metadata)
  1273. preserved = (existing.extra_data or {}).get("_print_data")
  1274. if preserved is not None and "_print_data" not in merged:
  1275. merged["_print_data"] = preserved
  1276. # A record that this row started life without a 3MF, which the
  1277. # dropped markers no longer say.
  1278. merged["recovered_no_3mf"] = True
  1279. existing.filename = original_filename or source_file.name
  1280. existing.file_path = str(dest_file.relative_to(settings.base_dir))
  1281. existing.file_size = dest_file.stat().st_size
  1282. existing.content_hash = content_hash
  1283. existing.thumbnail_path = thumbnail_path
  1284. existing.print_name = (
  1285. clean_display_name(display_stem)
  1286. if prefer_filename_for_name
  1287. else (clean_display_name(metadata.get("print_name")) or clean_display_name(display_stem))
  1288. )
  1289. # Only overwrite what the 3MF actually knows. A fallback archive
  1290. # recovered mid-print has a real print_time_seconds from MQTT and a
  1291. # filament type/colour from the AMS; a 3MF that omits a field must
  1292. # not blank them back out.
  1293. for field in (
  1294. "print_time_seconds",
  1295. "filament_used_grams",
  1296. "filament_type",
  1297. "filament_color",
  1298. "layer_height",
  1299. "total_layers",
  1300. "nozzle_diameter",
  1301. "bed_temperature",
  1302. "bed_type",
  1303. "nozzle_temperature",
  1304. "sliced_for_model",
  1305. "makerworld_url",
  1306. "designer",
  1307. ):
  1308. value = metadata.get(field)
  1309. if value is not None:
  1310. setattr(existing, field, value)
  1311. if cost is not None:
  1312. existing.cost = cost
  1313. existing.quantity = quantity
  1314. existing.extra_data = merged
  1315. if plate_id is not None:
  1316. existing.plate_id = plate_id
  1317. if library_file_id is not None:
  1318. existing.library_file_id = library_file_id
  1319. await self.db.commit()
  1320. await self.db.refresh(existing)
  1321. return existing
  1322. # Create archive record
  1323. archive = PrintArchive(
  1324. printer_id=printer_id,
  1325. filename=original_filename or source_file.name,
  1326. file_path=str(dest_file.relative_to(settings.base_dir)),
  1327. file_size=dest_file.stat().st_size,
  1328. content_hash=content_hash,
  1329. thumbnail_path=thumbnail_path,
  1330. # clean_display_name because the 3MF's own metadata reaches this
  1331. # verbatim, and a control character in it renders nowhere and
  1332. # truncates somewhere (#2832). The schema does the same for names
  1333. # arriving over the API. Cleaned before the fallback rather than
  1334. # after it, so an embedded name that is only whitespace still falls
  1335. # through to the filename instead of leaving the archive nameless.
  1336. print_name=(
  1337. clean_display_name(display_stem)
  1338. if prefer_filename_for_name
  1339. else (clean_display_name(metadata.get("print_name")) or clean_display_name(display_stem))
  1340. ),
  1341. print_time_seconds=metadata.get("print_time_seconds"),
  1342. filament_used_grams=metadata.get("filament_used_grams"),
  1343. filament_type=metadata.get("filament_type"),
  1344. filament_color=metadata.get("filament_color"),
  1345. layer_height=metadata.get("layer_height"),
  1346. total_layers=metadata.get("total_layers"),
  1347. nozzle_diameter=metadata.get("nozzle_diameter"),
  1348. bed_temperature=metadata.get("bed_temperature"),
  1349. bed_type=metadata.get("bed_type"),
  1350. nozzle_temperature=metadata.get("nozzle_temperature"),
  1351. sliced_for_model=metadata.get("sliced_for_model"),
  1352. makerworld_url=metadata.get("makerworld_url"),
  1353. designer=metadata.get("designer"),
  1354. status=status,
  1355. started_at=started_at,
  1356. completed_at=completed_at,
  1357. cost=cost,
  1358. quantity=quantity,
  1359. extra_data=metadata,
  1360. created_by_id=created_by_id,
  1361. project_id=project_id,
  1362. library_file_id=library_file_id,
  1363. cost_center_id=cost_center_id,
  1364. subtask_id=subtask_id,
  1365. plate_id=plate_id,
  1366. )
  1367. self.db.add(archive)
  1368. try:
  1369. await self.db.commit()
  1370. except IntegrityError:
  1371. # Refused, so the row was not written (a printer deleted meanwhile,
  1372. # by its foreign key): the folder its files went into would be
  1373. # orphaned. Not on other errors: a connection lost during COMMIT may
  1374. # still have written the row, whose files these are.
  1375. if created_archive_dir:
  1376. shutil.rmtree(archive_dir, ignore_errors=True)
  1377. raise
  1378. await self.db.refresh(archive)
  1379. return archive
  1380. async def get_archive(self, archive_id: int) -> PrintArchive | None:
  1381. """Get an archive by ID with relationships loaded."""
  1382. from sqlalchemy.orm import selectinload
  1383. result = await self.db.execute(
  1384. select(PrintArchive)
  1385. .options(selectinload(PrintArchive.created_by), selectinload(PrintArchive.project))
  1386. .where(PrintArchive.id == archive_id)
  1387. )
  1388. return result.scalar_one_or_none()
  1389. async def update_archive_status(
  1390. self,
  1391. archive_id: int,
  1392. status: str,
  1393. completed_at: datetime | None = None,
  1394. failure_reason: str | None = None,
  1395. ) -> bool:
  1396. """Update the status of an archive."""
  1397. archive = await self.get_archive(archive_id)
  1398. if not archive:
  1399. return False
  1400. archive.status = status
  1401. if completed_at:
  1402. archive.completed_at = completed_at
  1403. if failure_reason:
  1404. archive.failure_reason = failure_reason
  1405. await self.db.commit()
  1406. return True
  1407. async def list_archives(
  1408. self,
  1409. printer_id: int | None = None,
  1410. project_id: int | None = None,
  1411. date_from: date | None = None,
  1412. date_to: date | None = None,
  1413. limit: int = 50,
  1414. offset: int = 0,
  1415. visible_to_user_id: int | None = None,
  1416. printer_scope: PrinterScope | None = None,
  1417. ) -> list[PrintArchive]:
  1418. """List archives with optional filtering.
  1419. ``visible_to_user_id`` scopes results to archives that user owns. Used
  1420. when the caller has ARCHIVES_READ_OWN but not ARCHIVES_READ_ALL — pass
  1421. ``None`` to skip the filter (caller has read-all or auth is disabled).
  1422. """
  1423. from sqlalchemy.orm import selectinload
  1424. query = (
  1425. select(PrintArchive)
  1426. .options(selectinload(PrintArchive.project), selectinload(PrintArchive.created_by))
  1427. # Hide soft-deleted rows from the listings (#1343). The stats
  1428. # endpoint deliberately does NOT add this filter so deleted
  1429. # archives keep contributing to Quick Stats.
  1430. .where(PrintArchive.deleted_at.is_(None))
  1431. .order_by(PrintArchive.created_at.desc())
  1432. )
  1433. if printer_id:
  1434. query = query.where(PrintArchive.printer_id == printer_id)
  1435. if project_id:
  1436. query = query.where(PrintArchive.project_id == project_id)
  1437. if date_from:
  1438. dt_from = datetime.combine(date_from, time.min, tzinfo=timezone.utc)
  1439. query = query.where(PrintArchive.created_at >= dt_from)
  1440. if date_to:
  1441. dt_to = datetime.combine(date_to, time.max, tzinfo=timezone.utc)
  1442. query = query.where(PrintArchive.created_at <= dt_to)
  1443. if visible_to_user_id is not None:
  1444. query = query.where(PrintArchive.created_by_id == visible_to_user_id)
  1445. # Only archives from printers the caller may see (#1727)
  1446. if printer_scope is not None and (clause := printer_scope.where(PrintArchive.printer_id)) is not None:
  1447. query = query.where(clause)
  1448. query = query.limit(limit).offset(offset)
  1449. result = await self.db.execute(query)
  1450. return list(result.scalars().all())
  1451. async def soft_delete_archive(self, archive_id: int) -> bool:
  1452. """Soft-delete an archive (#1343).
  1453. Removes the archive's files from disk (it disappears from the listings
  1454. and frees the storage) but flips the row's ``deleted_at`` so the stats
  1455. endpoint keeps counting its filament / energy / time / cost. The user
  1456. can opt into a hard delete via the "Also remove from statistics"
  1457. checkbox in the delete dialog — that path calls ``delete_archive``
  1458. instead and removes the row entirely.
  1459. """
  1460. archive = await self.get_archive(archive_id)
  1461. if not archive:
  1462. return False
  1463. if archive.deleted_at is not None:
  1464. # Already soft-deleted; nothing to do. The files were purged on
  1465. # the first soft-delete pass so there is nothing left on disk.
  1466. return True
  1467. dirs_to_delete = self._resolve_archive_dirs_for_delete(archive)
  1468. recorded_paths = (archive.timelapse_path, archive.thumbnail_path)
  1469. await _null_print_log_thumbnail_paths(self.db, archive_id)
  1470. await _delete_related_queue_items(self.db, archive_id)
  1471. archive.deleted_at = datetime.now(timezone.utc)
  1472. await self.db.commit()
  1473. for directory in dirs_to_delete:
  1474. shutil.rmtree(directory, ignore_errors=True)
  1475. self._purge_id_named_dir(archive_id, recorded_paths)
  1476. return True
  1477. def _resolve_archive_dirs_for_delete(self, archive: PrintArchive) -> list[Path]:
  1478. """Directories belonging to *archive* alone, safe to remove whole.
  1479. Shared by soft-delete and hard-delete so the two cannot drift apart
  1480. again — the previous helper said it was extracted for that reason, and
  1481. ``delete_archive`` was still doing its own copy of the same rules.
  1482. An archive with a 3MF owns the directory its ``file_path`` sits in,
  1483. ``<archive_dir>/<printer_id>/<timestamp>_<name>/``. Any archive may also
  1484. own ``archive/no_source/<id>/``, where a source 3MF uploaded onto a
  1485. no-3MF archive lands (#1531); that one was never removed, so deleting
  1486. such an archive freed the row and left the upload behind.
  1487. Two directories are deliberately absent. ``<base_dir>/photos`` is the
  1488. legacy location *every* no-3MF archive wrote into at once, so removing
  1489. it on one delete would take the others' photos with it. And
  1490. ``<archive_dir>/<id>`` — the directory :func:`resolve_archive_dir` gives
  1491. an archive with no ``file_path`` — is handled by
  1492. :meth:`_purge_id_named_dir` instead, for the reason given there.
  1493. """
  1494. candidates: list[Path] = []
  1495. # Only when there is a path to derive it from. Without one,
  1496. # ``resolve_archive_dir`` returns the id-named directory, which must not
  1497. # be removed wholesale -- see _purge_id_named_dir.
  1498. if archive.file_path and archive.file_path.strip():
  1499. candidates.append(resolve_archive_dir(archive))
  1500. candidates.append(settings.archive_dir / "no_source" / str(archive.id))
  1501. resolved: list[Path] = []
  1502. for candidate in candidates:
  1503. if candidate in resolved or not candidate.is_dir():
  1504. continue
  1505. try:
  1506. relative_path = candidate.resolve().relative_to(settings.archive_dir.resolve())
  1507. except ValueError:
  1508. # A genuine guard trip, unlike the empty ``file_path`` this used
  1509. # to shout about: the row points somewhere outside the archive
  1510. # tree, which only a corrupted import or hand-edited SQL can do.
  1511. logger.error(
  1512. f"SECURITY: Refusing to delete archive {archive.id} - "
  1513. f"path {candidate} is outside archive directory {settings.archive_dir}"
  1514. )
  1515. continue
  1516. # Two deep, not one. An archive directory has been
  1517. # ``<archive_dir>/<printer_id>/<timestamp>_<name>/`` since the first
  1518. # commit, so nothing legitimate sits one level down -- but the
  1519. # per-printer folder does, and it holds every print that printer
  1520. # ever made. Under the old ``< 1`` a row whose file_path had lost a
  1521. # path component took the whole folder with it.
  1522. if len(relative_path.parts) < 2:
  1523. logger.error(
  1524. f"SECURITY: Refusing to delete archive {archive.id} - "
  1525. f"path {candidate} is not deep enough inside archive directory"
  1526. )
  1527. continue
  1528. resolved.append(candidate)
  1529. return resolved
  1530. def _purge_id_named_dir(self, archive_id: int, recorded_paths: tuple[str | None, ...]) -> None:
  1531. """Remove one archive's own files from ``<archive_dir>/<id>``, carefully.
  1532. Takes the recorded paths rather than the row because ``delete_archive``
  1533. removes the row before it touches the disk, deliberately: a failed
  1534. commit must leave the files alone. Reading ``archive.timelapse_path``
  1535. off a deleted instance afterwards would raise or silently refresh.
  1536. That directory is where an archive with no 3MF keeps its timelapse and
  1537. its finish photos (:func:`resolve_archive_dir`). It is emphatically NOT
  1538. an ``rmtree`` target, because it shares a namespace with the per-printer
  1539. folders: a normal archive lives at
  1540. ``<archive_dir>/<printer_id>/<timestamp>_<name>/``, so ``archive/1`` is
  1541. printer 1's folder *and* the directory the helper hands archive id 1.
  1542. Archive ids and printer ids are both small integers from unrelated
  1543. sequences, so on any install the first few archives collide with the
  1544. printers. Removing the directory would take every print that printer
  1545. ever made — measured on a scratch tree before this guard existed.
  1546. So nothing is removed that has not been identified as this archive's.
  1547. ``photos`` is a fixed subdirectory name and an archive directory is
  1548. always ``<timestamp>_<name>``, so the two cannot be confused; the video
  1549. is removed by the path the row itself records. The directory then goes
  1550. only if that left it empty, which a printer folder holding prints never
  1551. will. Anything unrecognised keeps it alive and is leaked rather than
  1552. guessed at — the safe direction for a recursive delete.
  1553. """
  1554. directory = settings.archive_dir / str(archive_id)
  1555. if not directory.is_dir():
  1556. return
  1557. try:
  1558. relative_path = directory.resolve().relative_to(settings.archive_dir.resolve())
  1559. except ValueError:
  1560. return
  1561. if len(relative_path.parts) != 1:
  1562. return
  1563. shutil.rmtree(directory / "photos", ignore_errors=True) # SEC-PATH-OK: constant subdirectory
  1564. for recorded in recorded_paths:
  1565. if not recorded:
  1566. continue
  1567. try:
  1568. # Two checks, not one. safe_join_under rejects the absolute and
  1569. # ``..`` shapes and proves the result is inside the data
  1570. # directory; assert_under then narrows it to *this* archive's
  1571. # own directory, because a row whose timelapse_path names
  1572. # another archive's file must not take it with this delete.
  1573. # The column is written by Bambuddy from a filename the printer
  1574. # supplied over FTP, so it is not a trusted constant.
  1575. candidate = safe_join_under(settings.base_dir, recorded, http=False)
  1576. assert_under(directory, candidate, http=False)
  1577. except PathTraversalError:
  1578. continue
  1579. if candidate.is_file():
  1580. candidate.unlink(missing_ok=True)
  1581. try:
  1582. directory.rmdir()
  1583. except OSError:
  1584. # Not empty (a printer folder, or a file this archive did not
  1585. # record) or already gone. Both are fine: the point of rmdir over
  1586. # rmtree is that it cannot take anything with it.
  1587. pass
  1588. async def delete_archive(self, archive_id: int) -> bool:
  1589. """Delete an archive and its files."""
  1590. archive = await self.get_archive(archive_id)
  1591. if not archive:
  1592. return False
  1593. # Resolved BEFORE committing the DB change, since the row is what says
  1594. # where the files are. Shared with soft-delete rather than repeated
  1595. # here: this was a second copy of the same checks and it had already
  1596. # diverged from the one it was extracted from.
  1597. dirs_to_delete = self._resolve_archive_dirs_for_delete(archive)
  1598. recorded_paths = (archive.timelapse_path, archive.thumbnail_path)
  1599. # NULL stale thumbnail_path on linked PrintLogEntries before the FK
  1600. # SET-NULL cascade fires. The on-disk file is about to be removed by
  1601. # the rmtree below, so the path on any surviving log entry (archive_id
  1602. # gets SET NULL by the FK) would otherwise point at a missing file
  1603. # and produce 404 storms in the print-log view (#1348-followup).
  1604. await _null_print_log_thumbnail_paths(self.db, archive_id)
  1605. # Delete database record FIRST — if the commit fails (e.g. database locked
  1606. # during concurrent bulk deletes), the files stay on disk and nothing is lost.
  1607. await self.db.delete(archive)
  1608. await self.db.commit()
  1609. # Only delete files AFTER the DB commit succeeds to avoid orphaned records
  1610. for directory in dirs_to_delete:
  1611. shutil.rmtree(directory, ignore_errors=True)
  1612. self._purge_id_named_dir(archive_id, recorded_paths)
  1613. return True
  1614. async def attach_timelapse(
  1615. self,
  1616. archive_id: int,
  1617. timelapse_data: bytes,
  1618. filename: str = "timelapse.mp4",
  1619. *,
  1620. plate_id: int | None = None,
  1621. ) -> bool:
  1622. """Attach a timelapse video to an archive.
  1623. Non-MP4 videos (e.g. AVI from P1S) are saved as-is and a background
  1624. task converts them to MP4 for browser compatibility.
  1625. ``plate_id`` is the plate whose run produced the video, when the caller
  1626. knows it; print start uses it to tell a reprint from the next plate of
  1627. a shared archive (#3275).
  1628. """
  1629. import asyncio
  1630. archive = await self.get_archive(archive_id)
  1631. if not archive:
  1632. return False
  1633. # Where this archive's files live. Deliberately the shared helper: an
  1634. # archive created without a 3MF has ``file_path == ""``, and deriving the
  1635. # directory here as ``(base_dir / "").parent`` resolved to the parent of
  1636. # base_dir — outside the data directory entirely. In Docker that is /app,
  1637. # so the write failed with EACCES and the timelapse was retried and
  1638. # discarded 25 times; where the parent happens to be writable it
  1639. # succeeded, dropped a stray video next to the install, and then failed
  1640. # anyway on the relative_to() below. Every H2-series and P2S print sent
  1641. # from the slicer takes that path, because the file goes to internal
  1642. # storage and no 3MF can be fetched.
  1643. archive_dir = resolve_archive_dir(archive)
  1644. # Save timelapse - use thread pool to avoid blocking event loop
  1645. # (timelapse files can be 100MB+, sync write blocks for seconds).
  1646. # `filename` ultimately comes from a printer's FTP listing (compromised-
  1647. # printer threat model) or a query param on /archives/{id}/timelapse/select;
  1648. # the safe-join helper rejects ``..`` segments and absolute paths so a
  1649. # crafted name can't escape the archive directory. Use http=False so a
  1650. # service-layer reject surfaces as a return False (matching the existing
  1651. # not-found contract) rather than a 400 raised from inside a background
  1652. # task.
  1653. try:
  1654. timelapse_file = safe_join_under(archive_dir, filename, http=False)
  1655. except PathTraversalError:
  1656. logger.warning(
  1657. "Refusing to attach timelapse with unsafe filename %r to archive %s",
  1658. filename,
  1659. archive_id,
  1660. )
  1661. return False
  1662. # Created only once the name has been vetted, so a rejected filename
  1663. # leaves nothing behind. A no-3MF archive has never had a directory of
  1664. # its own, and the timelapse can be the first thing to want one.
  1665. await asyncio.to_thread(lambda: timelapse_file.parent.mkdir(parents=True, exist_ok=True))
  1666. # A file of this name that the archive no longer points at is an earlier
  1667. # run's video, kept because another plate of a shared archive started
  1668. # (#3275). Writing over it would destroy the copy that was kept: the
  1669. # external-camera stitch always names its output layer_timelapse.mp4.
  1670. # Re-attaching the file the archive does point at still replaces it.
  1671. timelapse_file = await asyncio.to_thread(
  1672. _free_timelapse_name, timelapse_file, archive.timelapse_path, settings.base_dir
  1673. )
  1674. await asyncio.to_thread(timelapse_file.write_bytes, timelapse_data)
  1675. # Update archive record
  1676. archive.timelapse_path = str(timelapse_file.relative_to(settings.base_dir))
  1677. archive.timelapse_plate_id = plate_id
  1678. await self.db.commit()
  1679. # For non-MP4 videos (e.g. AVI from P1S), kick off background conversion
  1680. if not filename.lower().endswith(".mp4"):
  1681. spawn_background_task(
  1682. _convert_timelapse_to_mp4(archive_id, timelapse_file),
  1683. name=f"timelapse-convert-{archive_id}",
  1684. )
  1685. return True
  1686. def _free_timelapse_name(target: Path, current_relpath: str | None, base_dir: Path) -> Path:
  1687. """``target``, or ``<stem>_<n><suffix>`` beside it when ``target`` would
  1688. replace a video the archive does not point at (see ``attach_timelapse``).
  1689. A non-MP4 is converted to ``<stem>.mp4`` afterwards, so that name counts as
  1690. taken too.
  1691. """
  1692. def outputs(path: Path) -> set[Path]:
  1693. return {path.resolve(), path.with_suffix(".mp4").resolve()}
  1694. # Only compared against ``target``, which attach_timelapse has already
  1695. # safe-joined; nothing is read or written through this path.
  1696. current = (base_dir / current_relpath).resolve() if current_relpath else None # SEC-PATH-OK: comparison only
  1697. taken = {p for p in outputs(target) if p.exists()}
  1698. if not taken or current in taken:
  1699. return target
  1700. n = 2
  1701. while True:
  1702. candidate = target.with_name(f"{target.stem}_{n}{target.suffix}")
  1703. if not any(p.exists() for p in outputs(candidate)):
  1704. return candidate
  1705. n += 1
  1706. async def _convert_timelapse_to_mp4(archive_id: int, source_path: Path) -> None:
  1707. """Background task: convert non-MP4 timelapse (e.g. AVI from P1S) to MP4.
  1708. Runs with low CPU priority (-threads 1, nice) so it doesn't starve
  1709. other processes on resource-constrained devices like Raspberry Pi.
  1710. """
  1711. import asyncio
  1712. from backend.app.core.database import async_session
  1713. from backend.app.services.camera import get_ffmpeg_path
  1714. logger = logging.getLogger(__name__)
  1715. ffmpeg = get_ffmpeg_path()
  1716. if not ffmpeg:
  1717. logger.info(
  1718. "FFmpeg not available, skipping timelapse conversion for archive %s (file saved as %s)",
  1719. archive_id,
  1720. source_path.suffix,
  1721. )
  1722. return
  1723. mp4_path = source_path.with_suffix(".mp4")
  1724. try:
  1725. cmd = [
  1726. ffmpeg,
  1727. "-y",
  1728. "-i",
  1729. str(source_path),
  1730. "-c:v",
  1731. "libx264",
  1732. "-preset",
  1733. "fast",
  1734. "-crf",
  1735. "23",
  1736. "-threads",
  1737. "1",
  1738. "-movflags",
  1739. "+faststart",
  1740. str(mp4_path),
  1741. ]
  1742. # Try with nice for lower CPU priority (standard on Linux/macOS)
  1743. try:
  1744. process = await asyncio.create_subprocess_exec(
  1745. "nice",
  1746. "-n",
  1747. "19",
  1748. *cmd,
  1749. stdout=asyncio.subprocess.PIPE,
  1750. stderr=asyncio.subprocess.PIPE,
  1751. )
  1752. except FileNotFoundError:
  1753. # nice not available (e.g. Windows), run without
  1754. process = await asyncio.create_subprocess_exec(
  1755. *cmd,
  1756. stdout=asyncio.subprocess.PIPE,
  1757. stderr=asyncio.subprocess.PIPE,
  1758. )
  1759. _, stderr = await process.communicate()
  1760. if process.returncode != 0:
  1761. logger.warning(
  1762. "Timelapse conversion failed for archive %s: %s",
  1763. archive_id,
  1764. summarize_ffmpeg_stderr(stderr) or NO_FFMPEG_OUTPUT,
  1765. )
  1766. if mp4_path.exists():
  1767. mp4_path.unlink()
  1768. return
  1769. # Update DB path to the new MP4 file
  1770. async with async_session() as db:
  1771. from backend.app.models.archive import PrintArchive
  1772. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1773. archive = result.scalar_one_or_none()
  1774. if archive:
  1775. archive.timelapse_path = str(mp4_path.relative_to(settings.base_dir))
  1776. await db.commit()
  1777. # Remove original non-MP4 file
  1778. if source_path.exists():
  1779. source_path.unlink()
  1780. logger.info(
  1781. "Converted timelapse to MP4 for archive %s (%s → %s)",
  1782. archive_id,
  1783. source_path.name,
  1784. mp4_path.name,
  1785. )
  1786. except Exception as e:
  1787. logger.warning("Timelapse conversion error for archive %s: %s", archive_id, e)
  1788. if mp4_path.exists():
  1789. mp4_path.unlink()