archive.py 96 KB

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