archive.py 97 KB

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