archive.py 91 KB

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