archive.py 89 KB

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