archive.py 97 KB

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