archive.py 86 KB

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