archive.py 92 KB

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