archive.py 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955
  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.filename import clean_display_name
  21. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  22. logger = logging.getLogger(__name__)
  23. # Bed temperature is not one key in a BambuStudio project. Every plate type has
  24. # its own per-filament array, and the plate actually fitted is named separately
  25. # in ``curr_bed_type`` -- so reading a bed temperature means picking the array
  26. # the plate points at. Keys and mapping are BambuStudio's own
  27. # ``get_bed_temp_1st_layer_key`` / ``get_bed_temp_key`` (PrintConfig.hpp), and
  28. # the plate names are the ``curr_bed_type`` enum values (PrintConfig.cpp).
  29. # First-layer temperature first: that is what the printer heats to before the
  30. # print starts, which is what preheat is trying to reach.
  31. #
  32. # ``Default Plate`` is deliberately absent -- BambuStudio maps it to no key at
  33. # all, so there is nothing to read and guessing a plate would invent a bed
  34. # temperature the slice never specified.
  35. _BED_TEMP_KEYS: dict[str, tuple[str, str]] = {
  36. "Cool Plate": ("cool_plate_temp_initial_layer", "cool_plate_temp"),
  37. "Engineering Plate": ("eng_plate_temp_initial_layer", "eng_plate_temp"),
  38. "High Temp Plate": ("hot_plate_temp_initial_layer", "hot_plate_temp"),
  39. "Textured PEI Plate": ("textured_plate_temp_initial_layer", "textured_plate_temp"),
  40. "Supertack Plate": ("supertack_plate_temp_initial_layer", "supertack_plate_temp"),
  41. }
  42. # Fallback for a config that names no plate: the Orca/PrusaSlicer spelling,
  43. # which is a single value rather than a per-plate array.
  44. _GENERIC_BED_TEMP_KEYS = ("bed_temperature_initial_layer", "bed_temperature")
  45. def _plate_temperature(val) -> int | None:
  46. """Bed temperature from one plate-temperature entry, or None.
  47. The plate arrays carry one entry per filament in the project, and a 0 means
  48. that filament cannot print on this plate. The bed only has one temperature,
  49. so the print runs at the highest its filaments ask for -- taking entry 0 the
  50. way the neighbouring scalar settings do would store a 0 for any project
  51. whose first filament is not one this plate is heated for.
  52. """
  53. values = val if isinstance(val, list) else [val]
  54. temps = []
  55. for entry in values:
  56. if isinstance(entry, bool) or not isinstance(entry, (int, float, str)):
  57. continue
  58. try:
  59. temps.append(int(float(entry)))
  60. except (TypeError, ValueError):
  61. continue
  62. return max(temps) if temps else None
  63. def _copy_and_fsync(src: Path, dst: Path, chunk_size: int = 1024 * 1024) -> None:
  64. """Copy src to dst with an explicit chunked read/write and fsync the dst.
  65. Replacement for shutil.copy2 in the archive pipeline. shutil.copy2 uses
  66. Linux sendfile(), which on some kernels/filesystems has returned a short
  67. count on the first call and truncated the destination for larger 3MF
  68. uploads (#1032, observed on Raspberry Pi OS bookworm / armv7l). An
  69. explicit loop with fsync avoids that path and guarantees the dest bytes
  70. are on disk before the caller inspects them as a ZIP.
  71. """
  72. with src.open("rb") as rf, dst.open("wb") as wf:
  73. while True:
  74. buf = rf.read(chunk_size)
  75. if not buf:
  76. break
  77. wf.write(buf)
  78. wf.flush()
  79. os.fsync(wf.fileno())
  80. shutil.copystat(src, dst)
  81. def resolve_display_stem(filename: str) -> str:
  82. """Return a clean human-readable stem from a 3MF/gcode filename.
  83. Bambu Studio's "Send to printer" dialog typically writes files like
  84. ``Plate_1.gcode.3mf`` (a sliced gcode payload wrapped in a 3MF container).
  85. The naive ``Path(filename).stem`` only drops the last suffix, leaving
  86. ``Plate_1.gcode`` — which then surfaces in the archive UI as a confusing
  87. ``Plate_1.gcode`` rather than ``Plate_1`` (#1152 follow-up).
  88. Strip the recognised print-format suffixes in order:
  89. - ``.gcode.3mf`` → bare stem (Bambu Studio FTP send)
  90. - ``.3mf`` → bare stem
  91. - ``.gcode`` → bare stem (rare standalone gcode upload)
  92. Anything else passes through unchanged.
  93. """
  94. name = Path(filename).name # drop any path components
  95. lower = name.lower()
  96. for suffix in (".gcode.3mf", ".3mf", ".gcode"):
  97. if lower.endswith(suffix):
  98. return name[: -len(suffix)]
  99. return Path(name).stem
  100. def _read_plate_index(plate) -> int | None:
  101. """Return the 1-based index of a ``slice_info.config`` ``<plate>`` element, or None.
  102. Bambu Studio and OrcaSlicer record it as a ``<metadata key="index"
  103. value="N"/>`` child — there is no ``plate_idx`` attribute on ``<plate>``
  104. itself, so an XPath predicate on one never matches (#2522).
  105. """
  106. for meta in plate.findall("metadata"):
  107. if meta.get("key") == "index":
  108. value = meta.get("value")
  109. if not value:
  110. return None
  111. try:
  112. return int(value)
  113. except ValueError:
  114. return None
  115. return None
  116. def peek_plate_index_in_3mf(file_path: Path) -> int | None:
  117. """Return the plate index a single-plate Bambu 3MF represents, or None.
  118. Reads only ``Metadata/slice_info.config`` to keep this cheap — used by
  119. the print-start callback to verify that the 3MF we just downloaded over
  120. FTP actually matches the plate the printer is running (#1204). The full
  121. ThreeMFParser does much more work and runs later inside ArchiveService.
  122. An all-plates export carries every plate, so "which plate is this file"
  123. has no answer; returning None there keeps the #1204 guard from reading
  124. plate 1 out of such a file, declaring a mismatch against the plate that
  125. is really running, and discarding a perfectly good 3MF (#2522).
  126. """
  127. try:
  128. with zipfile.ZipFile(file_path, "r") as zf:
  129. if "Metadata/slice_info.config" not in zf.namelist():
  130. return None
  131. content = zf.read("Metadata/slice_info.config").decode()
  132. root = ET.fromstring(content)
  133. plates = root.findall(".//plate")
  134. if len(plates) != 1:
  135. return None
  136. return _read_plate_index(plates[0])
  137. except Exception:
  138. return None
  139. _PLATE_SUFFIX_RE = re.compile(r"^(.*?)(\s*-\s*Plate\s+|_plate_)(\d+)$", re.IGNORECASE)
  140. def swap_plate_suffix(name: str | None, target_plate: int) -> str | None:
  141. """Return ``name`` with its trailing plate number replaced, or None.
  142. Bambu Studio names multi-plate uploads ``"<Project> - Plate <N>"`` (and
  143. a lowercase ``"_plate_<N>"`` variant exists too — see
  144. test_print_start_expected_promotion). When MQTT subtask_name lags
  145. across consecutive plates of the same model (#1204) the suffix points
  146. at the previous plate; swapping it gives us the correct upload to
  147. re-fetch from FTP. Returns None if no recognised suffix is present.
  148. """
  149. if not name:
  150. return None
  151. m = _PLATE_SUFFIX_RE.match(name)
  152. if not m:
  153. return None
  154. base, separator, _ = m.groups()
  155. return f"{base}{separator}{target_plate}"
  156. # How much of a plate's G-code to scan for header/config values. The header
  157. # block ends in the first kilobyte; the CONFIG_BLOCK that follows it carries
  158. # layer_height 14-25KB in (measured across the sliced 3MFs on hand, Bambu
  159. # Studio and OrcaSlicer alike), so 4KB — what this used to read — could only
  160. # ever see the header.
  161. _GCODE_SCAN_BYTES = 64 * 1024
  162. class ThreeMFParser:
  163. """Parser for Bambu Lab 3MF files."""
  164. def __init__(self, file_path: Path, plate_number: int | None = None):
  165. self.file_path = file_path
  166. self.plate_number = plate_number # Which plate was printed (1, 2, 3, etc.)
  167. self.metadata: dict = {}
  168. def parse(self) -> dict:
  169. """Extract metadata from 3MF file."""
  170. try:
  171. with zipfile.ZipFile(self.file_path, "r") as zf:
  172. self._parse_slice_info(zf) # Now sets self.plate_number from slice_info
  173. self._parse_project_settings(zf)
  174. self._parse_gcode_header(zf)
  175. self._parse_3dmodel(zf)
  176. self._extract_thumbnail(zf) # Uses correct plate_number for thumbnail
  177. # Enhance print_name with plate info if this is a multi-plate export
  178. plate_index = self.metadata.get("_plate_index")
  179. if plate_index and plate_index > 1:
  180. # Append plate number to distinguish from other plates
  181. existing_name = self.metadata.get("print_name", "")
  182. if existing_name and f"Plate {plate_index}" not in existing_name:
  183. self.metadata["print_name"] = f"{existing_name} - Plate {plate_index}"
  184. # ALWAYS prefer slice_info values - they contain ONLY filaments actually used in print
  185. # project_settings contains ALL configured filaments (AMS slots), not just used ones
  186. if self.metadata.get("_slice_filament_type"):
  187. self.metadata["filament_type"] = self.metadata["_slice_filament_type"]
  188. if self.metadata.get("_slice_filament_color"):
  189. self.metadata["filament_color"] = self.metadata["_slice_filament_color"]
  190. # Clean up internal keys
  191. self.metadata.pop("_slice_filament_type", None)
  192. self.metadata.pop("_slice_filament_color", None)
  193. self.metadata.pop("_plate_index", None)
  194. except Exception as e:
  195. # Return whatever metadata was extracted before the error, but
  196. # surface the failure so corrupted / truncated 3MF archives are
  197. # visible in support bundles (#1032).
  198. logger.warning(
  199. "ThreeMFParser: failed to parse %s: %s(%s) — returning partial metadata",
  200. self.file_path,
  201. type(e).__name__,
  202. e,
  203. )
  204. return self.metadata
  205. def _parse_slice_info(self, zf: zipfile.ZipFile):
  206. """Parse slice_info.config for print settings and printable objects."""
  207. try:
  208. if "Metadata/slice_info.config" in zf.namelist():
  209. content = zf.read("Metadata/slice_info.config").decode()
  210. root = ET.fromstring(content)
  211. # Extract printer_model_id from plate metadata
  212. # Format: <plate><metadata key="printer_model_id" value="C11" /></plate>
  213. for meta in root.findall(".//metadata"):
  214. key = meta.get("key")
  215. value = meta.get("value")
  216. if key == "printer_model_id" and value:
  217. from backend.app.utils.printer_models import normalize_printer_model_id
  218. normalized = normalize_printer_model_id(value)
  219. if normalized:
  220. self.metadata["sliced_for_model"] = normalized
  221. break
  222. # Loop every <plate> so multi-plate exports get summed file-level
  223. # totals. Pre-fix, this used `root.find(".//plate")` which
  224. # returned only the first plate — file-level `print_time_seconds`
  225. # / `filament_used_grams` reflected plate 1 alone, and the
  226. # archive card / project rollup under-reported by the number
  227. # of plates (#1593). Per-plate breakdown is still served by
  228. # the dedicated `/plates` endpoint.
  229. plates = root.findall(".//plate")
  230. summed_time = 0
  231. summed_grams = 0.0
  232. any_time_seen = False
  233. any_grams_seen = False
  234. for plate in plates:
  235. # Plate-level fields that only make sense at the file
  236. # level when there's exactly one plate. ``plate_number``
  237. # / ``_plate_index`` describe which plate the export
  238. # represents — meaningless for an all-plates 3MF, so we
  239. # only record them in the single-plate case. ``bed_type``
  240. # is also single-valued; we take the first plate's value
  241. # as a best-effort default for the archive metadata.
  242. plate_index_value: int | None = None
  243. for meta in plate.findall("metadata"):
  244. key = meta.get("key")
  245. value = meta.get("value")
  246. if key == "index" and value:
  247. try:
  248. plate_index_value = int(value)
  249. except ValueError:
  250. pass # Skip non-numeric plate index
  251. elif key == "prediction" and value:
  252. try:
  253. summed_time += int(value)
  254. any_time_seen = True
  255. except ValueError:
  256. pass
  257. elif key == "weight" and value:
  258. try:
  259. summed_grams += float(value)
  260. any_grams_seen = True
  261. except ValueError:
  262. pass
  263. elif key == "curr_bed_type" and value and "bed_type" not in self.metadata:
  264. self.metadata["bed_type"] = value
  265. # Per-plate object lists are only kept at the file level
  266. # when there's one plate — the skip-object affordance
  267. # operates on the plate being printed, which is the
  268. # `/plates` endpoint's job for multi-plate exports.
  269. if len(plates) == 1:
  270. if plate_index_value is not None:
  271. if not self.plate_number:
  272. self.plate_number = plate_index_value
  273. self.metadata["_plate_index"] = plate_index_value
  274. printable_objects: dict[int, str] = {}
  275. for obj in plate.findall("object"):
  276. identify_id = obj.get("identify_id")
  277. name = obj.get("name")
  278. skipped = obj.get("skipped", "false")
  279. if identify_id and name and skipped.lower() != "true":
  280. try:
  281. printable_objects[int(identify_id)] = name
  282. except ValueError:
  283. pass # Skip objects with non-numeric identify_id
  284. if printable_objects:
  285. self.metadata["printable_objects"] = printable_objects
  286. if any_time_seen:
  287. self.metadata["print_time_seconds"] = summed_time
  288. if any_grams_seen:
  289. self.metadata["filament_used_grams"] = round(summed_grams, 2)
  290. # Get filament info from filaments ACTUALLY USED in the print
  291. # slice_info has <filament id="1" type="PLA" color="#FFFFFF" used_g="100" />
  292. # Only include filaments where used_g > 0
  293. filaments = root.findall(".//filament")
  294. if filaments:
  295. # Collect unique filament types and colors for filaments that are actually used
  296. types = []
  297. colors = []
  298. for f in filaments:
  299. # Check if this filament is actually used in the print
  300. used_g = f.get("used_g", "0")
  301. try:
  302. used_amount = float(used_g)
  303. except (ValueError, TypeError):
  304. used_amount = 0
  305. # Only include if used_g > 0 (filament is actually consumed)
  306. if used_amount > 0:
  307. ftype = f.get("type")
  308. fcolor = f.get("color")
  309. if ftype and ftype not in types:
  310. types.append(ftype)
  311. if fcolor and fcolor not in colors:
  312. colors.append(fcolor)
  313. if types:
  314. self.metadata["_slice_filament_type"] = ", ".join(types)
  315. if colors:
  316. self.metadata["_slice_filament_color"] = ",".join(colors)
  317. # Collect per-slot filament usage for tracking & notifications
  318. filament_slots = []
  319. for f in filaments:
  320. slot_id = f.get("id")
  321. used_g_str = f.get("used_g", "0")
  322. try:
  323. used_g = float(used_g_str)
  324. except (ValueError, TypeError):
  325. used_g = 0
  326. if used_g > 0 and slot_id:
  327. filament_slots.append(
  328. {
  329. "slot_id": int(slot_id),
  330. "used_g": round(used_g, 2),
  331. "type": f.get("type", ""),
  332. "color": f.get("color", ""),
  333. }
  334. )
  335. if filament_slots:
  336. self.metadata["filament_slots"] = filament_slots
  337. except Exception:
  338. pass # Skip unparseable slice_info metadata
  339. def _parse_project_settings(self, zf: zipfile.ZipFile):
  340. """Parse project settings for print configuration."""
  341. try:
  342. if "Metadata/project_settings.config" in zf.namelist():
  343. content = zf.read("Metadata/project_settings.config").decode()
  344. try:
  345. data = json.loads(content)
  346. self._extract_filament_info(data)
  347. self._extract_print_settings(data)
  348. except json.JSONDecodeError:
  349. pass # Skip malformed project_settings JSON
  350. except Exception:
  351. pass # Skip unreadable project settings file
  352. def _printed_plate_gcode(self, gcode_files: list[str]) -> str:
  353. """Return the G-code entry for the plate this archive is about.
  354. ``plate_number`` is known for a plate-specific export (slice_info sets
  355. it) and picking blindly is wrong there: a project sliced with plate 2
  356. at 0.08 and plate 1 at 0.2 would otherwise report plate 1's numbers.
  357. Falls back to the lowest plate index, then to zip order, so a file
  358. whose entries are named some other way still parses as it did before.
  359. """
  360. if self.plate_number:
  361. wanted = f"Metadata/plate_{self.plate_number}.gcode"
  362. if wanted in gcode_files:
  363. return wanted
  364. def plate_index(name: str) -> int:
  365. match = re.search(r"plate_(\d+)\.gcode$", name)
  366. return int(match.group(1)) if match else 10**6
  367. return min(gcode_files, key=lambda name: (plate_index(name), gcode_files.index(name)))
  368. def _parse_gcode_header(self, zf: zipfile.ZipFile):
  369. """Parse the printed plate's G-code for what only it can settle.
  370. The plate's own G-code is the file the printer executes, so where it
  371. disagrees with ``project_settings.config`` — the *project's* record,
  372. which a multi-plate or per-plate-modified export can leave describing
  373. a different plate entirely — the G-code wins.
  374. """
  375. try:
  376. gcode_files = [f for f in zf.namelist() if f.endswith(".gcode")]
  377. if not gcode_files:
  378. return
  379. gcode_path = self._printed_plate_gcode(gcode_files)
  380. # 64KB, not 4KB: the header block ends within the first kilobyte,
  381. # but the CONFIG_BLOCK that carries layer_height starts right after
  382. # it and the keys are alphabetical, so layer_height lands 14-25KB
  383. # in on real files. The read is decompress-on-demand, so the cost
  384. # of the wider window is a few tens of KB per archived file.
  385. with zf.open(gcode_path) as f:
  386. header = f.read(_GCODE_SCAN_BYTES).decode("utf-8", errors="ignore")
  387. # Look for "; total layer number: XX" pattern
  388. match = re.search(r";\s*total\s+layer\s+number[:\s]+(\d+)", header, re.IGNORECASE)
  389. if match:
  390. self.metadata["total_layers"] = int(match.group(1))
  391. # Layer height, overriding project_settings.config when both are
  392. # present. The project config records the project's settings and can
  393. # describe a plate other than this one; the plate's G-code is what
  394. # the printer executes, so it decides. Anchored to the line start so keys ending in
  395. # "layer_height" (independent_support_layer_height) can't match.
  396. match = re.search(r"^;\s*layer_height\s*=\s*([\d.]+)\s*$", header, re.IGNORECASE | re.MULTILINE)
  397. if match:
  398. try:
  399. self.metadata["layer_height"] = float(match.group(1))
  400. except ValueError:
  401. pass # Malformed value: keep whatever project_settings gave us
  402. # Total filament usage. The slicer writes the print's totals into
  403. # the G-code header ("; total filament weight [g] : 126.26"). Only
  404. # a fallback — slice_info.config is more authoritative when present
  405. # — but it covers sliced outputs whose slice_info lacks per-filament
  406. # used_g, and it's the slicer's own figure regardless.
  407. if "filament_used_grams" not in self.metadata:
  408. match = re.search(r";\s*total\s+filament\s+weight\s*\[g\]\s*:\s*([\d.]+)", header, re.IGNORECASE)
  409. if match:
  410. self.metadata["filament_used_grams"] = float(match.group(1))
  411. if "filament_used_mm" not in self.metadata:
  412. match = re.search(r";\s*total\s+filament\s+length\s*\[mm\]\s*:\s*([\d.]+)", header, re.IGNORECASE)
  413. if match:
  414. self.metadata["filament_used_mm"] = float(match.group(1))
  415. # Look for printer_model in gcode header (fallback if not found in slice_info)
  416. # Format: "; printer_model = Bambu Lab X1 Carbon" or "; printer_model = X1C"
  417. if "sliced_for_model" not in self.metadata:
  418. match = re.search(r";\s*printer_model\s*=\s*(.+)", header, re.IGNORECASE)
  419. if match:
  420. from backend.app.utils.printer_models import normalize_printer_model
  421. raw_model = match.group(1).strip()
  422. self.metadata["sliced_for_model"] = normalize_printer_model(raw_model)
  423. except Exception:
  424. pass # G-code header parsing is best-effort; metadata may come from other sources
  425. def _extract_filament_info(self, data: dict):
  426. """Extract filament info from project settings — includes support
  427. materials so a PLA-model / PVA-support project shows both on the
  428. archive card badge (#1881).
  429. Earlier code filtered by ``filament_is_support``; that hid PVA
  430. (and any other soluble/breakaway support material) from the card
  431. even when the user had explicitly configured it, and made source
  432. 3MFs look single-material until the print completed. slice_info
  433. (parsed separately) is still preferred when present — it lists
  434. only filaments the print actually consumes, this fallback only
  435. runs on unsliced source 3MFs.
  436. """
  437. try:
  438. filament_types = data.get("filament_type", [])
  439. filament_colors = data.get("filament_colour", [])
  440. if not filament_types:
  441. return
  442. unique_types: list[str] = []
  443. for ftype in filament_types:
  444. if ftype and ftype not in unique_types:
  445. unique_types.append(ftype)
  446. unique_colors: list[str] = []
  447. for color in filament_colors:
  448. if color and color not in unique_colors:
  449. unique_colors.append(color)
  450. if unique_types:
  451. self.metadata["filament_type"] = ", ".join(unique_types)
  452. if unique_colors:
  453. self.metadata["filament_color"] = ",".join(unique_colors)
  454. except Exception:
  455. pass # Filament info is optional; fall back to slice_info values
  456. def _extract_print_settings(self, data: dict):
  457. """Extract print settings from JSON config."""
  458. try:
  459. # Layer height - usually an array, get first value
  460. if "layer_height" in data:
  461. val = data["layer_height"]
  462. if isinstance(val, list) and val:
  463. self.metadata["layer_height"] = float(val[0])
  464. elif isinstance(val, (int, float, str)):
  465. self.metadata["layer_height"] = float(val)
  466. # Nozzle diameter
  467. if "nozzle_diameter" in data:
  468. val = data["nozzle_diameter"]
  469. if isinstance(val, list) and val:
  470. self.metadata["nozzle_diameter"] = float(val[0])
  471. elif isinstance(val, (int, float, str)):
  472. self.metadata["nozzle_diameter"] = float(val)
  473. # Bed temperature, for the plate this project is sliced for. This
  474. # used to look for `bed_temperature` alone, a key BambuStudio does
  475. # not write -- so every archive from a Bambu slice stored NULL, and
  476. # preheat fell back to a configured bed temperature on every job
  477. # (#2989). Orca-exported 3MFs keep working through the generic keys.
  478. bed_type = str(data.get("curr_bed_type") or "").strip()
  479. for key in (*_BED_TEMP_KEYS.get(bed_type, ()), *_GENERIC_BED_TEMP_KEYS):
  480. if key not in data:
  481. continue
  482. temperature = _plate_temperature(data[key])
  483. # A plate array of all zeros means no filament in the project
  484. # prints on this plate, which is not a bed temperature -- keep
  485. # looking rather than recording a 0 that reads as "cold bed".
  486. if temperature:
  487. self.metadata["bed_temperature"] = temperature
  488. break
  489. # Nozzle temperature
  490. for key in ["nozzle_temperature_initial_layer", "nozzle_temperature"]:
  491. if key in data:
  492. val = data[key]
  493. if isinstance(val, list) and val:
  494. self.metadata["nozzle_temperature"] = int(float(val[0]))
  495. elif isinstance(val, (int, float, str)):
  496. self.metadata["nozzle_temperature"] = int(float(val))
  497. break
  498. # Printer model (extract and normalize)
  499. if "printer_model" in data:
  500. from backend.app.utils.printer_models import normalize_printer_model
  501. self.metadata["sliced_for_model"] = normalize_printer_model(data["printer_model"])
  502. # Build plate type — only set from project_settings if slice_info didn't already
  503. # provide it (slice_info is more authoritative as it reflects the exported plate).
  504. if "bed_type" not in self.metadata and "curr_bed_type" in data:
  505. val = data["curr_bed_type"]
  506. if isinstance(val, str) and val.strip():
  507. self.metadata["bed_type"] = val.strip()
  508. except Exception:
  509. pass # Print settings are optional; missing values are left unset
  510. def _extract_settings_from_content(self, content: str):
  511. """Extract print settings from config content."""
  512. settings_map = {
  513. "layer_height": ("layer_height", float),
  514. "nozzle_diameter": ("nozzle_diameter", float),
  515. "bed_temperature": ("bed_temperature", int),
  516. "nozzle_temperature": ("nozzle_temperature", int),
  517. }
  518. for key, (search_key, converter) in settings_map.items():
  519. if key not in self.metadata:
  520. try:
  521. # Try JSON format
  522. if f'"{search_key}"' in content:
  523. start = content.find(f'"{search_key}"')
  524. value_start = content.find(":", start) + 1
  525. value_end = content.find(",", value_start)
  526. if value_end == -1:
  527. value_end = content.find("}", value_start)
  528. value = content[value_start:value_end].strip().strip('"')
  529. self.metadata[key] = converter(value)
  530. except (ValueError, TypeError):
  531. pass # Skip settings with unconvertible values
  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 = zf.read(model_path).decode("utf-8", errors="ignore")
  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 = zf.read(model_path).decode("utf-8", errors="ignore")
  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(self) -> tuple[set[str], set[tuple[str, str]]]:
  971. """Get all content hashes and (print name, hash) pairs that appear more than once.
  972. For hashes: returns all hashes with > 1 archive (true duplicates).
  973. For name/hash pairs: returns only pairs that have > 1 archive
  974. (i.e., same file archived multiple times, not different files with same name).
  975. Returns a tuple of (duplicate_hashes, duplicate_name_hash_pairs).
  976. """
  977. from sqlalchemy import func
  978. # Soft-deleted archives don't appear in the listing (#1343), so they
  979. # mustn't influence the duplicate-group counts either — otherwise a
  980. # group with 1 live + 4 soft-deleted would still be flagged as a
  981. # duplicate even though the user only sees one row.
  982. result = await self.db.execute(
  983. select(PrintArchive.content_hash)
  984. .where(PrintArchive.content_hash.isnot(None), PrintArchive.deleted_at.is_(None))
  985. .group_by(PrintArchive.content_hash)
  986. .having(func.count(PrintArchive.id) > 1)
  987. )
  988. duplicate_hashes = {row[0] for row in result.all()}
  989. # Find print names that have multiple archives with the SAME hash
  990. # This avoids marking different files with the same name as duplicates
  991. result = await self.db.execute(
  992. select(func.lower(PrintArchive.print_name), PrintArchive.content_hash)
  993. .where(
  994. PrintArchive.print_name.isnot(None),
  995. PrintArchive.content_hash.isnot(None),
  996. PrintArchive.deleted_at.is_(None),
  997. )
  998. .group_by(func.lower(PrintArchive.print_name), PrintArchive.content_hash)
  999. .having(func.count(PrintArchive.id) > 1)
  1000. )
  1001. duplicate_name_hash_pairs = {(row[0], row[1]) for row in result.all()}
  1002. return duplicate_hashes, duplicate_name_hash_pairs
  1003. async def find_duplicates(
  1004. self,
  1005. archive_id: int,
  1006. content_hash: str | None = None,
  1007. print_name: str | None = None,
  1008. makerworld_model_id: str | None = None,
  1009. ) -> list[dict]:
  1010. """Find duplicate archives based on hash or name matching.
  1011. Returns list of dicts with id, print_name, created_at, match_type.
  1012. """
  1013. duplicates = []
  1014. # First, find exact matches by content hash
  1015. if content_hash:
  1016. result = await self.db.execute(
  1017. select(PrintArchive)
  1018. .where(
  1019. and_(
  1020. PrintArchive.content_hash == content_hash,
  1021. PrintArchive.id != archive_id,
  1022. PrintArchive.deleted_at.is_(None),
  1023. )
  1024. )
  1025. .order_by(PrintArchive.created_at.desc())
  1026. .limit(10)
  1027. )
  1028. for archive in result.scalars().all():
  1029. duplicates.append(
  1030. {
  1031. "id": archive.id,
  1032. "print_name": archive.print_name,
  1033. "created_at": archive.created_at,
  1034. "match_type": "exact",
  1035. }
  1036. )
  1037. # Then, find similar matches by print name or MakerWorld ID
  1038. # Prefer strict name+hash matching when hash exists; fallback to name-only for legacy/manual
  1039. # archives that may not have a content_hash.
  1040. if print_name or makerworld_model_id:
  1041. conditions = [PrintArchive.id != archive_id, PrintArchive.deleted_at.is_(None)]
  1042. name_conditions = []
  1043. if print_name:
  1044. if content_hash:
  1045. # Match if print names are similar AND have the same hash (same file)
  1046. name_conditions.append(
  1047. and_(PrintArchive.print_name.ilike(print_name), PrintArchive.content_hash == content_hash)
  1048. )
  1049. else:
  1050. # Fallback for archives without hash data: match by print name only.
  1051. name_conditions.append(PrintArchive.print_name.ilike(print_name))
  1052. if makerworld_model_id:
  1053. # Match by MakerWorld model ID stored in extra_data
  1054. from backend.app.core.db_dialect import is_sqlite
  1055. if is_sqlite():
  1056. from sqlalchemy import func
  1057. name_conditions.append(
  1058. func.json_extract(PrintArchive.extra_data, "$.makerworld_model_id") == str(makerworld_model_id)
  1059. )
  1060. else:
  1061. name_conditions.append(
  1062. text("(extra_data::jsonb->>'makerworld_model_id') = :mw_id").bindparams(
  1063. mw_id=str(makerworld_model_id)
  1064. )
  1065. )
  1066. if name_conditions:
  1067. conditions.append(or_(*name_conditions))
  1068. result = await self.db.execute(
  1069. select(PrintArchive).where(and_(*conditions)).order_by(PrintArchive.created_at.desc()).limit(10)
  1070. )
  1071. for archive in result.scalars().all():
  1072. # Don't add if already in duplicates (exact match)
  1073. if not any(d["id"] == archive.id for d in duplicates):
  1074. duplicates.append(
  1075. {
  1076. "id": archive.id,
  1077. "print_name": archive.print_name,
  1078. "created_at": archive.created_at,
  1079. "match_type": "similar",
  1080. }
  1081. )
  1082. return duplicates
  1083. async def archive_print(
  1084. self,
  1085. printer_id: int | None,
  1086. source_file: Path,
  1087. print_data: dict | None = None,
  1088. created_by_id: int | None = None,
  1089. original_filename: str | None = None,
  1090. project_id: int | None = None,
  1091. cost_center_id: int | None = None,
  1092. subtask_id: str | None = None,
  1093. prefer_filename_for_name: bool = False,
  1094. plate_id: int | None = None,
  1095. library_file_id: int | None = None,
  1096. slicer_ams_mapping: list[int] | None = None,
  1097. slicer_ams_mapping_printer_id: int | None = None,
  1098. update_archive_id: int | None = None,
  1099. ) -> PrintArchive | None:
  1100. """Archive a 3MF file with metadata.
  1101. Args:
  1102. printer_id: ID of the printer (optional)
  1103. source_file: Path to the 3MF file
  1104. print_data: Print data from MQTT (optional)
  1105. created_by_id: User ID who created this archive (optional, for user tracking)
  1106. original_filename: Original human-readable filename (optional, for library files
  1107. stored with UUID names)
  1108. project_id: Project to associate this archive with (optional, set when triggered
  1109. from the project view)
  1110. library_file_id: Library file this run was dispatched from (optional,
  1111. set by the queue scheduler — powers per-file project progress, #1897)
  1112. subtask_id: MQTT-provided task identifier (optional). Used to match an
  1113. existing archive across a backend restart mid-print so the
  1114. original row can be resumed instead of cancelled (#972).
  1115. prefer_filename_for_name: When True, use the uploaded filename stem as the
  1116. archive's display name even if the 3MF embeds a `print_name` in its
  1117. metadata. Used by virtual-printer flows so users who rename a job in
  1118. BambuStudio's "send to printer" dialog see that name instead of the
  1119. creator-baked title (#1152).
  1120. slicer_ams_mapping: The slicer's own live-resolved AMS-slot pick, to persist
  1121. onto `extra_data.slicer_ams_mapping` for a later reprint to reuse. Deliberately
  1122. a distinct parameter, not read off `print_data["ams_mapping"]` — that key is
  1123. populated on every MQTT print-start callback regardless of source (bambu_mqtt's
  1124. request-topic interception captures it for slicer-direct LAN prints too), so
  1125. promoting it unconditionally would stamp every archive on installs with no
  1126. virtual printer at all. Callers that gate this behind an opt-in (the VP-queue
  1127. "Save AMS mapping" toggle) pass it explicitly; everyone else leaves it unset.
  1128. slicer_ams_mapping_printer_id: The printer `slicer_ams_mapping`'s tray IDs were
  1129. resolved against. Required alongside `slicer_ams_mapping` — a global tray ID
  1130. only means something relative to one printer's specific AMS layout, so a
  1131. mapping saved without knowing which printer it came from can't be safely
  1132. reused later on any printer, including the same one (there'd be no way to
  1133. tell). A model-based VP with no fixed target printer has no valid value to
  1134. pass here and must leave both params unset.
  1135. update_archive_id: Fill in an existing archive row instead of adding one.
  1136. Used to upgrade a no-3MF fallback archive once the file finally arrives
  1137. (#2957). Everything above the row itself — the copy, the parse, the
  1138. thumbnail, the cost — is exactly what a fresh archive does; only the
  1139. destination differs. The row must keep its id: the energy-start reading,
  1140. the timelapse session, ``_active_prints``, the start notification and any
  1141. queue link were all written against it while the print was running, and a
  1142. second row would orphan every one of them. Fields the fallback path
  1143. already established from MQTT (``started_at``, ``subtask_id``,
  1144. ``created_by_id``, ``project_id``) are left alone; the 3MF has nothing
  1145. better to say about them.
  1146. """
  1147. # Verify printer exists if specified
  1148. if printer_id is not None:
  1149. result = await self.db.execute(select(Printer).where(Printer.id == printer_id))
  1150. printer = result.scalar_one_or_none()
  1151. if not printer:
  1152. return None
  1153. # Create archive directory structure
  1154. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  1155. display_stem = resolve_display_stem(original_filename if original_filename else source_file.name)
  1156. archive_name = f"{timestamp}_{display_stem}"
  1157. # Use "unassigned" folder for archives without a printer
  1158. printer_folder = str(printer_id) if printer_id is not None else "unassigned"
  1159. archive_dir = (
  1160. settings.archive_dir / printer_folder / archive_name
  1161. ) # 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
  1162. archive_dir.mkdir(parents=True, exist_ok=True)
  1163. # Copy 3MF file with an explicit fsync'd loop (avoids a sendfile
  1164. # short-read quirk that silently truncated 3MF archives on some
  1165. # platforms — see _copy_and_fsync and #1032).
  1166. dest_file = archive_dir / source_file.name
  1167. _copy_and_fsync(source_file, dest_file)
  1168. # If we just archived a 3MF, verify the dest is a valid ZIP before
  1169. # going any further. Staying quiet here is how #1032 escaped review —
  1170. # the archive row was written but every later zipfile.ZipFile() call
  1171. # on the dest failed with "File is not a zip file".
  1172. if (
  1173. source_file.suffix.lower() == ".3mf"
  1174. and zipfile.is_zipfile(source_file)
  1175. and not zipfile.is_zipfile(dest_file)
  1176. ):
  1177. try:
  1178. src_size = source_file.stat().st_size
  1179. dst_size = dest_file.stat().st_size
  1180. except OSError:
  1181. src_size = dst_size = -1
  1182. logger.error(
  1183. "Archive copy corrupted 3MF: src=%s (%s bytes, valid ZIP) -> dst=%s (%s bytes, NOT a ZIP). Refusing to create archive row.",
  1184. source_file,
  1185. src_size,
  1186. dest_file,
  1187. dst_size,
  1188. )
  1189. # Narrow cleanup: remove only the truncated file and the archive
  1190. # directory if it's now empty. archive_dir was created with
  1191. # exist_ok=True so it could in theory pre-date this call (e.g.
  1192. # same-second same-filename collision); rmtree would be too broad.
  1193. try:
  1194. dest_file.unlink()
  1195. except OSError:
  1196. pass
  1197. try:
  1198. archive_dir.rmdir()
  1199. except OSError:
  1200. pass # directory not empty — leave untouched
  1201. return None
  1202. # Compute content hash for duplicate detection
  1203. content_hash = self.compute_file_hash(dest_file)
  1204. # Extract plate number from filename (e.g., "plate_5" from "/data/Metadata/plate_5.gcode")
  1205. plate_number = None
  1206. if print_data:
  1207. filename = print_data.get("filename", "")
  1208. match = re.search(r"plate_(\d+)", filename)
  1209. if match:
  1210. plate_number = int(match.group(1))
  1211. # Parse 3MF metadata
  1212. parser = ThreeMFParser(dest_file, plate_number=plate_number)
  1213. metadata = parser.parse()
  1214. # Save thumbnail if present
  1215. thumbnail_path = None
  1216. if "_thumbnail_data" in metadata:
  1217. thumb_file = archive_dir / f"thumbnail{metadata['_thumbnail_ext']}"
  1218. thumb_file.write_bytes(metadata["_thumbnail_data"])
  1219. thumbnail_path = str(thumb_file.relative_to(settings.base_dir))
  1220. del metadata["_thumbnail_data"]
  1221. del metadata["_thumbnail_ext"]
  1222. # Merge with print data from MQTT
  1223. if print_data:
  1224. metadata["_print_data"] = print_data
  1225. # Promote the slicer's own live-resolved AMS-slot pick, when the caller
  1226. # explicitly opted in (see the `slicer_ams_mapping` param docstring for
  1227. # why this is NOT read off `print_data["ams_mapping"]`), to a stable
  1228. # top-level extra_data key. Lets a later reprint reuse the exact tray
  1229. # the user picked/BambuStudio auto-matched at slice time instead of the
  1230. # scheduler re-deriving one from just the file's static type/color,
  1231. # which can land on the wrong physical spool when that match isn't
  1232. # unique. Top-level (not nested under the `_print_data` diagnostic bag)
  1233. # so API consumers have a single stable path:
  1234. # `archive.extra_data.slicer_ams_mapping`. Stored together with the
  1235. # printer it was resolved against — see `slicer_ams_mapping_printer_id`
  1236. # param docstring — so a later reprint can tell whether it's even
  1237. # applicable before trying to reuse it.
  1238. if slicer_ams_mapping and slicer_ams_mapping_printer_id is not None:
  1239. metadata["slicer_ams_mapping"] = {
  1240. "mapping": slicer_ams_mapping,
  1241. "printer_id": slicer_ams_mapping_printer_id,
  1242. }
  1243. # Determine status and timestamps
  1244. status = print_data.get("status", "completed") if print_data else "archived"
  1245. started_at = datetime.now(timezone.utc) if status == "printing" else None
  1246. completed_at = datetime.now(timezone.utc) if status in ("completed", "failed", "archived") else None
  1247. # Calculate cost based on filament usage and type
  1248. cost = None
  1249. filament_grams = metadata.get("filament_used_grams")
  1250. filament_type = metadata.get("filament_type")
  1251. if filament_grams and filament_type:
  1252. # For multi-material prints, use the first filament type for cost calculation
  1253. primary_type = filament_type.split(",")[0].strip()
  1254. # Look up filament cost_per_kg from database
  1255. filament_result = await self.db.execute(select(Filament).where(Filament.type == primary_type).limit(1))
  1256. filament = filament_result.scalar_one_or_none()
  1257. if filament:
  1258. cost = round((filament_grams / 1000) * filament.cost_per_kg, 2)
  1259. else:
  1260. # Use default filament cost from settings
  1261. from backend.app.api.routes.settings import get_setting
  1262. default_cost_setting = await get_setting(self.db, "default_filament_cost")
  1263. default_cost_per_kg = float(default_cost_setting) if default_cost_setting else 25.0
  1264. cost = round((filament_grams / 1000) * default_cost_per_kg, 2)
  1265. # Calculate quantity from printable objects count
  1266. # printable_objects is a dict of {identify_id: name} for non-skipped objects
  1267. quantity = 1 # Default to 1
  1268. printable_objects = metadata.get("printable_objects")
  1269. if printable_objects and isinstance(printable_objects, dict):
  1270. quantity = len(printable_objects)
  1271. logger.debug("Auto-detected %s parts from 3MF printable objects", quantity)
  1272. # Recovery of an existing fallback row: assign the freshly-parsed values
  1273. # onto it rather than adding a second archive for the same print (#2957).
  1274. if update_archive_id is not None:
  1275. existing = await self.db.get(PrintArchive, update_archive_id)
  1276. if existing is None:
  1277. logger.warning("archive_print: archive %s to update no longer exists", update_archive_id)
  1278. return None
  1279. # `metadata` is freshly parsed from the 3MF, so assigning it drops
  1280. # the row's `no_3mf_available` / `no_3mf_reason` markers as a side
  1281. # effect — which is correct, the archive is no longer a fallback,
  1282. # and it is what stops the Archives banner counting it.
  1283. # `_print_data` is diagnostic history rather than something the 3MF
  1284. # knows about: keep the row's copy for a caller that passed no
  1285. # print_data of its own.
  1286. merged = dict(metadata)
  1287. preserved = (existing.extra_data or {}).get("_print_data")
  1288. if preserved is not None and "_print_data" not in merged:
  1289. merged["_print_data"] = preserved
  1290. # A record that this row started life without a 3MF, which the
  1291. # dropped markers no longer say.
  1292. merged["recovered_no_3mf"] = True
  1293. existing.filename = original_filename or source_file.name
  1294. existing.file_path = str(dest_file.relative_to(settings.base_dir))
  1295. existing.file_size = dest_file.stat().st_size
  1296. existing.content_hash = content_hash
  1297. existing.thumbnail_path = thumbnail_path
  1298. existing.print_name = (
  1299. clean_display_name(display_stem)
  1300. if prefer_filename_for_name
  1301. else (clean_display_name(metadata.get("print_name")) or clean_display_name(display_stem))
  1302. )
  1303. # Only overwrite what the 3MF actually knows. A fallback archive
  1304. # recovered mid-print has a real print_time_seconds from MQTT and a
  1305. # filament type/colour from the AMS; a 3MF that omits a field must
  1306. # not blank them back out.
  1307. for field in (
  1308. "print_time_seconds",
  1309. "filament_used_grams",
  1310. "filament_type",
  1311. "filament_color",
  1312. "layer_height",
  1313. "total_layers",
  1314. "nozzle_diameter",
  1315. "bed_temperature",
  1316. "bed_type",
  1317. "nozzle_temperature",
  1318. "sliced_for_model",
  1319. "makerworld_url",
  1320. "designer",
  1321. ):
  1322. value = metadata.get(field)
  1323. if value is not None:
  1324. setattr(existing, field, value)
  1325. if cost is not None:
  1326. existing.cost = cost
  1327. existing.quantity = quantity
  1328. existing.extra_data = merged
  1329. if plate_id is not None:
  1330. existing.plate_id = plate_id
  1331. if library_file_id is not None:
  1332. existing.library_file_id = library_file_id
  1333. await self.db.commit()
  1334. await self.db.refresh(existing)
  1335. return existing
  1336. # Create archive record
  1337. archive = PrintArchive(
  1338. printer_id=printer_id,
  1339. filename=original_filename or source_file.name,
  1340. file_path=str(dest_file.relative_to(settings.base_dir)),
  1341. file_size=dest_file.stat().st_size,
  1342. content_hash=content_hash,
  1343. thumbnail_path=thumbnail_path,
  1344. # clean_display_name because the 3MF's own metadata reaches this
  1345. # verbatim, and a control character in it renders nowhere and
  1346. # truncates somewhere (#2832). The schema does the same for names
  1347. # arriving over the API. Cleaned before the fallback rather than
  1348. # after it, so an embedded name that is only whitespace still falls
  1349. # through to the filename instead of leaving the archive nameless.
  1350. print_name=(
  1351. clean_display_name(display_stem)
  1352. if prefer_filename_for_name
  1353. else (clean_display_name(metadata.get("print_name")) or clean_display_name(display_stem))
  1354. ),
  1355. print_time_seconds=metadata.get("print_time_seconds"),
  1356. filament_used_grams=metadata.get("filament_used_grams"),
  1357. filament_type=metadata.get("filament_type"),
  1358. filament_color=metadata.get("filament_color"),
  1359. layer_height=metadata.get("layer_height"),
  1360. total_layers=metadata.get("total_layers"),
  1361. nozzle_diameter=metadata.get("nozzle_diameter"),
  1362. bed_temperature=metadata.get("bed_temperature"),
  1363. bed_type=metadata.get("bed_type"),
  1364. nozzle_temperature=metadata.get("nozzle_temperature"),
  1365. sliced_for_model=metadata.get("sliced_for_model"),
  1366. makerworld_url=metadata.get("makerworld_url"),
  1367. designer=metadata.get("designer"),
  1368. status=status,
  1369. started_at=started_at,
  1370. completed_at=completed_at,
  1371. cost=cost,
  1372. quantity=quantity,
  1373. extra_data=metadata,
  1374. created_by_id=created_by_id,
  1375. project_id=project_id,
  1376. library_file_id=library_file_id,
  1377. cost_center_id=cost_center_id,
  1378. subtask_id=subtask_id,
  1379. plate_id=plate_id,
  1380. )
  1381. self.db.add(archive)
  1382. await self.db.commit()
  1383. await self.db.refresh(archive)
  1384. return archive
  1385. async def get_archive(self, archive_id: int) -> PrintArchive | None:
  1386. """Get an archive by ID with relationships loaded."""
  1387. from sqlalchemy.orm import selectinload
  1388. result = await self.db.execute(
  1389. select(PrintArchive)
  1390. .options(selectinload(PrintArchive.created_by), selectinload(PrintArchive.project))
  1391. .where(PrintArchive.id == archive_id)
  1392. )
  1393. return result.scalar_one_or_none()
  1394. async def update_archive_status(
  1395. self,
  1396. archive_id: int,
  1397. status: str,
  1398. completed_at: datetime | None = None,
  1399. failure_reason: str | None = None,
  1400. ) -> bool:
  1401. """Update the status of an archive."""
  1402. archive = await self.get_archive(archive_id)
  1403. if not archive:
  1404. return False
  1405. archive.status = status
  1406. if completed_at:
  1407. archive.completed_at = completed_at
  1408. if failure_reason:
  1409. archive.failure_reason = failure_reason
  1410. await self.db.commit()
  1411. return True
  1412. async def list_archives(
  1413. self,
  1414. printer_id: int | None = None,
  1415. project_id: int | None = None,
  1416. date_from: date | None = None,
  1417. date_to: date | None = None,
  1418. limit: int = 50,
  1419. offset: int = 0,
  1420. visible_to_user_id: int | None = None,
  1421. ) -> list[PrintArchive]:
  1422. """List archives with optional filtering.
  1423. ``visible_to_user_id`` scopes results to archives that user owns. Used
  1424. when the caller has ARCHIVES_READ_OWN but not ARCHIVES_READ_ALL — pass
  1425. ``None`` to skip the filter (caller has read-all or auth is disabled).
  1426. """
  1427. from sqlalchemy.orm import selectinload
  1428. query = (
  1429. select(PrintArchive)
  1430. .options(selectinload(PrintArchive.project), selectinload(PrintArchive.created_by))
  1431. # Hide soft-deleted rows from the listings (#1343). The stats
  1432. # endpoint deliberately does NOT add this filter so deleted
  1433. # archives keep contributing to Quick Stats.
  1434. .where(PrintArchive.deleted_at.is_(None))
  1435. .order_by(PrintArchive.created_at.desc())
  1436. )
  1437. if printer_id:
  1438. query = query.where(PrintArchive.printer_id == printer_id)
  1439. if project_id:
  1440. query = query.where(PrintArchive.project_id == project_id)
  1441. if date_from:
  1442. dt_from = datetime.combine(date_from, time.min, tzinfo=timezone.utc)
  1443. query = query.where(PrintArchive.created_at >= dt_from)
  1444. if date_to:
  1445. dt_to = datetime.combine(date_to, time.max, tzinfo=timezone.utc)
  1446. query = query.where(PrintArchive.created_at <= dt_to)
  1447. if visible_to_user_id is not None:
  1448. query = query.where(PrintArchive.created_by_id == visible_to_user_id)
  1449. query = query.limit(limit).offset(offset)
  1450. result = await self.db.execute(query)
  1451. return list(result.scalars().all())
  1452. async def soft_delete_archive(self, archive_id: int) -> bool:
  1453. """Soft-delete an archive (#1343).
  1454. Removes the archive's files from disk (it disappears from the listings
  1455. and frees the storage) but flips the row's ``deleted_at`` so the stats
  1456. endpoint keeps counting its filament / energy / time / cost. The user
  1457. can opt into a hard delete via the "Also remove from statistics"
  1458. checkbox in the delete dialog — that path calls ``delete_archive``
  1459. instead and removes the row entirely.
  1460. """
  1461. archive = await self.get_archive(archive_id)
  1462. if not archive:
  1463. return False
  1464. if archive.deleted_at is not None:
  1465. # Already soft-deleted; nothing to do. The files were purged on
  1466. # the first soft-delete pass so there is nothing left on disk.
  1467. return True
  1468. dir_to_delete = self._resolve_archive_dir_for_delete(archive)
  1469. await _null_print_log_thumbnail_paths(self.db, archive_id)
  1470. await _delete_related_queue_items(self.db, archive_id)
  1471. archive.deleted_at = datetime.now(timezone.utc)
  1472. await self.db.commit()
  1473. if dir_to_delete:
  1474. shutil.rmtree(dir_to_delete, ignore_errors=True)
  1475. return True
  1476. def _resolve_archive_dir_for_delete(self, archive: PrintArchive) -> Path | None:
  1477. """Return the on-disk directory that backs *archive*, after the same
  1478. two safety checks ``delete_archive`` enforces.
  1479. Extracted so soft-delete and hard-delete share the path-resolution
  1480. rules. Returns ``None`` when nothing should be removed from disk
  1481. (no file_path, path outside archive_dir, or path not deep enough).
  1482. """
  1483. if not archive.file_path or not archive.file_path.strip():
  1484. logger.error(
  1485. f"SECURITY: Refusing to delete files for archive {archive.id} - "
  1486. f"file_path is empty or invalid: '{archive.file_path}'"
  1487. )
  1488. return None
  1489. file_path = settings.base_dir / archive.file_path
  1490. if not file_path.exists():
  1491. return None
  1492. archive_dir = file_path.parent
  1493. try:
  1494. relative_path = archive_dir.resolve().relative_to(settings.archive_dir.resolve())
  1495. except ValueError:
  1496. logger.error(
  1497. f"SECURITY: Refusing to delete archive {archive.id} - "
  1498. f"path {archive_dir} is outside archive directory {settings.archive_dir}"
  1499. )
  1500. return None
  1501. if len(relative_path.parts) < 1:
  1502. logger.error(
  1503. f"SECURITY: Refusing to delete archive {archive.id} - "
  1504. f"path {archive_dir} is not deep enough inside archive directory"
  1505. )
  1506. return None
  1507. return archive_dir
  1508. async def delete_archive(self, archive_id: int) -> bool:
  1509. """Delete an archive and its files."""
  1510. archive = await self.get_archive(archive_id)
  1511. if not archive:
  1512. return False
  1513. # Resolve the directory to delete BEFORE committing the DB change
  1514. dir_to_delete: Path | None = None
  1515. if archive.file_path and archive.file_path.strip():
  1516. file_path = settings.base_dir / archive.file_path
  1517. if file_path.exists():
  1518. archive_dir = file_path.parent
  1519. # Safety check 1: archive_dir must be inside archive_dir
  1520. try:
  1521. archive_dir.resolve().relative_to(settings.archive_dir.resolve())
  1522. except ValueError:
  1523. logger.error(
  1524. f"SECURITY: Refusing to delete archive {archive_id} - "
  1525. f"path {archive_dir} is outside archive directory {settings.archive_dir}"
  1526. )
  1527. await self.db.delete(archive)
  1528. await self.db.commit()
  1529. return True
  1530. # Safety check 2: archive_dir must be at least 1 level deep inside archive_dir
  1531. try:
  1532. relative_path = archive_dir.resolve().relative_to(settings.archive_dir.resolve())
  1533. if len(relative_path.parts) < 1:
  1534. logger.error(
  1535. f"SECURITY: Refusing to delete archive {archive_id} - "
  1536. f"path {archive_dir} is not deep enough inside archive directory"
  1537. )
  1538. await self.db.delete(archive)
  1539. await self.db.commit()
  1540. return True
  1541. except ValueError:
  1542. pass # Already handled above
  1543. dir_to_delete = archive_dir
  1544. else:
  1545. logger.error(
  1546. f"SECURITY: Refusing to delete files for archive {archive_id} - "
  1547. f"file_path is empty or invalid: '{archive.file_path}'"
  1548. )
  1549. # NULL stale thumbnail_path on linked PrintLogEntries before the FK
  1550. # SET-NULL cascade fires. The on-disk file is about to be removed by
  1551. # the rmtree below, so the path on any surviving log entry (archive_id
  1552. # gets SET NULL by the FK) would otherwise point at a missing file
  1553. # and produce 404 storms in the print-log view (#1348-followup).
  1554. await _null_print_log_thumbnail_paths(self.db, archive_id)
  1555. # Delete database record FIRST — if the commit fails (e.g. database locked
  1556. # during concurrent bulk deletes), the files stay on disk and nothing is lost.
  1557. await self.db.delete(archive)
  1558. await self.db.commit()
  1559. # Only delete files AFTER the DB commit succeeds to avoid orphaned records
  1560. if dir_to_delete:
  1561. shutil.rmtree(dir_to_delete, ignore_errors=True)
  1562. return True
  1563. async def attach_timelapse(
  1564. self,
  1565. archive_id: int,
  1566. timelapse_data: bytes,
  1567. filename: str = "timelapse.mp4",
  1568. ) -> bool:
  1569. """Attach a timelapse video to an archive.
  1570. Non-MP4 videos (e.g. AVI from P1S) are saved as-is and a background
  1571. task converts them to MP4 for browser compatibility.
  1572. """
  1573. import asyncio
  1574. archive = await self.get_archive(archive_id)
  1575. if not archive:
  1576. return False
  1577. # Where this archive's files live. Deliberately the shared helper: an
  1578. # archive created without a 3MF has ``file_path == ""``, and deriving the
  1579. # directory here as ``(base_dir / "").parent`` resolved to the parent of
  1580. # base_dir — outside the data directory entirely. In Docker that is /app,
  1581. # so the write failed with EACCES and the timelapse was retried and
  1582. # discarded 25 times; where the parent happens to be writable it
  1583. # succeeded, dropped a stray video next to the install, and then failed
  1584. # anyway on the relative_to() below. Every H2-series and P2S print sent
  1585. # from the slicer takes that path, because the file goes to internal
  1586. # storage and no 3MF can be fetched.
  1587. archive_dir = resolve_archive_dir(archive)
  1588. # Save timelapse - use thread pool to avoid blocking event loop
  1589. # (timelapse files can be 100MB+, sync write blocks for seconds).
  1590. # `filename` ultimately comes from a printer's FTP listing (compromised-
  1591. # printer threat model) or a query param on /archives/{id}/timelapse/select;
  1592. # the safe-join helper rejects ``..`` segments and absolute paths so a
  1593. # crafted name can't escape the archive directory. Use http=False so a
  1594. # service-layer reject surfaces as a return False (matching the existing
  1595. # not-found contract) rather than a 400 raised from inside a background
  1596. # task.
  1597. try:
  1598. timelapse_file = safe_join_under(archive_dir, filename, http=False)
  1599. except PathTraversalError:
  1600. logger.warning(
  1601. "Refusing to attach timelapse with unsafe filename %r to archive %s",
  1602. filename,
  1603. archive_id,
  1604. )
  1605. return False
  1606. # Created only once the name has been vetted, so a rejected filename
  1607. # leaves nothing behind. A no-3MF archive has never had a directory of
  1608. # its own, and the timelapse can be the first thing to want one.
  1609. await asyncio.to_thread(lambda: timelapse_file.parent.mkdir(parents=True, exist_ok=True))
  1610. await asyncio.to_thread(timelapse_file.write_bytes, timelapse_data)
  1611. # Update archive record
  1612. archive.timelapse_path = str(timelapse_file.relative_to(settings.base_dir))
  1613. await self.db.commit()
  1614. # For non-MP4 videos (e.g. AVI from P1S), kick off background conversion
  1615. if not filename.lower().endswith(".mp4"):
  1616. spawn_background_task(
  1617. _convert_timelapse_to_mp4(archive_id, timelapse_file),
  1618. name=f"timelapse-convert-{archive_id}",
  1619. )
  1620. return True
  1621. async def _convert_timelapse_to_mp4(archive_id: int, source_path: Path) -> None:
  1622. """Background task: convert non-MP4 timelapse (e.g. AVI from P1S) to MP4.
  1623. Runs with low CPU priority (-threads 1, nice) so it doesn't starve
  1624. other processes on resource-constrained devices like Raspberry Pi.
  1625. """
  1626. import asyncio
  1627. from backend.app.core.database import async_session
  1628. from backend.app.services.camera import get_ffmpeg_path
  1629. logger = logging.getLogger(__name__)
  1630. ffmpeg = get_ffmpeg_path()
  1631. if not ffmpeg:
  1632. logger.info(
  1633. "FFmpeg not available, skipping timelapse conversion for archive %s (file saved as %s)",
  1634. archive_id,
  1635. source_path.suffix,
  1636. )
  1637. return
  1638. mp4_path = source_path.with_suffix(".mp4")
  1639. try:
  1640. cmd = [
  1641. ffmpeg,
  1642. "-y",
  1643. "-i",
  1644. str(source_path),
  1645. "-c:v",
  1646. "libx264",
  1647. "-preset",
  1648. "fast",
  1649. "-crf",
  1650. "23",
  1651. "-threads",
  1652. "1",
  1653. "-movflags",
  1654. "+faststart",
  1655. str(mp4_path),
  1656. ]
  1657. # Try with nice for lower CPU priority (standard on Linux/macOS)
  1658. try:
  1659. process = await asyncio.create_subprocess_exec(
  1660. "nice",
  1661. "-n",
  1662. "19",
  1663. *cmd,
  1664. stdout=asyncio.subprocess.PIPE,
  1665. stderr=asyncio.subprocess.PIPE,
  1666. )
  1667. except FileNotFoundError:
  1668. # nice not available (e.g. Windows), run without
  1669. process = await asyncio.create_subprocess_exec(
  1670. *cmd,
  1671. stdout=asyncio.subprocess.PIPE,
  1672. stderr=asyncio.subprocess.PIPE,
  1673. )
  1674. _, stderr = await process.communicate()
  1675. if process.returncode != 0:
  1676. logger.warning(
  1677. "Timelapse conversion failed for archive %s: %s",
  1678. archive_id,
  1679. stderr.decode()[-500:],
  1680. )
  1681. if mp4_path.exists():
  1682. mp4_path.unlink()
  1683. return
  1684. # Update DB path to the new MP4 file
  1685. async with async_session() as db:
  1686. from backend.app.models.archive import PrintArchive
  1687. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1688. archive = result.scalar_one_or_none()
  1689. if archive:
  1690. archive.timelapse_path = str(mp4_path.relative_to(settings.base_dir))
  1691. await db.commit()
  1692. # Remove original non-MP4 file
  1693. if source_path.exists():
  1694. source_path.unlink()
  1695. logger.info(
  1696. "Converted timelapse to MP4 for archive %s (%s → %s)",
  1697. archive_id,
  1698. source_path.name,
  1699. mp4_path.name,
  1700. )
  1701. except Exception as e:
  1702. logger.warning("Timelapse conversion error for archive %s: %s", archive_id, e)
  1703. if mp4_path.exists():
  1704. mp4_path.unlink()