archive.py 89 KB

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